Show entry name in one more message.
[rover.git] / rover.c
blobdd127a64731249bc200db720dd1d4436cabc6cab
1 #define _XOPEN_SOURCE 700
2 #define _XOPEN_SOURCE_EXTENDED
3 #define _FILE_OFFSET_BITS 64
5 #include <stdlib.h>
6 #include <stdint.h>
7 #include <ctype.h>
8 #include <wchar.h>
9 #include <wctype.h>
10 #include <string.h>
11 #include <sys/types.h> /* pid_t, ... */
12 #include <stdio.h>
13 #include <limits.h> /* PATH_MAX */
14 #include <locale.h> /* setlocale(), LC_ALL */
15 #include <unistd.h> /* chdir(), getcwd(), read(), close(), ... */
16 #include <dirent.h> /* DIR, struct dirent, opendir(), ... */
17 #include <sys/stat.h>
18 #include <fcntl.h> /* open() */
19 #include <sys/wait.h> /* waitpid() */
20 #include <signal.h> /* struct sigaction, sigaction() */
21 #include <errno.h>
22 #include <stdarg.h>
23 #include <curses.h>
25 #include "config.h"
27 /* String buffers. */
28 #define BUFLEN PATH_MAX
29 static char BUF1[BUFLEN];
30 static char BUF2[BUFLEN];
31 static char INPUT[BUFLEN];
32 static wchar_t WBUF[BUFLEN];
34 /* Argument buffers for execvp(). */
35 #define MAXARGS 256
36 static char *ARGS[MAXARGS];
38 /* Listing view parameters. */
39 #define HEIGHT (LINES-4)
40 #define STATUSPOS (COLS-16)
42 /* Listing view flags. */
43 #define SHOW_FILES 0x01u
44 #define SHOW_DIRS 0x02u
45 #define SHOW_HIDDEN 0x04u
47 /* Marks parameters. */
48 #define BULK_INIT 5
49 #define BULK_THRESH 256
51 /* Information associated to each entry in listing. */
52 typedef struct Row {
53 char *name;
54 off_t size;
55 mode_t mode;
56 int islink;
57 int marked;
58 } Row;
60 /* Dynamic array of marked entries. */
61 typedef struct Marks {
62 char dirpath[PATH_MAX];
63 int bulk;
64 int nentries;
65 char **entries;
66 } Marks;
68 /* Line editing state. */
69 typedef struct Edit {
70 wchar_t buffer[BUFLEN+1];
71 int left, right;
72 } Edit;
74 /* Each tab only stores the following information. */
75 typedef struct Tab {
76 int scroll;
77 int esel;
78 uint8_t flags;
79 char cwd[PATH_MAX];
80 } Tab;
82 /* Global state. */
83 static struct Rover {
84 int tab;
85 int nfiles;
86 Row *rows;
87 WINDOW *window;
88 Marks marks;
89 Edit edit;
90 int edit_scroll;
91 volatile sig_atomic_t pending_winch;
92 Tab tabs[10];
93 } rover;
95 /* Macros for accessing global state. */
96 #define ENAME(I) rover.rows[I].name
97 #define ESIZE(I) rover.rows[I].size
98 #define EMODE(I) rover.rows[I].mode
99 #define ISLINK(I) rover.rows[I].islink
100 #define MARKED(I) rover.rows[I].marked
101 #define SCROLL rover.tabs[rover.tab].scroll
102 #define ESEL rover.tabs[rover.tab].esel
103 #define FLAGS rover.tabs[rover.tab].flags
104 #define CWD rover.tabs[rover.tab].cwd
106 /* Helpers. */
107 #define MIN(A, B) ((A) < (B) ? (A) : (B))
108 #define MAX(A, B) ((A) > (B) ? (A) : (B))
109 #define ISDIR(E) (strchr((E), '/') != NULL)
111 /* Line Editing Macros. */
112 #define EDIT_FULL(E) ((E).left == (E).right)
113 #define EDIT_CAN_LEFT(E) ((E).left)
114 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
115 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
116 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
117 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
118 #define EDIT_BACKSPACE(E) (E).left--
119 #define EDIT_DELETE(E) (E).right++
120 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
122 typedef enum EditStat {CONTINUE, CONFIRM, CANCEL} EditStat;
123 typedef enum Color {DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK} Color;
124 typedef int (*PROCESS)(const char *path);
126 static void
127 init_marks(Marks *marks)
129 strcpy(marks->dirpath, "");
130 marks->bulk = BULK_INIT;
131 marks->nentries = 0;
132 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
135 /* Unmark all entries. */
136 static void
137 mark_none(Marks *marks)
139 int i;
141 strcpy(marks->dirpath, "");
142 for (i = 0; i < marks->bulk && marks->nentries; i++)
143 if (marks->entries[i]) {
144 free(marks->entries[i]);
145 marks->entries[i] = NULL;
146 marks->nentries--;
148 if (marks->bulk > BULK_THRESH) {
149 /* Reset bulk to free some memory. */
150 free(marks->entries);
151 marks->bulk = BULK_INIT;
152 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
156 static void
157 add_mark(Marks *marks, char *dirpath, char *entry)
159 int i;
161 if (!strcmp(marks->dirpath, dirpath)) {
162 /* Append mark to directory. */
163 if (marks->nentries == marks->bulk) {
164 /* Expand bulk to accomodate new entry. */
165 int extra = marks->bulk / 2;
166 marks->bulk += extra; /* bulk *= 1.5; */
167 marks->entries = realloc(marks->entries,
168 marks->bulk * sizeof *marks->entries);
169 memset(&marks->entries[marks->nentries], 0,
170 extra * sizeof *marks->entries);
171 i = marks->nentries;
172 } else {
173 /* Search for empty slot (there must be one). */
174 for (i = 0; i < marks->bulk; i++)
175 if (!marks->entries[i])
176 break;
178 } else {
179 /* Directory changed. Discard old marks. */
180 mark_none(marks);
181 strcpy(marks->dirpath, dirpath);
182 i = 0;
184 marks->entries[i] = malloc(strlen(entry) + 1);
185 strcpy(marks->entries[i], entry);
186 marks->nentries++;
189 static void
190 del_mark(Marks *marks, char *entry)
192 int i;
194 if (marks->nentries > 1) {
195 for (i = 0; i < marks->bulk; i++)
196 if (marks->entries[i] && !strcmp(marks->entries[i], entry))
197 break;
198 free(marks->entries[i]);
199 marks->entries[i] = NULL;
200 marks->nentries--;
201 } else
202 mark_none(marks);
205 static void
206 free_marks(Marks *marks)
208 int i;
210 for (i = 0; i < marks->bulk && marks->nentries; i++)
211 if (marks->entries[i]) {
212 free(marks->entries[i]);
213 marks->nentries--;
215 free(marks->entries);
218 static void
219 handle_winch(int sig)
221 rover.pending_winch = 1;
224 static void
225 enable_handlers()
227 struct sigaction sa;
229 memset(&sa, 0, sizeof (struct sigaction));
230 sa.sa_handler = handle_winch;
231 sigaction(SIGWINCH, &sa, NULL);
234 static void
235 disable_handlers()
237 struct sigaction sa;
239 memset(&sa, 0, sizeof (struct sigaction));
240 sa.sa_handler = SIG_DFL;
241 sigaction(SIGWINCH, &sa, NULL);
244 static void update_view();
246 /* Handle any signals received since last call. */
247 static void
248 sync_signals()
250 if (rover.pending_winch) {
251 /* SIGWINCH received: resize application accordingly. */
252 delwin(rover.window);
253 endwin();
254 refresh();
255 clear();
256 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
257 if (HEIGHT < rover.nfiles && SCROLL + HEIGHT > rover.nfiles)
258 SCROLL = ESEL - HEIGHT;
259 update_view();
260 rover.pending_winch = 0;
264 /* This function must be used in place of getch().
265 It handles signals while waiting for user input. */
266 static int
267 rover_getch()
269 int ch;
271 while ((ch = getch()) == ERR)
272 sync_signals();
273 return ch;
276 /* This function must be used in place of get_wch().
277 It handles signals while waiting for user input. */
278 static int
279 rover_get_wch(wint_t *wch)
281 wint_t ret;
283 while ((ret = get_wch(wch)) == (wint_t) ERR)
284 sync_signals();
285 return ret;
288 /* Do a fork-exec to external program (e.g. $EDITOR). */
289 static void
290 spawn()
292 pid_t pid;
293 int status;
295 setenv("RVSEL", rover.nfiles ? ENAME(ESEL) : "", 1);
296 pid = fork();
297 if (pid > 0) {
298 /* fork() succeeded. */
299 disable_handlers();
300 endwin();
301 waitpid(pid, &status, 0);
302 enable_handlers();
303 kill(getpid(), SIGWINCH);
304 } else if (pid == 0) {
305 /* Child process. */
306 execvp(ARGS[0], ARGS);
310 /* Curses setup. */
311 static void
312 init_term()
314 setlocale(LC_ALL, "");
315 initscr();
316 cbreak(); /* Get one character at a time. */
317 timeout(100); /* For getch(). */
318 noecho();
319 nonl(); /* No NL->CR/NL on output. */
320 intrflush(stdscr, FALSE);
321 keypad(stdscr, TRUE);
322 curs_set(FALSE); /* Hide blinking cursor. */
323 if (has_colors()) {
324 short bg;
325 start_color();
326 #ifdef NCURSES_EXT_FUNCS
327 use_default_colors();
328 bg = -1;
329 #else
330 bg = COLOR_BLACK;
331 #endif
332 init_pair(RED, COLOR_RED, bg);
333 init_pair(GREEN, COLOR_GREEN, bg);
334 init_pair(YELLOW, COLOR_YELLOW, bg);
335 init_pair(BLUE, COLOR_BLUE, bg);
336 init_pair(CYAN, COLOR_CYAN, bg);
337 init_pair(MAGENTA, COLOR_MAGENTA, bg);
338 init_pair(WHITE, COLOR_WHITE, bg);
339 init_pair(BLACK, COLOR_BLACK, bg);
341 atexit((void (*)(void)) endwin);
342 enable_handlers();
345 /* Update the listing view. */
346 static void
347 update_view()
349 int i, j;
350 int numsize;
351 int ishidden, isdir;
352 int marking;
354 mvhline(0, 0, ' ', COLS);
355 attr_on(A_BOLD, NULL);
356 color_set(RVC_TABNUM, NULL);
357 mvaddch(0, COLS - 2, rover.tab + '0');
358 attr_off(A_BOLD, NULL);
359 if (rover.marks.nentries) {
360 numsize = snprintf(BUF1, BUFLEN, "%d", rover.marks.nentries);
361 color_set(RVC_MARKS, NULL);
362 mvaddstr(0, COLS - 3 - numsize, BUF1);
363 } else
364 numsize = -1;
365 color_set(RVC_CWD, NULL);
366 mbstowcs(WBUF, CWD, PATH_MAX);
367 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
368 wcolor_set(rover.window, RVC_BORDER, NULL);
369 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
370 ESEL = MIN(ESEL, rover.nfiles - 1);
371 /* Selection might not be visible, due to cursor wrapping or window
372 shrinking. In that case, the scroll must be moved to make it visible. */
373 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
374 marking = !strcmp(CWD, rover.marks.dirpath);
375 for (i = 0, j = SCROLL; i < HEIGHT && j < rover.nfiles; i++, j++) {
376 ishidden = ENAME(j)[0] == '.';
377 isdir = S_ISDIR(EMODE(j));
378 if (j == ESEL)
379 wattr_on(rover.window, A_REVERSE, NULL);
380 if (ISLINK(j))
381 wcolor_set(rover.window, RVC_LINK, NULL);
382 else if (ishidden)
383 wcolor_set(rover.window, RVC_HIDDEN, NULL);
384 else if (isdir)
385 wcolor_set(rover.window, RVC_DIR, NULL);
386 else
387 wcolor_set(rover.window, RVC_FILE, NULL);
388 if (!isdir) {
389 char *suffix, *suffixes = "BKMGTPEZY";
390 off_t human_size = ESIZE(j) * 10;
391 int length = mbstowcs(NULL, ENAME(j), 0);
392 for (suffix = suffixes; human_size >= 10240; suffix++)
393 human_size = (human_size + 512) / 1024;
394 if (*suffix == 'B')
395 swprintf(WBUF, PATH_MAX, L"%s%*d %c", ENAME(j),
396 (int) (COLS - length - 6),
397 (int) human_size / 10, *suffix);
398 else
399 swprintf(WBUF, PATH_MAX, L"%s%*d.%d %c", ENAME(j),
400 (int) (COLS - length - 8),
401 (int) human_size / 10, (int) human_size % 10, *suffix);
402 } else
403 mbstowcs(WBUF, ENAME(j), PATH_MAX);
404 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
405 mvwaddnwstr(rover.window, i + 1, 2, WBUF, COLS - 4);
406 if (marking && MARKED(j)) {
407 wcolor_set(rover.window, RVC_MARKS, NULL);
408 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
409 } else
410 mvwaddch(rover.window, i + 1, 1, ' ');
411 if (j == ESEL)
412 wattr_off(rover.window, A_REVERSE, NULL);
414 for (; i < HEIGHT; i++)
415 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
416 if (rover.nfiles > HEIGHT) {
417 int center, height;
418 center = (SCROLL + HEIGHT / 2) * HEIGHT / rover.nfiles;
419 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
420 if (!height) height = 1;
421 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
422 mvwvline(rover.window, center-height/2+1, COLS-1, RVS_SCROLLBAR, height);
424 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
425 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
426 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
427 if (!rover.nfiles)
428 strcpy(BUF2, "0/0");
429 else
430 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, rover.nfiles);
431 snprintf(BUF1+3, BUFLEN-3, "%12s", BUF2);
432 color_set(RVC_STATUS, NULL);
433 mvaddstr(LINES - 1, STATUSPOS, BUF1);
434 wrefresh(rover.window);
437 /* Show a message on the status bar. */
438 static void
439 message(Color color, char *fmt, ...)
441 int len, pos;
442 va_list args;
444 va_start(args, fmt);
445 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
446 va_end(args);
447 len = strlen(BUF1);
448 pos = (STATUSPOS - len) / 2;
449 attr_on(A_BOLD, NULL);
450 color_set(color, NULL);
451 mvaddstr(LINES - 1, pos, BUF1);
452 color_set(DEFAULT, NULL);
453 attr_off(A_BOLD, NULL);
456 /* Clear message area, leaving only status info. */
457 static void
458 clear_message()
460 mvhline(LINES - 1, 0, ' ', STATUSPOS);
463 /* Comparison used to sort listing entries. */
464 static int
465 rowcmp(const void *a, const void *b)
467 int isdir1, isdir2, cmpdir;
468 const Row *r1 = a;
469 const Row *r2 = b;
470 isdir1 = S_ISDIR(r1->mode);
471 isdir2 = S_ISDIR(r2->mode);
472 cmpdir = isdir2 - isdir1;
473 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
476 /* Get all entries in current working directory. */
477 static int
478 ls(Row **rowsp, uint8_t flags)
480 DIR *dp;
481 struct dirent *ep;
482 struct stat statbuf;
483 Row *rows;
484 int i, n;
486 if(!(dp = opendir("."))) return -1;
487 n = -2; /* We don't want the entries "." and "..". */
488 while (readdir(dp)) n++;
489 rewinddir(dp);
490 rows = malloc(n * sizeof *rows);
491 i = 0;
492 while ((ep = readdir(dp))) {
493 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
494 continue;
495 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
496 continue;
497 lstat(ep->d_name, &statbuf);
498 rows[i].islink = S_ISLNK(statbuf.st_mode);
499 stat(ep->d_name, &statbuf);
500 if (S_ISDIR(statbuf.st_mode)) {
501 if (flags & SHOW_DIRS) {
502 rows[i].name = malloc(strlen(ep->d_name) + 2);
503 strcpy(rows[i].name, ep->d_name);
504 strcat(rows[i].name, "/");
505 rows[i].mode = statbuf.st_mode;
506 i++;
508 } else if (flags & SHOW_FILES) {
509 rows[i].name = malloc(strlen(ep->d_name) + 1);
510 strcpy(rows[i].name, ep->d_name);
511 rows[i].size = statbuf.st_size;
512 rows[i].mode = statbuf.st_mode;
513 i++;
516 n = i; /* Ignore unused space in array caused by filters. */
517 qsort(rows, n, sizeof (*rows), rowcmp);
518 closedir(dp);
519 *rowsp = rows;
520 return n;
523 static void
524 free_rows(Row **rowsp, int nfiles)
526 int i;
528 for (i = 0; i < nfiles; i++)
529 free((*rowsp)[i].name);
530 free(*rowsp);
531 *rowsp = NULL;
534 /* Change working directory to the path in CWD. */
535 static void
536 cd(int reset)
538 int i, j;
540 message(CYAN, "Loading...");
541 refresh();
542 if (reset) ESEL = SCROLL = 0;
543 chdir(CWD);
544 if (rover.nfiles)
545 free_rows(&rover.rows, rover.nfiles);
546 rover.nfiles = ls(&rover.rows, FLAGS);
547 if (!strcmp(CWD, rover.marks.dirpath)) {
548 for (i = 0; i < rover.nfiles; i++) {
549 for (j = 0; j < rover.marks.bulk; j++)
550 if (
551 rover.marks.entries[j] &&
552 !strcmp(rover.marks.entries[j], ENAME(i))
554 break;
555 MARKED(i) = j < rover.marks.bulk;
557 } else
558 for (i = 0; i < rover.nfiles; i++)
559 MARKED(i) = 0;
560 clear_message();
561 update_view();
564 /* Select a target entry, if it is present. */
565 static void
566 try_to_sel(const char *target)
568 ESEL = 0;
569 if (!ISDIR(target))
570 while ((ESEL+1) < rover.nfiles && S_ISDIR(EMODE(ESEL)))
571 ESEL++;
572 while ((ESEL+1) < rover.nfiles && strcoll(ENAME(ESEL), target) < 0)
573 ESEL++;
574 if (rover.nfiles > HEIGHT) {
575 SCROLL = ESEL - HEIGHT / 2;
576 SCROLL = MIN(MAX(SCROLL, 0), rover.nfiles - HEIGHT);
580 /* Reload CWD, but try to keep selection. */
581 static void
582 reload()
584 if (rover.nfiles) {
585 strcpy(INPUT, ENAME(ESEL));
586 cd(1);
587 try_to_sel(INPUT);
588 update_view();
589 } else
590 cd(1);
593 /* Recursively process a source directory using CWD as destination root.
594 For each node (i.e. directory), do the following:
595 1. call pre(destination);
596 2. call proc() on every child leaf (i.e. files);
597 3. recurse into every child node;
598 4. call pos(source).
599 E.g. to move directory /src/ (and all its contents) inside /dst/:
600 strcpy(CWD, "/dst/");
601 process_dir(adddir, movfile, deldir, "/src/"); */
602 static int
603 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
605 int ret;
606 DIR *dp;
607 struct dirent *ep;
608 struct stat statbuf;
609 char subpath[PATH_MAX];
611 ret = 0;
612 if (pre) {
613 char dstpath[PATH_MAX];
614 strcpy(dstpath, CWD);
615 strcat(dstpath, path + strlen(rover.marks.dirpath));
616 ret |= pre(dstpath);
618 if(!(dp = opendir(path))) return -1;
619 while ((ep = readdir(dp))) {
620 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
621 continue;
622 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
623 stat(subpath, &statbuf);
624 if (S_ISDIR(statbuf.st_mode)) {
625 strcat(subpath, "/");
626 ret |= process_dir(pre, proc, pos, subpath);
627 } else
628 ret |= proc(subpath);
630 closedir(dp);
631 if (pos) ret |= pos(path);
632 return ret;
635 /* Process all marked entries using CWD as destination root.
636 All marked entries that are directories will be recursively processed.
637 See process_dir() for details on the parameters. */
638 static void
639 process_marked(PROCESS pre, PROCESS proc, PROCESS pos,
640 const char *msg_doing, const char *msg_done)
642 int i, ret;
643 char path[PATH_MAX];
645 clear_message();
646 message(CYAN, "%s...", msg_doing);
647 refresh();
648 for (i = 0; i < rover.marks.bulk; i++)
649 if (rover.marks.entries[i]) {
650 ret = 0;
651 snprintf(path, PATH_MAX, "%s%s", rover.marks.dirpath, rover.marks.entries[i]);
652 if (ISDIR(rover.marks.entries[i])) {
653 if (!strncmp(path, CWD, strlen(path)))
654 ret = -1;
655 else
656 ret = process_dir(pre, proc, pos, path);
657 } else
658 ret = proc(path);
659 if (!ret) del_mark(&rover.marks, rover.marks.entries[i]);
661 reload();
662 if (!rover.marks.nentries)
663 message(GREEN, "%s all marked entries.", msg_done);
664 else
665 message(RED, "Some errors occured while %s.", msg_doing);
668 /* Wrappers for file operations. */
669 static PROCESS delfile = unlink;
670 static PROCESS deldir = rmdir;
671 static int addfile(const char *path) {
672 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
673 int ret;
675 ret = creat(path, 0644);
676 if (ret < 0) return ret;
677 return close(ret);
679 static int cpyfile(const char *srcpath) {
680 int src, dst, ret;
681 size_t size;
682 struct stat st;
683 char buf[BUFSIZ];
684 char dstpath[PATH_MAX];
686 ret = src = open(srcpath, O_RDONLY);
687 if (ret < 0) return ret;
688 ret = fstat(src, &st);
689 if (ret < 0) return ret;
690 strcpy(dstpath, CWD);
691 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
692 ret = dst = creat(dstpath, st.st_mode);
693 if (ret < 0) return ret;
694 while ((size = read(src, buf, BUFSIZ)) > 0) {
695 write(dst, buf, size);
696 sync_signals();
698 close(src);
699 close(dst);
700 return 0;
702 static int adddir(const char *path) {
703 int ret;
704 struct stat st;
706 ret = stat(CWD, &st);
707 if (ret < 0) return ret;
708 return mkdir(path, st.st_mode);
710 static int movfile(const char *srcpath) {
711 int ret;
712 char dstpath[PATH_MAX];
714 strcpy(dstpath, CWD);
715 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
716 ret = rename(srcpath, dstpath);
717 if (ret < 0 && errno == EXDEV) {
718 ret = cpyfile(srcpath);
719 if (ret < 0) return ret;
720 ret = delfile(srcpath);
722 return ret;
725 static void
726 start_line_edit(const char *init_input)
728 curs_set(TRUE);
729 strncpy(INPUT, init_input, BUFLEN);
730 rover.edit.left = mbstowcs(rover.edit.buffer, init_input, BUFLEN);
731 rover.edit.right = BUFLEN - 1;
732 rover.edit.buffer[BUFLEN] = L'\0';
733 rover.edit_scroll = 0;
736 /* Read input and change editing state accordingly. */
737 static EditStat
738 get_line_edit()
740 wchar_t eraser, killer, wch;
741 int ret, length;
743 ret = rover_get_wch((wint_t *) &wch);
744 erasewchar(&eraser);
745 killwchar(&killer);
746 if (ret == KEY_CODE_YES) {
747 if (wch == KEY_ENTER) {
748 curs_set(FALSE);
749 return CONFIRM;
750 } else if (wch == KEY_LEFT) {
751 if (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
752 } else if (wch == KEY_RIGHT) {
753 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
754 } else if (wch == KEY_UP) {
755 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
756 } else if (wch == KEY_DOWN) {
757 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
758 } else if (wch == KEY_BACKSPACE) {
759 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
760 } else if (wch == KEY_DC) {
761 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
763 } else {
764 if (wch == L'\r' || wch == L'\n') {
765 curs_set(FALSE);
766 return CONFIRM;
767 } else if (wch == L'\t') {
768 curs_set(FALSE);
769 return CANCEL;
770 } else if (wch == eraser) {
771 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
772 } else if (wch == killer) {
773 EDIT_CLEAR(rover.edit);
774 clear_message();
775 } else if (iswprint(wch)) {
776 if (!EDIT_FULL(rover.edit)) EDIT_INSERT(rover.edit, wch);
779 /* Encode edit contents in INPUT. */
780 rover.edit.buffer[rover.edit.left] = L'\0';
781 length = wcstombs(INPUT, rover.edit.buffer, BUFLEN);
782 wcstombs(&INPUT[length], &rover.edit.buffer[rover.edit.right+1],
783 BUFLEN-length);
784 return CONTINUE;
787 /* Update line input on the screen. */
788 static void
789 update_input(const char *prompt, Color color)
791 int plen, ilen, maxlen;
793 plen = strlen(prompt);
794 ilen = mbstowcs(NULL, INPUT, 0);
795 maxlen = STATUSPOS - plen - 2;
796 if (ilen - rover.edit_scroll < maxlen)
797 rover.edit_scroll = MAX(ilen - maxlen, 0);
798 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
799 rover.edit_scroll = rover.edit.left - maxlen;
800 else if (rover.edit.left < rover.edit_scroll)
801 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
802 color_set(RVC_PROMPT, NULL);
803 mvaddstr(LINES - 1, 0, prompt);
804 color_set(color, NULL);
805 mbstowcs(WBUF, INPUT, COLS);
806 mvaddnwstr(LINES - 1, plen, &WBUF[rover.edit_scroll], maxlen);
807 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
808 color_set(DEFAULT, NULL);
809 if (rover.edit_scroll)
810 mvaddch(LINES - 1, plen - 1, '<');
811 if (ilen > rover.edit_scroll + maxlen)
812 mvaddch(LINES - 1, plen + maxlen, '>');
813 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
817 main(int argc, char *argv[])
819 int i, ch;
820 char *program;
821 const char *key;
822 DIR *d;
823 EditStat edit_stat;
824 FILE *save_cwd_file = NULL;
826 if (argc >= 2) {
827 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
828 printf("rover %s\n", RV_VERSION);
829 return 0;
830 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
831 printf(
832 "Usage: rover [-s|--save-cwd FILE] [DIR [DIR [DIR [...]]]]\n"
833 " Browse current directory or the ones specified.\n"
834 " If FILE is given, write last visited path to it.\n\n"
835 " or: rover -h|--help\n"
836 " Print this help message and exit.\n\n"
837 " or: rover -v|--version\n"
838 " Print program version and exit.\n\n"
839 "See rover(1) for more information.\n\n"
840 "Rover homepage: <https://github.com/lecram/rover>.\n"
842 return 0;
843 } else if (!strcmp(argv[1], "-s") || !strcmp(argv[1], "--save-cwd")) {
844 if (argc > 2) {
845 save_cwd_file = fopen(argv[2], "w");
846 argc -= 2; argv += 2;
847 } else {
848 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
849 return 1;
853 init_term();
854 rover.nfiles = 0;
855 for (i = 0; i < 10; i++) {
856 rover.tabs[i].esel = rover.tabs[i].scroll = 0;
857 rover.tabs[i].flags = SHOW_FILES | SHOW_DIRS;
859 strcpy(rover.tabs[0].cwd, getenv("HOME"));
860 for (i = 1; i < argc && i < 10; i++) {
861 if ((d = opendir(argv[i]))) {
862 realpath(argv[i], rover.tabs[i].cwd);
863 closedir(d);
864 } else
865 strcpy(rover.tabs[i].cwd, rover.tabs[0].cwd);
867 getcwd(rover.tabs[i].cwd, PATH_MAX);
868 for (i++; i < 10; i++)
869 strcpy(rover.tabs[i].cwd, rover.tabs[i-1].cwd);
870 for (i = 0; i < 10; i++)
871 if (rover.tabs[i].cwd[strlen(rover.tabs[i].cwd) - 1] != '/')
872 strcat(rover.tabs[i].cwd, "/");
873 rover.tab = 1;
874 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
875 init_marks(&rover.marks);
876 cd(1);
877 while (1) {
878 ch = rover_getch();
879 key = keyname(ch);
880 clear_message();
881 if (!strcmp(key, RVK_QUIT)) break;
882 else if (ch >= '0' && ch <= '9') {
883 rover.tab = ch - '0';
884 cd(0);
885 } else if (!strcmp(key, RVK_HELP)) {
886 ARGS[0] = "man";
887 ARGS[1] = "rover";
888 ARGS[2] = NULL;
889 spawn();
890 } else if (!strcmp(key, RVK_DOWN)) {
891 if (!rover.nfiles) continue;
892 ESEL = MIN(ESEL + 1, rover.nfiles - 1);
893 update_view();
894 } else if (!strcmp(key, RVK_UP)) {
895 if (!rover.nfiles) continue;
896 ESEL = MAX(ESEL - 1, 0);
897 update_view();
898 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
899 if (!rover.nfiles) continue;
900 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
901 if (rover.nfiles > HEIGHT)
902 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
903 update_view();
904 } else if (!strcmp(key, RVK_JUMP_UP)) {
905 if (!rover.nfiles) continue;
906 ESEL = MAX(ESEL - RV_JUMP, 0);
907 SCROLL = MAX(SCROLL - RV_JUMP, 0);
908 update_view();
909 } else if (!strcmp(key, RVK_JUMP_TOP)) {
910 if (!rover.nfiles) continue;
911 ESEL = 0;
912 update_view();
913 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
914 if (!rover.nfiles) continue;
915 ESEL = rover.nfiles - 1;
916 update_view();
917 } else if (!strcmp(key, RVK_CD_DOWN)) {
918 if (!rover.nfiles || !S_ISDIR(EMODE(ESEL))) continue;
919 if (chdir(ENAME(ESEL)) == -1) {
920 message(RED, "Cannot access \"%s\".", ENAME(ESEL));
921 continue;
923 strcat(CWD, ENAME(ESEL));
924 cd(1);
925 } else if (!strcmp(key, RVK_CD_UP)) {
926 char *dirname, first;
927 if (!strcmp(CWD, "/")) continue;
928 CWD[strlen(CWD) - 1] = '\0';
929 dirname = strrchr(CWD, '/') + 1;
930 first = dirname[0];
931 dirname[0] = '\0';
932 cd(1);
933 dirname[0] = first;
934 dirname[strlen(dirname)] = '/';
935 try_to_sel(dirname);
936 dirname[0] = '\0';
937 update_view();
938 } else if (!strcmp(key, RVK_HOME)) {
939 strcpy(CWD, getenv("HOME"));
940 if (CWD[strlen(CWD) - 1] != '/')
941 strcat(CWD, "/");
942 cd(1);
943 } else if (!strcmp(key, RVK_REFRESH)) {
944 reload();
945 } else if (!strcmp(key, RVK_SHELL)) {
946 program = getenv("SHELL");
947 if (program) {
948 ARGS[0] = program;
949 ARGS[1] = NULL;
950 spawn();
951 reload();
953 } else if (!strcmp(key, RVK_VIEW)) {
954 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
955 program = getenv("PAGER");
956 if (program) {
957 ARGS[0] = program;
958 ARGS[1] = ENAME(ESEL);
959 ARGS[2] = NULL;
960 spawn();
962 } else if (!strcmp(key, RVK_EDIT)) {
963 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
964 program = getenv("EDITOR");
965 if (program) {
966 ARGS[0] = program;
967 ARGS[1] = ENAME(ESEL);
968 ARGS[2] = NULL;
969 spawn();
970 cd(0);
972 } else if (!strcmp(key, RVK_SEARCH)) {
973 int oldsel, oldscroll, length;
974 if (!rover.nfiles) continue;
975 oldsel = ESEL;
976 oldscroll = SCROLL;
977 start_line_edit("");
978 update_input(RVP_SEARCH, RED);
979 while ((edit_stat = get_line_edit()) == CONTINUE) {
980 int sel;
981 Color color = RED;
982 length = strlen(INPUT);
983 if (length) {
984 for (sel = 0; sel < rover.nfiles; sel++)
985 if (!strncmp(ENAME(sel), INPUT, length))
986 break;
987 if (sel < rover.nfiles) {
988 color = GREEN;
989 ESEL = sel;
990 if (rover.nfiles > HEIGHT) {
991 if (sel < 3)
992 SCROLL = 0;
993 else if (sel - 3 > rover.nfiles - HEIGHT)
994 SCROLL = rover.nfiles - HEIGHT;
995 else
996 SCROLL = sel - 3;
999 } else {
1000 ESEL = oldsel;
1001 SCROLL = oldscroll;
1003 update_view();
1004 update_input(RVP_SEARCH, color);
1006 if (edit_stat == CANCEL) {
1007 ESEL = oldsel;
1008 SCROLL = oldscroll;
1010 clear_message();
1011 update_view();
1012 } else if (!strcmp(key, RVK_TG_FILES)) {
1013 FLAGS ^= SHOW_FILES;
1014 reload();
1015 } else if (!strcmp(key, RVK_TG_DIRS)) {
1016 FLAGS ^= SHOW_DIRS;
1017 reload();
1018 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
1019 FLAGS ^= SHOW_HIDDEN;
1020 reload();
1021 } else if (!strcmp(key, RVK_NEW_FILE)) {
1022 int ok = 0;
1023 start_line_edit("");
1024 update_input(RVP_NEW_FILE, RED);
1025 while ((edit_stat = get_line_edit()) == CONTINUE) {
1026 int length = strlen(INPUT);
1027 ok = length;
1028 for (i = 0; i < rover.nfiles; i++) {
1029 if (
1030 !strncmp(ENAME(i), INPUT, length) &&
1031 (!strcmp(ENAME(i) + length, "") ||
1032 !strcmp(ENAME(i) + length, "/"))
1034 ok = 0;
1035 break;
1038 update_input(RVP_NEW_FILE, ok ? GREEN : RED);
1040 clear_message();
1041 if (edit_stat == CONFIRM) {
1042 if (ok) {
1043 addfile(INPUT);
1044 cd(1);
1045 try_to_sel(INPUT);
1046 update_view();
1047 } else
1048 message(RED, "\"%s\" already exists.", INPUT);
1050 } else if (!strcmp(key, RVK_NEW_DIR)) {
1051 int ok = 0;
1052 start_line_edit("");
1053 update_input(RVP_NEW_DIR, RED);
1054 while ((edit_stat = get_line_edit()) == CONTINUE) {
1055 int length = strlen(INPUT);
1056 ok = length;
1057 for (i = 0; i < rover.nfiles; i++) {
1058 if (
1059 !strncmp(ENAME(i), INPUT, length) &&
1060 (!strcmp(ENAME(i) + length, "") ||
1061 !strcmp(ENAME(i) + length, "/"))
1063 ok = 0;
1064 break;
1067 update_input(RVP_NEW_DIR, ok ? GREEN : RED);
1069 clear_message();
1070 if (edit_stat == CONFIRM) {
1071 if (ok) {
1072 adddir(INPUT);
1073 cd(1);
1074 strcat(INPUT, "/");
1075 try_to_sel(INPUT);
1076 update_view();
1077 } else
1078 message(RED, "\"%s\" already exists.", INPUT);
1080 } else if (!strcmp(key, RVK_RENAME)) {
1081 int ok = 0;
1082 char *last;
1083 int isdir;
1084 strcpy(INPUT, ENAME(ESEL));
1085 last = INPUT + strlen(INPUT) - 1;
1086 if ((isdir = *last == '/'))
1087 *last = '\0';
1088 start_line_edit(INPUT);
1089 update_input(RVP_RENAME, RED);
1090 while ((edit_stat = get_line_edit()) == CONTINUE) {
1091 int length = strlen(INPUT);
1092 ok = length;
1093 for (i = 0; i < rover.nfiles; i++)
1094 if (
1095 !strncmp(ENAME(i), INPUT, length) &&
1096 (!strcmp(ENAME(i) + length, "") ||
1097 !strcmp(ENAME(i) + length, "/"))
1099 ok = 0;
1100 break;
1102 update_input(RVP_RENAME, ok ? GREEN : RED);
1104 clear_message();
1105 if (edit_stat == CONFIRM) {
1106 if (isdir)
1107 strcat(INPUT, "/");
1108 if (ok) {
1109 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1110 del_mark(&rover.marks, ENAME(ESEL));
1111 add_mark(&rover.marks, CWD, INPUT);
1113 cd(1);
1114 try_to_sel(INPUT);
1115 update_view();
1116 } else
1117 message(RED, "\"%s\" already exists.", INPUT);
1119 } else if (!strcmp(key, RVK_DELETE)) {
1120 if (rover.nfiles) {
1121 message(YELLOW, "Delete \"%s\"? (Y to confirm)", ENAME(ESEL));
1122 if (rover_getch() == 'Y') {
1123 const char *name = ENAME(ESEL);
1124 int ret = S_ISDIR(EMODE(ESEL)) ? deldir(name) : delfile(name);
1125 reload();
1126 if (ret)
1127 message(RED, "Could not delete \"%s\".", ENAME(ESEL));
1128 } else
1129 clear_message();
1130 } else
1131 message(RED, "No entry selected for deletion.");
1132 } else if (!strcmp(key, RVK_TG_MARK)) {
1133 if (MARKED(ESEL))
1134 del_mark(&rover.marks, ENAME(ESEL));
1135 else
1136 add_mark(&rover.marks, CWD, ENAME(ESEL));
1137 MARKED(ESEL) = !MARKED(ESEL);
1138 ESEL = (ESEL + 1) % rover.nfiles;
1139 update_view();
1140 } else if (!strcmp(key, RVK_INVMARK)) {
1141 for (i = 0; i < rover.nfiles; i++) {
1142 if (MARKED(i))
1143 del_mark(&rover.marks, ENAME(i));
1144 else
1145 add_mark(&rover.marks, CWD, ENAME(i));
1146 MARKED(i) = !MARKED(i);
1148 update_view();
1149 } else if (!strcmp(key, RVK_MARKALL)) {
1150 for (i = 0; i < rover.nfiles; i++)
1151 if (!MARKED(i)) {
1152 add_mark(&rover.marks, CWD, ENAME(i));
1153 MARKED(i) = 1;
1155 update_view();
1156 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1157 if (rover.marks.nentries) {
1158 message(YELLOW, "Delete all marked entries? (Y to confirm)");
1159 if (rover_getch() == 'Y')
1160 process_marked(NULL, delfile, deldir, "Deleting", "Deleted");
1161 else
1162 clear_message();
1163 } else
1164 message(RED, "No entries marked for deletion.");
1165 } else if (!strcmp(key, RVK_MARK_COPY)) {
1166 if (rover.marks.nentries)
1167 process_marked(adddir, cpyfile, NULL, "Copying", "Copied");
1168 else
1169 message(RED, "No entries marked for copying.");
1170 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1171 if (rover.marks.nentries)
1172 process_marked(adddir, movfile, deldir, "Moving", "Moved");
1173 else
1174 message(RED, "No entries marked for moving.");
1177 if (rover.nfiles)
1178 free_rows(&rover.rows, rover.nfiles);
1179 free_marks(&rover.marks);
1180 delwin(rover.window);
1181 if (save_cwd_file != NULL) {
1182 fputs(CWD, save_cwd_file);
1183 fclose(save_cwd_file);
1185 return 0;