Review manual.
[rover.git] / rover.c
blob13d4d78d7fef70cb02a565e8bb42ff0e0aba1f34
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 /* This signal is not defined by POSIX, but should be
28 present on all systems that have resizable terminals. */
29 #ifndef SIGWINCH
30 #define SIGWINCH 28
31 #endif
33 /* String buffers. */
34 #define BUFLEN PATH_MAX
35 static char BUF1[BUFLEN];
36 static char BUF2[BUFLEN];
37 static char INPUT[BUFLEN];
38 static wchar_t WBUF[BUFLEN];
40 /* Argument buffers for execvp(). */
41 #define MAXARGS 256
42 static char *ARGS[MAXARGS];
44 /* Listing view parameters. */
45 #define HEIGHT (LINES-4)
46 #define STATUSPOS (COLS-16)
48 /* Listing view flags. */
49 #define SHOW_FILES 0x01u
50 #define SHOW_DIRS 0x02u
51 #define SHOW_HIDDEN 0x04u
53 /* Marks parameters. */
54 #define BULK_INIT 5
55 #define BULK_THRESH 256
57 /* Information associated to each entry in listing. */
58 typedef struct Row {
59 char *name;
60 off_t size;
61 mode_t mode;
62 int islink;
63 int marked;
64 } Row;
66 /* Dynamic array of marked entries. */
67 typedef struct Marks {
68 char dirpath[PATH_MAX];
69 int bulk;
70 int nentries;
71 char **entries;
72 } Marks;
74 /* Line editing state. */
75 typedef struct Edit {
76 wchar_t buffer[BUFLEN+1];
77 int left, right;
78 } Edit;
80 /* Each tab only stores the following information. */
81 typedef struct Tab {
82 int scroll;
83 int esel;
84 uint8_t flags;
85 char cwd[PATH_MAX];
86 } Tab;
88 typedef struct Prog {
89 off_t partial;
90 off_t total;
91 const char *msg;
92 } Prog;
94 /* Global state. */
95 static struct Rover {
96 int tab;
97 int nfiles;
98 Row *rows;
99 WINDOW *window;
100 Marks marks;
101 Edit edit;
102 int edit_scroll;
103 volatile sig_atomic_t pending_winch;
104 Prog prog;
105 Tab tabs[10];
106 } rover;
108 /* Macros for accessing global state. */
109 #define ENAME(I) rover.rows[I].name
110 #define ESIZE(I) rover.rows[I].size
111 #define EMODE(I) rover.rows[I].mode
112 #define ISLINK(I) rover.rows[I].islink
113 #define MARKED(I) rover.rows[I].marked
114 #define SCROLL rover.tabs[rover.tab].scroll
115 #define ESEL rover.tabs[rover.tab].esel
116 #define FLAGS rover.tabs[rover.tab].flags
117 #define CWD rover.tabs[rover.tab].cwd
119 /* Helpers. */
120 #define MIN(A, B) ((A) < (B) ? (A) : (B))
121 #define MAX(A, B) ((A) > (B) ? (A) : (B))
122 #define ISDIR(E) (strchr((E), '/') != NULL)
124 /* Line Editing Macros. */
125 #define EDIT_FULL(E) ((E).left == (E).right)
126 #define EDIT_CAN_LEFT(E) ((E).left)
127 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
128 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
129 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
130 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
131 #define EDIT_BACKSPACE(E) (E).left--
132 #define EDIT_DELETE(E) (E).right++
133 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
135 typedef enum EditStat {CONTINUE, CONFIRM, CANCEL} EditStat;
136 typedef enum Color {DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK} Color;
137 typedef int (*PROCESS)(const char *path);
139 static void
140 init_marks(Marks *marks)
142 strcpy(marks->dirpath, "");
143 marks->bulk = BULK_INIT;
144 marks->nentries = 0;
145 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
148 /* Unmark all entries. */
149 static void
150 mark_none(Marks *marks)
152 int i;
154 strcpy(marks->dirpath, "");
155 for (i = 0; i < marks->bulk && marks->nentries; i++)
156 if (marks->entries[i]) {
157 free(marks->entries[i]);
158 marks->entries[i] = NULL;
159 marks->nentries--;
161 if (marks->bulk > BULK_THRESH) {
162 /* Reset bulk to free some memory. */
163 free(marks->entries);
164 marks->bulk = BULK_INIT;
165 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
169 static void
170 add_mark(Marks *marks, char *dirpath, char *entry)
172 int i;
174 if (!strcmp(marks->dirpath, dirpath)) {
175 /* Append mark to directory. */
176 if (marks->nentries == marks->bulk) {
177 /* Expand bulk to accomodate new entry. */
178 int extra = marks->bulk / 2;
179 marks->bulk += extra; /* bulk *= 1.5; */
180 marks->entries = realloc(marks->entries,
181 marks->bulk * sizeof *marks->entries);
182 memset(&marks->entries[marks->nentries], 0,
183 extra * sizeof *marks->entries);
184 i = marks->nentries;
185 } else {
186 /* Search for empty slot (there must be one). */
187 for (i = 0; i < marks->bulk; i++)
188 if (!marks->entries[i])
189 break;
191 } else {
192 /* Directory changed. Discard old marks. */
193 mark_none(marks);
194 strcpy(marks->dirpath, dirpath);
195 i = 0;
197 marks->entries[i] = malloc(strlen(entry) + 1);
198 strcpy(marks->entries[i], entry);
199 marks->nentries++;
202 static void
203 del_mark(Marks *marks, char *entry)
205 int i;
207 if (marks->nentries > 1) {
208 for (i = 0; i < marks->bulk; i++)
209 if (marks->entries[i] && !strcmp(marks->entries[i], entry))
210 break;
211 free(marks->entries[i]);
212 marks->entries[i] = NULL;
213 marks->nentries--;
214 } else
215 mark_none(marks);
218 static void
219 free_marks(Marks *marks)
221 int i;
223 for (i = 0; i < marks->bulk && marks->nentries; i++)
224 if (marks->entries[i]) {
225 free(marks->entries[i]);
226 marks->nentries--;
228 free(marks->entries);
231 static void
232 handle_winch(int sig)
234 rover.pending_winch = 1;
237 static void
238 enable_handlers()
240 struct sigaction sa;
242 memset(&sa, 0, sizeof (struct sigaction));
243 sa.sa_handler = handle_winch;
244 sigaction(SIGWINCH, &sa, NULL);
247 static void
248 disable_handlers()
250 struct sigaction sa;
252 memset(&sa, 0, sizeof (struct sigaction));
253 sa.sa_handler = SIG_DFL;
254 sigaction(SIGWINCH, &sa, NULL);
257 static void update_view();
259 /* Handle any signals received since last call. */
260 static void
261 sync_signals()
263 if (rover.pending_winch) {
264 /* SIGWINCH received: resize application accordingly. */
265 delwin(rover.window);
266 endwin();
267 refresh();
268 clear();
269 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
270 if (HEIGHT < rover.nfiles && SCROLL + HEIGHT > rover.nfiles)
271 SCROLL = ESEL - HEIGHT;
272 update_view();
273 rover.pending_winch = 0;
277 /* This function must be used in place of getch().
278 It handles signals while waiting for user input. */
279 static int
280 rover_getch()
282 int ch;
284 while ((ch = getch()) == ERR)
285 sync_signals();
286 return ch;
289 /* This function must be used in place of get_wch().
290 It handles signals while waiting for user input. */
291 static int
292 rover_get_wch(wint_t *wch)
294 wint_t ret;
296 while ((ret = get_wch(wch)) == (wint_t) ERR)
297 sync_signals();
298 return ret;
301 /* Do a fork-exec to external program (e.g. $EDITOR). */
302 static void
303 spawn()
305 pid_t pid;
306 int status;
308 setenv("RVSEL", rover.nfiles ? ENAME(ESEL) : "", 1);
309 pid = fork();
310 if (pid > 0) {
311 /* fork() succeeded. */
312 disable_handlers();
313 endwin();
314 waitpid(pid, &status, 0);
315 enable_handlers();
316 kill(getpid(), SIGWINCH);
317 } else if (pid == 0) {
318 /* Child process. */
319 execvp(ARGS[0], ARGS);
323 /* Curses setup. */
324 static void
325 init_term()
327 setlocale(LC_ALL, "");
328 initscr();
329 cbreak(); /* Get one character at a time. */
330 timeout(100); /* For getch(). */
331 noecho();
332 nonl(); /* No NL->CR/NL on output. */
333 intrflush(stdscr, FALSE);
334 keypad(stdscr, TRUE);
335 curs_set(FALSE); /* Hide blinking cursor. */
336 if (has_colors()) {
337 short bg;
338 start_color();
339 #ifdef NCURSES_EXT_FUNCS
340 use_default_colors();
341 bg = -1;
342 #else
343 bg = COLOR_BLACK;
344 #endif
345 init_pair(RED, COLOR_RED, bg);
346 init_pair(GREEN, COLOR_GREEN, bg);
347 init_pair(YELLOW, COLOR_YELLOW, bg);
348 init_pair(BLUE, COLOR_BLUE, bg);
349 init_pair(CYAN, COLOR_CYAN, bg);
350 init_pair(MAGENTA, COLOR_MAGENTA, bg);
351 init_pair(WHITE, COLOR_WHITE, bg);
352 init_pair(BLACK, COLOR_BLACK, bg);
354 atexit((void (*)(void)) endwin);
355 enable_handlers();
358 /* Update the listing view. */
359 static void
360 update_view()
362 int i, j;
363 int numsize;
364 int ishidden;
365 int marking;
367 mvhline(0, 0, ' ', COLS);
368 attr_on(A_BOLD, NULL);
369 color_set(RVC_TABNUM, NULL);
370 mvaddch(0, COLS - 2, rover.tab + '0');
371 attr_off(A_BOLD, NULL);
372 if (rover.marks.nentries) {
373 numsize = snprintf(BUF1, BUFLEN, "%d", rover.marks.nentries);
374 color_set(RVC_MARKS, NULL);
375 mvaddstr(0, COLS - 3 - numsize, BUF1);
376 } else
377 numsize = -1;
378 color_set(RVC_CWD, NULL);
379 mbstowcs(WBUF, CWD, PATH_MAX);
380 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
381 wcolor_set(rover.window, RVC_BORDER, NULL);
382 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
383 ESEL = MAX(MIN(ESEL, rover.nfiles - 1), 0);
384 /* Selection might not be visible, due to cursor wrapping or window
385 shrinking. In that case, the scroll must be moved to make it visible. */
386 if (rover.nfiles > HEIGHT) {
387 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
388 SCROLL = MIN(MAX(SCROLL, 0), rover.nfiles - HEIGHT);
389 } else
390 SCROLL = 0;
391 marking = !strcmp(CWD, rover.marks.dirpath);
392 for (i = 0, j = SCROLL; i < HEIGHT && j < rover.nfiles; i++, j++) {
393 ishidden = ENAME(j)[0] == '.';
394 if (j == ESEL)
395 wattr_on(rover.window, A_REVERSE, NULL);
396 if (ISLINK(j))
397 wcolor_set(rover.window, RVC_LINK, NULL);
398 else if (ishidden)
399 wcolor_set(rover.window, RVC_HIDDEN, NULL);
400 else if (S_ISREG(EMODE(j))) {
401 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
402 wcolor_set(rover.window, RVC_EXEC, NULL);
403 else
404 wcolor_set(rover.window, RVC_REG, NULL);
405 } else if (S_ISDIR(EMODE(j)))
406 wcolor_set(rover.window, RVC_DIR, NULL);
407 else if (S_ISCHR(EMODE(j)))
408 wcolor_set(rover.window, RVC_CHR, NULL);
409 else if (S_ISBLK(EMODE(j)))
410 wcolor_set(rover.window, RVC_BLK, NULL);
411 else if (S_ISFIFO(EMODE(j)))
412 wcolor_set(rover.window, RVC_FIFO, NULL);
413 else if (S_ISSOCK(EMODE(j)))
414 wcolor_set(rover.window, RVC_SOCK, NULL);
415 if (!S_ISDIR(EMODE(j))) {
416 char *suffix, *suffixes = "BKMGTPEZY";
417 off_t human_size = ESIZE(j) * 10;
418 int length = mbstowcs(NULL, ENAME(j), 0);
419 for (suffix = suffixes; human_size >= 10240; suffix++)
420 human_size = (human_size + 512) / 1024;
421 if (*suffix == 'B')
422 swprintf(WBUF, PATH_MAX, L"%s%*d %c", ENAME(j),
423 (int) (COLS - length - 6),
424 (int) human_size / 10, *suffix);
425 else
426 swprintf(WBUF, PATH_MAX, L"%s%*d.%d %c", ENAME(j),
427 (int) (COLS - length - 8),
428 (int) human_size / 10, (int) human_size % 10, *suffix);
429 } else
430 mbstowcs(WBUF, ENAME(j), PATH_MAX);
431 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
432 mvwaddnwstr(rover.window, i + 1, 2, WBUF, COLS - 4);
433 if (marking && MARKED(j)) {
434 wcolor_set(rover.window, RVC_MARKS, NULL);
435 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
436 } else
437 mvwaddch(rover.window, i + 1, 1, ' ');
438 if (j == ESEL)
439 wattr_off(rover.window, A_REVERSE, NULL);
441 for (; i < HEIGHT; i++)
442 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
443 if (rover.nfiles > HEIGHT) {
444 int center, height;
445 center = (SCROLL + HEIGHT / 2) * HEIGHT / rover.nfiles;
446 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
447 if (!height) height = 1;
448 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
449 mvwvline(rover.window, center-height/2+1, COLS-1, RVS_SCROLLBAR, height);
451 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
452 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
453 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
454 if (!rover.nfiles)
455 strcpy(BUF2, "0/0");
456 else
457 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, rover.nfiles);
458 snprintf(BUF1+3, BUFLEN-3, "%12s", BUF2);
459 color_set(RVC_STATUS, NULL);
460 mvaddstr(LINES - 1, STATUSPOS, BUF1);
461 wrefresh(rover.window);
464 /* Show a message on the status bar. */
465 static void
466 message(Color color, char *fmt, ...)
468 int len, pos;
469 va_list args;
471 va_start(args, fmt);
472 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
473 va_end(args);
474 len = strlen(BUF1);
475 pos = (STATUSPOS - len) / 2;
476 attr_on(A_BOLD, NULL);
477 color_set(color, NULL);
478 mvaddstr(LINES - 1, pos, BUF1);
479 color_set(DEFAULT, NULL);
480 attr_off(A_BOLD, NULL);
483 /* Clear message area, leaving only status info. */
484 static void
485 clear_message()
487 mvhline(LINES - 1, 0, ' ', STATUSPOS);
490 /* Comparison used to sort listing entries. */
491 static int
492 rowcmp(const void *a, const void *b)
494 int isdir1, isdir2, cmpdir;
495 const Row *r1 = a;
496 const Row *r2 = b;
497 isdir1 = S_ISDIR(r1->mode);
498 isdir2 = S_ISDIR(r2->mode);
499 cmpdir = isdir2 - isdir1;
500 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
503 /* Get all entries in current working directory. */
504 static int
505 ls(Row **rowsp, uint8_t flags)
507 DIR *dp;
508 struct dirent *ep;
509 struct stat statbuf;
510 Row *rows;
511 int i, n;
513 if(!(dp = opendir("."))) return -1;
514 n = -2; /* We don't want the entries "." and "..". */
515 while (readdir(dp)) n++;
516 rewinddir(dp);
517 rows = malloc(n * sizeof *rows);
518 i = 0;
519 while ((ep = readdir(dp))) {
520 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
521 continue;
522 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
523 continue;
524 lstat(ep->d_name, &statbuf);
525 rows[i].islink = S_ISLNK(statbuf.st_mode);
526 stat(ep->d_name, &statbuf);
527 if (S_ISDIR(statbuf.st_mode)) {
528 if (flags & SHOW_DIRS) {
529 rows[i].name = malloc(strlen(ep->d_name) + 2);
530 strcpy(rows[i].name, ep->d_name);
531 strcat(rows[i].name, "/");
532 rows[i].mode = statbuf.st_mode;
533 i++;
535 } else if (flags & SHOW_FILES) {
536 rows[i].name = malloc(strlen(ep->d_name) + 1);
537 strcpy(rows[i].name, ep->d_name);
538 rows[i].size = statbuf.st_size;
539 rows[i].mode = statbuf.st_mode;
540 i++;
543 n = i; /* Ignore unused space in array caused by filters. */
544 qsort(rows, n, sizeof (*rows), rowcmp);
545 closedir(dp);
546 *rowsp = rows;
547 return n;
550 static void
551 free_rows(Row **rowsp, int nfiles)
553 int i;
555 for (i = 0; i < nfiles; i++)
556 free((*rowsp)[i].name);
557 free(*rowsp);
558 *rowsp = NULL;
561 /* Change working directory to the path in CWD. */
562 static void
563 cd(int reset)
565 int i, j;
567 message(CYAN, "Loading...");
568 refresh();
569 if (reset) ESEL = SCROLL = 0;
570 chdir(CWD);
571 if (rover.nfiles)
572 free_rows(&rover.rows, rover.nfiles);
573 rover.nfiles = ls(&rover.rows, FLAGS);
574 if (!strcmp(CWD, rover.marks.dirpath)) {
575 for (i = 0; i < rover.nfiles; i++) {
576 for (j = 0; j < rover.marks.bulk; j++)
577 if (
578 rover.marks.entries[j] &&
579 !strcmp(rover.marks.entries[j], ENAME(i))
581 break;
582 MARKED(i) = j < rover.marks.bulk;
584 } else
585 for (i = 0; i < rover.nfiles; i++)
586 MARKED(i) = 0;
587 clear_message();
588 update_view();
591 /* Select a target entry, if it is present. */
592 static void
593 try_to_sel(const char *target)
595 ESEL = 0;
596 if (!ISDIR(target))
597 while ((ESEL+1) < rover.nfiles && S_ISDIR(EMODE(ESEL)))
598 ESEL++;
599 while ((ESEL+1) < rover.nfiles && strcoll(ENAME(ESEL), target) < 0)
600 ESEL++;
603 /* Reload CWD, but try to keep selection. */
604 static void
605 reload()
607 if (rover.nfiles) {
608 strcpy(INPUT, ENAME(ESEL));
609 cd(0);
610 try_to_sel(INPUT);
611 update_view();
612 } else
613 cd(1);
616 static off_t
617 count_dir(const char *path)
619 DIR *dp;
620 struct dirent *ep;
621 struct stat statbuf;
622 char subpath[PATH_MAX];
623 off_t total;
625 if(!(dp = opendir(path))) return 0;
626 total = 0;
627 while ((ep = readdir(dp))) {
628 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
629 continue;
630 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
631 lstat(subpath, &statbuf);
632 if (S_ISDIR(statbuf.st_mode)) {
633 strcat(subpath, "/");
634 total += count_dir(subpath);
635 } else
636 total += statbuf.st_size;
638 closedir(dp);
639 return total;
642 static off_t
643 count_marked()
645 int i;
646 char *entry;
647 off_t total;
648 struct stat statbuf;
650 total = 0;
651 chdir(rover.marks.dirpath);
652 for (i = 0; i < rover.marks.bulk; i++) {
653 entry = rover.marks.entries[i];
654 if (entry) {
655 if (ISDIR(entry)) {
656 total += count_dir(entry);
657 } else {
658 lstat(entry, &statbuf);
659 total += statbuf.st_size;
663 chdir(CWD);
664 return total;
667 /* Recursively process a source directory using CWD as destination root.
668 For each node (i.e. directory), do the following:
669 1. call pre(destination);
670 2. call proc() on every child leaf (i.e. files);
671 3. recurse into every child node;
672 4. call pos(source).
673 E.g. to move directory /src/ (and all its contents) inside /dst/:
674 strcpy(CWD, "/dst/");
675 process_dir(adddir, movfile, deldir, "/src/"); */
676 static int
677 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
679 int ret;
680 DIR *dp;
681 struct dirent *ep;
682 struct stat statbuf;
683 char subpath[PATH_MAX];
685 ret = 0;
686 if (pre) {
687 char dstpath[PATH_MAX];
688 strcpy(dstpath, CWD);
689 strcat(dstpath, path + strlen(rover.marks.dirpath));
690 ret |= pre(dstpath);
692 if(!(dp = opendir(path))) return -1;
693 while ((ep = readdir(dp))) {
694 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
695 continue;
696 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
697 stat(subpath, &statbuf);
698 if (S_ISDIR(statbuf.st_mode)) {
699 strcat(subpath, "/");
700 ret |= process_dir(pre, proc, pos, subpath);
701 } else
702 ret |= proc(subpath);
704 closedir(dp);
705 if (pos) ret |= pos(path);
706 return ret;
709 /* Process all marked entries using CWD as destination root.
710 All marked entries that are directories will be recursively processed.
711 See process_dir() for details on the parameters. */
712 static void
713 process_marked(PROCESS pre, PROCESS proc, PROCESS pos,
714 const char *msg_doing, const char *msg_done)
716 int i, ret;
717 char *entry;
718 char path[PATH_MAX];
720 clear_message();
721 message(CYAN, "%s...", msg_doing);
722 refresh();
723 rover.prog = (Prog) {0, count_marked(), msg_doing};
724 for (i = 0; i < rover.marks.bulk; i++) {
725 entry = rover.marks.entries[i];
726 if (entry) {
727 ret = 0;
728 snprintf(path, PATH_MAX, "%s%s", rover.marks.dirpath, entry);
729 if (ISDIR(entry)) {
730 if (!strncmp(path, CWD, strlen(path)))
731 ret = -1;
732 else
733 ret = process_dir(pre, proc, pos, path);
734 } else
735 ret = proc(path);
736 if (!ret) {
737 del_mark(&rover.marks, entry);
738 reload();
742 rover.prog.total = 0;
743 reload();
744 if (!rover.marks.nentries)
745 message(GREEN, "%s all marked entries.", msg_done);
746 else
747 message(RED, "Some errors occured while %s.", msg_doing);
748 RV_ALERT();
751 static void
752 update_progress(off_t delta)
754 int percent;
756 if (!rover.prog.total) return;
757 rover.prog.partial += delta;
758 percent = (int) (rover.prog.partial * 100 / rover.prog.total);
759 message(CYAN, "%s...%d%%", rover.prog.msg, percent);
760 refresh();
763 /* Wrappers for file operations. */
764 static int delfile(const char *path) {
765 int ret;
766 struct stat st;
768 ret = lstat(path, &st);
769 if (ret < 0) return ret;
770 update_progress(st.st_size);
771 return unlink(path);
773 static PROCESS deldir = rmdir;
774 static int addfile(const char *path) {
775 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
776 int ret;
778 ret = creat(path, 0644);
779 if (ret < 0) return ret;
780 return close(ret);
782 static int cpyfile(const char *srcpath) {
783 int src, dst, ret;
784 size_t size;
785 struct stat st;
786 char buf[BUFSIZ];
787 char dstpath[PATH_MAX];
789 ret = src = open(srcpath, O_RDONLY);
790 if (ret < 0) return ret;
791 ret = fstat(src, &st);
792 if (ret < 0) return ret;
793 strcpy(dstpath, CWD);
794 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
795 ret = dst = creat(dstpath, st.st_mode);
796 if (ret < 0) return ret;
797 while ((size = read(src, buf, BUFSIZ)) > 0) {
798 write(dst, buf, size);
799 update_progress(size);
800 sync_signals();
802 close(src);
803 close(dst);
804 return 0;
806 static int adddir(const char *path) {
807 int ret;
808 struct stat st;
810 ret = stat(CWD, &st);
811 if (ret < 0) return ret;
812 return mkdir(path, st.st_mode);
814 static int movfile(const char *srcpath) {
815 int ret;
816 struct stat st;
817 char dstpath[PATH_MAX];
819 strcpy(dstpath, CWD);
820 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
821 ret = rename(srcpath, dstpath);
822 if (ret == 0) {
823 ret = lstat(dstpath, &st);
824 if (ret < 0) return ret;
825 update_progress(st.st_size);
826 } else if (errno == EXDEV) {
827 ret = cpyfile(srcpath);
828 if (ret < 0) return ret;
829 ret = unlink(srcpath);
831 return ret;
834 static void
835 start_line_edit(const char *init_input)
837 curs_set(TRUE);
838 strncpy(INPUT, init_input, BUFLEN);
839 rover.edit.left = mbstowcs(rover.edit.buffer, init_input, BUFLEN);
840 rover.edit.right = BUFLEN - 1;
841 rover.edit.buffer[BUFLEN] = L'\0';
842 rover.edit_scroll = 0;
845 /* Read input and change editing state accordingly. */
846 static EditStat
847 get_line_edit()
849 wchar_t eraser, killer, wch;
850 int ret, length;
852 ret = rover_get_wch((wint_t *) &wch);
853 erasewchar(&eraser);
854 killwchar(&killer);
855 if (ret == KEY_CODE_YES) {
856 if (wch == KEY_ENTER) {
857 curs_set(FALSE);
858 return CONFIRM;
859 } else if (wch == KEY_LEFT) {
860 if (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
861 } else if (wch == KEY_RIGHT) {
862 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
863 } else if (wch == KEY_UP) {
864 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
865 } else if (wch == KEY_DOWN) {
866 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
867 } else if (wch == KEY_BACKSPACE) {
868 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
869 } else if (wch == KEY_DC) {
870 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
872 } else {
873 if (wch == L'\r' || wch == L'\n') {
874 curs_set(FALSE);
875 return CONFIRM;
876 } else if (wch == L'\t') {
877 curs_set(FALSE);
878 return CANCEL;
879 } else if (wch == eraser) {
880 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
881 } else if (wch == killer) {
882 EDIT_CLEAR(rover.edit);
883 clear_message();
884 } else if (iswprint(wch)) {
885 if (!EDIT_FULL(rover.edit)) EDIT_INSERT(rover.edit, wch);
888 /* Encode edit contents in INPUT. */
889 rover.edit.buffer[rover.edit.left] = L'\0';
890 length = wcstombs(INPUT, rover.edit.buffer, BUFLEN);
891 wcstombs(&INPUT[length], &rover.edit.buffer[rover.edit.right+1],
892 BUFLEN-length);
893 return CONTINUE;
896 /* Update line input on the screen. */
897 static void
898 update_input(const char *prompt, Color color)
900 int plen, ilen, maxlen;
902 plen = strlen(prompt);
903 ilen = mbstowcs(NULL, INPUT, 0);
904 maxlen = STATUSPOS - plen - 2;
905 if (ilen - rover.edit_scroll < maxlen)
906 rover.edit_scroll = MAX(ilen - maxlen, 0);
907 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
908 rover.edit_scroll = rover.edit.left - maxlen;
909 else if (rover.edit.left < rover.edit_scroll)
910 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
911 color_set(RVC_PROMPT, NULL);
912 mvaddstr(LINES - 1, 0, prompt);
913 color_set(color, NULL);
914 mbstowcs(WBUF, INPUT, COLS);
915 mvaddnwstr(LINES - 1, plen, &WBUF[rover.edit_scroll], maxlen);
916 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
917 color_set(DEFAULT, NULL);
918 if (rover.edit_scroll)
919 mvaddch(LINES - 1, plen - 1, '<');
920 if (ilen > rover.edit_scroll + maxlen)
921 mvaddch(LINES - 1, plen + maxlen, '>');
922 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
926 main(int argc, char *argv[])
928 int i, ch;
929 char *program;
930 char *entry;
931 const char *key;
932 DIR *d;
933 EditStat edit_stat;
934 FILE *save_cwd_file = NULL;
935 FILE *save_marks_file = NULL;
937 if (argc >= 2) {
938 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
939 printf("rover %s\n", RV_VERSION);
940 return 0;
941 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
942 printf(
943 "Usage: rover"
944 " [-d|--save-cwd FILE]"
945 " [-m|--save-marks FILE]"
946 " [DIR [DIR [DIR [...]]]]\n"
947 " Browse current directory or the ones specified.\n"
948 " If FILE is given, write last visited path to it.\n\n"
949 " or: rover -h|--help\n"
950 " Print this help message and exit.\n\n"
951 " or: rover -v|--version\n"
952 " Print program version and exit.\n\n"
953 "See rover(1) for more information.\n\n"
954 "Rover homepage: <https://github.com/lecram/rover>.\n"
956 return 0;
957 } else if (!strcmp(argv[1], "-d") || !strcmp(argv[1], "--save-cwd")) {
958 if (argc > 2) {
959 save_cwd_file = fopen(argv[2], "w");
960 argc -= 2; argv += 2;
961 } else {
962 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
963 return 1;
965 } else if (!strcmp(argv[1], "-m") || !strcmp(argv[1], "--save-marks")) {
966 if (argc > 2) {
967 save_marks_file = fopen(argv[2], "a");
968 argc -= 2; argv += 2;
969 } else {
970 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
971 return 1;
975 init_term();
976 rover.nfiles = 0;
977 for (i = 0; i < 10; i++) {
978 rover.tabs[i].esel = rover.tabs[i].scroll = 0;
979 rover.tabs[i].flags = SHOW_FILES | SHOW_DIRS;
981 strcpy(rover.tabs[0].cwd, getenv("HOME"));
982 for (i = 1; i < argc && i < 10; i++) {
983 if ((d = opendir(argv[i]))) {
984 realpath(argv[i], rover.tabs[i].cwd);
985 closedir(d);
986 } else
987 strcpy(rover.tabs[i].cwd, rover.tabs[0].cwd);
989 getcwd(rover.tabs[i].cwd, PATH_MAX);
990 for (i++; i < 10; i++)
991 strcpy(rover.tabs[i].cwd, rover.tabs[i-1].cwd);
992 for (i = 0; i < 10; i++)
993 if (rover.tabs[i].cwd[strlen(rover.tabs[i].cwd) - 1] != '/')
994 strcat(rover.tabs[i].cwd, "/");
995 rover.tab = 1;
996 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
997 init_marks(&rover.marks);
998 cd(1);
999 while (1) {
1000 ch = rover_getch();
1001 key = keyname(ch);
1002 clear_message();
1003 if (!strcmp(key, RVK_QUIT)) break;
1004 else if (ch >= '0' && ch <= '9') {
1005 rover.tab = ch - '0';
1006 cd(0);
1007 } else if (!strcmp(key, RVK_HELP)) {
1008 ARGS[0] = "man";
1009 ARGS[1] = "rover";
1010 ARGS[2] = NULL;
1011 spawn();
1012 } else if (!strcmp(key, RVK_DOWN)) {
1013 if (!rover.nfiles) continue;
1014 ESEL = MIN(ESEL + 1, rover.nfiles - 1);
1015 update_view();
1016 } else if (!strcmp(key, RVK_UP)) {
1017 if (!rover.nfiles) continue;
1018 ESEL = MAX(ESEL - 1, 0);
1019 update_view();
1020 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
1021 if (!rover.nfiles) continue;
1022 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
1023 if (rover.nfiles > HEIGHT)
1024 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
1025 update_view();
1026 } else if (!strcmp(key, RVK_JUMP_UP)) {
1027 if (!rover.nfiles) continue;
1028 ESEL = MAX(ESEL - RV_JUMP, 0);
1029 SCROLL = MAX(SCROLL - RV_JUMP, 0);
1030 update_view();
1031 } else if (!strcmp(key, RVK_JUMP_TOP)) {
1032 if (!rover.nfiles) continue;
1033 ESEL = 0;
1034 update_view();
1035 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
1036 if (!rover.nfiles) continue;
1037 ESEL = rover.nfiles - 1;
1038 update_view();
1039 } else if (!strcmp(key, RVK_CD_DOWN)) {
1040 if (!rover.nfiles || !S_ISDIR(EMODE(ESEL))) continue;
1041 if (chdir(ENAME(ESEL)) == -1) {
1042 message(RED, "Cannot access \"%s\".", ENAME(ESEL));
1043 continue;
1045 strcat(CWD, ENAME(ESEL));
1046 cd(1);
1047 } else if (!strcmp(key, RVK_CD_UP)) {
1048 char *dirname, first;
1049 if (!strcmp(CWD, "/")) continue;
1050 CWD[strlen(CWD) - 1] = '\0';
1051 dirname = strrchr(CWD, '/') + 1;
1052 first = dirname[0];
1053 dirname[0] = '\0';
1054 cd(1);
1055 dirname[0] = first;
1056 dirname[strlen(dirname)] = '/';
1057 try_to_sel(dirname);
1058 dirname[0] = '\0';
1059 if (rover.nfiles > HEIGHT)
1060 SCROLL = ESEL - HEIGHT / 2;
1061 update_view();
1062 } else if (!strcmp(key, RVK_HOME)) {
1063 strcpy(CWD, getenv("HOME"));
1064 if (CWD[strlen(CWD) - 1] != '/')
1065 strcat(CWD, "/");
1066 cd(1);
1067 } else if (!strcmp(key, RVK_REFRESH)) {
1068 reload();
1069 } else if (!strcmp(key, RVK_SHELL)) {
1070 program = getenv("SHELL");
1071 if (program) {
1072 ARGS[0] = program;
1073 ARGS[1] = NULL;
1074 spawn();
1075 reload();
1077 } else if (!strcmp(key, RVK_VIEW)) {
1078 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1079 program = getenv("PAGER");
1080 if (program) {
1081 ARGS[0] = program;
1082 ARGS[1] = ENAME(ESEL);
1083 ARGS[2] = NULL;
1084 spawn();
1086 } else if (!strcmp(key, RVK_EDIT)) {
1087 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1088 program = getenv("EDITOR");
1089 if (program) {
1090 ARGS[0] = program;
1091 ARGS[1] = ENAME(ESEL);
1092 ARGS[2] = NULL;
1093 spawn();
1094 cd(0);
1096 } else if (!strcmp(key, RVK_SEARCH)) {
1097 int oldsel, oldscroll, length;
1098 if (!rover.nfiles) continue;
1099 oldsel = ESEL;
1100 oldscroll = SCROLL;
1101 start_line_edit("");
1102 update_input(RVP_SEARCH, RED);
1103 while ((edit_stat = get_line_edit()) == CONTINUE) {
1104 int sel;
1105 Color color = RED;
1106 length = strlen(INPUT);
1107 if (length) {
1108 for (sel = 0; sel < rover.nfiles; sel++)
1109 if (!strncmp(ENAME(sel), INPUT, length))
1110 break;
1111 if (sel < rover.nfiles) {
1112 color = GREEN;
1113 ESEL = sel;
1114 if (rover.nfiles > HEIGHT) {
1115 if (sel < 3)
1116 SCROLL = 0;
1117 else if (sel - 3 > rover.nfiles - HEIGHT)
1118 SCROLL = rover.nfiles - HEIGHT;
1119 else
1120 SCROLL = sel - 3;
1123 } else {
1124 ESEL = oldsel;
1125 SCROLL = oldscroll;
1127 update_view();
1128 update_input(RVP_SEARCH, color);
1130 if (edit_stat == CANCEL) {
1131 ESEL = oldsel;
1132 SCROLL = oldscroll;
1134 clear_message();
1135 update_view();
1136 } else if (!strcmp(key, RVK_TG_FILES)) {
1137 FLAGS ^= SHOW_FILES;
1138 reload();
1139 } else if (!strcmp(key, RVK_TG_DIRS)) {
1140 FLAGS ^= SHOW_DIRS;
1141 reload();
1142 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
1143 FLAGS ^= SHOW_HIDDEN;
1144 reload();
1145 } else if (!strcmp(key, RVK_NEW_FILE)) {
1146 int ok = 0;
1147 start_line_edit("");
1148 update_input(RVP_NEW_FILE, RED);
1149 while ((edit_stat = get_line_edit()) == CONTINUE) {
1150 int length = strlen(INPUT);
1151 ok = length;
1152 for (i = 0; i < rover.nfiles; i++) {
1153 if (
1154 !strncmp(ENAME(i), INPUT, length) &&
1155 (!strcmp(ENAME(i) + length, "") ||
1156 !strcmp(ENAME(i) + length, "/"))
1158 ok = 0;
1159 break;
1162 update_input(RVP_NEW_FILE, ok ? GREEN : RED);
1164 clear_message();
1165 if (edit_stat == CONFIRM) {
1166 if (ok) {
1167 addfile(INPUT);
1168 cd(1);
1169 try_to_sel(INPUT);
1170 update_view();
1171 } else
1172 message(RED, "\"%s\" already exists.", INPUT);
1174 } else if (!strcmp(key, RVK_NEW_DIR)) {
1175 int ok = 0;
1176 start_line_edit("");
1177 update_input(RVP_NEW_DIR, RED);
1178 while ((edit_stat = get_line_edit()) == CONTINUE) {
1179 int length = strlen(INPUT);
1180 ok = length;
1181 for (i = 0; i < rover.nfiles; i++) {
1182 if (
1183 !strncmp(ENAME(i), INPUT, length) &&
1184 (!strcmp(ENAME(i) + length, "") ||
1185 !strcmp(ENAME(i) + length, "/"))
1187 ok = 0;
1188 break;
1191 update_input(RVP_NEW_DIR, ok ? GREEN : RED);
1193 clear_message();
1194 if (edit_stat == CONFIRM) {
1195 if (ok) {
1196 adddir(INPUT);
1197 cd(1);
1198 strcat(INPUT, "/");
1199 try_to_sel(INPUT);
1200 update_view();
1201 } else
1202 message(RED, "\"%s\" already exists.", INPUT);
1204 } else if (!strcmp(key, RVK_RENAME)) {
1205 int ok = 0;
1206 char *last;
1207 int isdir;
1208 strcpy(INPUT, ENAME(ESEL));
1209 last = INPUT + strlen(INPUT) - 1;
1210 if ((isdir = *last == '/'))
1211 *last = '\0';
1212 start_line_edit(INPUT);
1213 update_input(RVP_RENAME, RED);
1214 while ((edit_stat = get_line_edit()) == CONTINUE) {
1215 int length = strlen(INPUT);
1216 ok = length;
1217 for (i = 0; i < rover.nfiles; i++)
1218 if (
1219 !strncmp(ENAME(i), INPUT, length) &&
1220 (!strcmp(ENAME(i) + length, "") ||
1221 !strcmp(ENAME(i) + length, "/"))
1223 ok = 0;
1224 break;
1226 update_input(RVP_RENAME, ok ? GREEN : RED);
1228 clear_message();
1229 if (edit_stat == CONFIRM) {
1230 if (isdir)
1231 strcat(INPUT, "/");
1232 if (ok) {
1233 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1234 del_mark(&rover.marks, ENAME(ESEL));
1235 add_mark(&rover.marks, CWD, INPUT);
1237 cd(1);
1238 try_to_sel(INPUT);
1239 update_view();
1240 } else
1241 message(RED, "\"%s\" already exists.", INPUT);
1243 } else if (!strcmp(key, RVK_DELETE)) {
1244 if (rover.nfiles) {
1245 message(YELLOW, "Delete \"%s\"? (Y to confirm)", ENAME(ESEL));
1246 if (rover_getch() == 'Y') {
1247 const char *name = ENAME(ESEL);
1248 int ret = S_ISDIR(EMODE(ESEL)) ? deldir(name) : delfile(name);
1249 reload();
1250 if (ret)
1251 message(RED, "Could not delete \"%s\".", ENAME(ESEL));
1252 } else
1253 clear_message();
1254 } else
1255 message(RED, "No entry selected for deletion.");
1256 } else if (!strcmp(key, RVK_TG_MARK)) {
1257 if (MARKED(ESEL))
1258 del_mark(&rover.marks, ENAME(ESEL));
1259 else
1260 add_mark(&rover.marks, CWD, ENAME(ESEL));
1261 MARKED(ESEL) = !MARKED(ESEL);
1262 ESEL = (ESEL + 1) % rover.nfiles;
1263 update_view();
1264 } else if (!strcmp(key, RVK_INVMARK)) {
1265 for (i = 0; i < rover.nfiles; i++) {
1266 if (MARKED(i))
1267 del_mark(&rover.marks, ENAME(i));
1268 else
1269 add_mark(&rover.marks, CWD, ENAME(i));
1270 MARKED(i) = !MARKED(i);
1272 update_view();
1273 } else if (!strcmp(key, RVK_MARKALL)) {
1274 for (i = 0; i < rover.nfiles; i++)
1275 if (!MARKED(i)) {
1276 add_mark(&rover.marks, CWD, ENAME(i));
1277 MARKED(i) = 1;
1279 update_view();
1280 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1281 if (rover.marks.nentries) {
1282 message(YELLOW, "Delete all marked entries? (Y to confirm)");
1283 if (rover_getch() == 'Y')
1284 process_marked(NULL, delfile, deldir, "Deleting", "Deleted");
1285 else
1286 clear_message();
1287 } else
1288 message(RED, "No entries marked for deletion.");
1289 } else if (!strcmp(key, RVK_MARK_COPY)) {
1290 if (rover.marks.nentries)
1291 process_marked(adddir, cpyfile, NULL, "Copying", "Copied");
1292 else
1293 message(RED, "No entries marked for copying.");
1294 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1295 if (rover.marks.nentries)
1296 process_marked(adddir, movfile, deldir, "Moving", "Moved");
1297 else
1298 message(RED, "No entries marked for moving.");
1301 if (rover.nfiles)
1302 free_rows(&rover.rows, rover.nfiles);
1303 delwin(rover.window);
1304 if (save_cwd_file != NULL) {
1305 fputs(CWD, save_cwd_file);
1306 fclose(save_cwd_file);
1308 if (save_marks_file != NULL) {
1309 for (i = 0; i < rover.marks.bulk; i++) {
1310 entry = rover.marks.entries[i];
1311 if (entry)
1312 fprintf(save_marks_file, "%s%s\n", rover.marks.dirpath, entry);
1314 fclose(save_marks_file);
1316 free_marks(&rover.marks);
1317 return 0;