Blob


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 typedef struct Prog {
83 off_t partial;
84 off_t total;
85 const char *msg;
86 } Prog;
88 /* Global state. */
89 static struct Rover {
90 int tab;
91 int nfiles;
92 Row *rows;
93 WINDOW *window;
94 Marks marks;
95 Edit edit;
96 int edit_scroll;
97 volatile sig_atomic_t pending_winch;
98 Prog prog;
99 Tab tabs[10];
100 } rover;
102 /* Macros for accessing global state. */
103 #define ENAME(I) rover.rows[I].name
104 #define ESIZE(I) rover.rows[I].size
105 #define EMODE(I) rover.rows[I].mode
106 #define ISLINK(I) rover.rows[I].islink
107 #define MARKED(I) rover.rows[I].marked
108 #define SCROLL rover.tabs[rover.tab].scroll
109 #define ESEL rover.tabs[rover.tab].esel
110 #define FLAGS rover.tabs[rover.tab].flags
111 #define CWD rover.tabs[rover.tab].cwd
113 /* Helpers. */
114 #define MIN(A, B) ((A) < (B) ? (A) : (B))
115 #define MAX(A, B) ((A) > (B) ? (A) : (B))
116 #define ISDIR(E) (strchr((E), '/') != NULL)
118 /* Line Editing Macros. */
119 #define EDIT_FULL(E) ((E).left == (E).right)
120 #define EDIT_CAN_LEFT(E) ((E).left)
121 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
122 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
123 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
124 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
125 #define EDIT_BACKSPACE(E) (E).left--
126 #define EDIT_DELETE(E) (E).right++
127 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
129 typedef enum EditStat {CONTINUE, CONFIRM, CANCEL} EditStat;
130 typedef enum Color {DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK} Color;
131 typedef int (*PROCESS)(const char *path);
133 static void
134 init_marks(Marks *marks)
136 strcpy(marks->dirpath, "");
137 marks->bulk = BULK_INIT;
138 marks->nentries = 0;
139 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
142 /* Unmark all entries. */
143 static void
144 mark_none(Marks *marks)
146 int i;
148 strcpy(marks->dirpath, "");
149 for (i = 0; i < marks->bulk && marks->nentries; i++)
150 if (marks->entries[i]) {
151 free(marks->entries[i]);
152 marks->entries[i] = NULL;
153 marks->nentries--;
155 if (marks->bulk > BULK_THRESH) {
156 /* Reset bulk to free some memory. */
157 free(marks->entries);
158 marks->bulk = BULK_INIT;
159 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
163 static void
164 add_mark(Marks *marks, char *dirpath, char *entry)
166 int i;
168 if (!strcmp(marks->dirpath, dirpath)) {
169 /* Append mark to directory. */
170 if (marks->nentries == marks->bulk) {
171 /* Expand bulk to accomodate new entry. */
172 int extra = marks->bulk / 2;
173 marks->bulk += extra; /* bulk *= 1.5; */
174 marks->entries = realloc(marks->entries,
175 marks->bulk * sizeof *marks->entries);
176 memset(&marks->entries[marks->nentries], 0,
177 extra * sizeof *marks->entries);
178 i = marks->nentries;
179 } else {
180 /* Search for empty slot (there must be one). */
181 for (i = 0; i < marks->bulk; i++)
182 if (!marks->entries[i])
183 break;
185 } else {
186 /* Directory changed. Discard old marks. */
187 mark_none(marks);
188 strcpy(marks->dirpath, dirpath);
189 i = 0;
191 marks->entries[i] = malloc(strlen(entry) + 1);
192 strcpy(marks->entries[i], entry);
193 marks->nentries++;
196 static void
197 del_mark(Marks *marks, char *entry)
199 int i;
201 if (marks->nentries > 1) {
202 for (i = 0; i < marks->bulk; i++)
203 if (marks->entries[i] && !strcmp(marks->entries[i], entry))
204 break;
205 free(marks->entries[i]);
206 marks->entries[i] = NULL;
207 marks->nentries--;
208 } else
209 mark_none(marks);
212 static void
213 free_marks(Marks *marks)
215 int i;
217 for (i = 0; i < marks->bulk && marks->nentries; i++)
218 if (marks->entries[i]) {
219 free(marks->entries[i]);
220 marks->nentries--;
222 free(marks->entries);
225 static void
226 handle_winch(int sig)
228 rover.pending_winch = 1;
231 static void
232 enable_handlers()
234 struct sigaction sa;
236 memset(&sa, 0, sizeof (struct sigaction));
237 sa.sa_handler = handle_winch;
238 sigaction(SIGWINCH, &sa, NULL);
241 static void
242 disable_handlers()
244 struct sigaction sa;
246 memset(&sa, 0, sizeof (struct sigaction));
247 sa.sa_handler = SIG_DFL;
248 sigaction(SIGWINCH, &sa, NULL);
251 static void update_view();
253 /* Handle any signals received since last call. */
254 static void
255 sync_signals()
257 if (rover.pending_winch) {
258 /* SIGWINCH received: resize application accordingly. */
259 delwin(rover.window);
260 endwin();
261 refresh();
262 clear();
263 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
264 if (HEIGHT < rover.nfiles && SCROLL + HEIGHT > rover.nfiles)
265 SCROLL = ESEL - HEIGHT;
266 update_view();
267 rover.pending_winch = 0;
271 /* This function must be used in place of getch().
272 It handles signals while waiting for user input. */
273 static int
274 rover_getch()
276 int ch;
278 while ((ch = getch()) == ERR)
279 sync_signals();
280 return ch;
283 /* This function must be used in place of get_wch().
284 It handles signals while waiting for user input. */
285 static int
286 rover_get_wch(wint_t *wch)
288 wint_t ret;
290 while ((ret = get_wch(wch)) == (wint_t) ERR)
291 sync_signals();
292 return ret;
295 /* Do a fork-exec to external program (e.g. $EDITOR). */
296 static void
297 spawn()
299 pid_t pid;
300 int status;
302 setenv("RVSEL", rover.nfiles ? ENAME(ESEL) : "", 1);
303 pid = fork();
304 if (pid > 0) {
305 /* fork() succeeded. */
306 disable_handlers();
307 endwin();
308 waitpid(pid, &status, 0);
309 enable_handlers();
310 kill(getpid(), SIGWINCH);
311 } else if (pid == 0) {
312 /* Child process. */
313 execvp(ARGS[0], ARGS);
317 /* Curses setup. */
318 static void
319 init_term()
321 setlocale(LC_ALL, "");
322 initscr();
323 cbreak(); /* Get one character at a time. */
324 timeout(100); /* For getch(). */
325 noecho();
326 nonl(); /* No NL->CR/NL on output. */
327 intrflush(stdscr, FALSE);
328 keypad(stdscr, TRUE);
329 curs_set(FALSE); /* Hide blinking cursor. */
330 if (has_colors()) {
331 short bg;
332 start_color();
333 #ifdef NCURSES_EXT_FUNCS
334 use_default_colors();
335 bg = -1;
336 #else
337 bg = COLOR_BLACK;
338 #endif
339 init_pair(RED, COLOR_RED, bg);
340 init_pair(GREEN, COLOR_GREEN, bg);
341 init_pair(YELLOW, COLOR_YELLOW, bg);
342 init_pair(BLUE, COLOR_BLUE, bg);
343 init_pair(CYAN, COLOR_CYAN, bg);
344 init_pair(MAGENTA, COLOR_MAGENTA, bg);
345 init_pair(WHITE, COLOR_WHITE, bg);
346 init_pair(BLACK, COLOR_BLACK, bg);
348 atexit((void (*)(void)) endwin);
349 enable_handlers();
352 /* Update the listing view. */
353 static void
354 update_view()
356 int i, j;
357 int numsize;
358 int ishidden;
359 int marking;
361 mvhline(0, 0, ' ', COLS);
362 attr_on(A_BOLD, NULL);
363 color_set(RVC_TABNUM, NULL);
364 mvaddch(0, COLS - 2, rover.tab + '0');
365 attr_off(A_BOLD, NULL);
366 if (rover.marks.nentries) {
367 numsize = snprintf(BUF1, BUFLEN, "%d", rover.marks.nentries);
368 color_set(RVC_MARKS, NULL);
369 mvaddstr(0, COLS - 3 - numsize, BUF1);
370 } else
371 numsize = -1;
372 color_set(RVC_CWD, NULL);
373 mbstowcs(WBUF, CWD, PATH_MAX);
374 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
375 wcolor_set(rover.window, RVC_BORDER, NULL);
376 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
377 ESEL = MAX(MIN(ESEL, rover.nfiles - 1), 0);
378 /* Selection might not be visible, due to cursor wrapping or window
379 shrinking. In that case, the scroll must be moved to make it visible. */
380 if (rover.nfiles > HEIGHT) {
381 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
382 SCROLL = MIN(MAX(SCROLL, 0), rover.nfiles - HEIGHT);
383 } else
384 SCROLL = 0;
385 marking = !strcmp(CWD, rover.marks.dirpath);
386 for (i = 0, j = SCROLL; i < HEIGHT && j < rover.nfiles; i++, j++) {
387 ishidden = ENAME(j)[0] == '.';
388 if (j == ESEL)
389 wattr_on(rover.window, A_REVERSE, NULL);
390 if (ISLINK(j))
391 wcolor_set(rover.window, RVC_LINK, NULL);
392 else if (ishidden)
393 wcolor_set(rover.window, RVC_HIDDEN, NULL);
394 else if (S_ISREG(EMODE(j))) {
395 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
396 wcolor_set(rover.window, RVC_EXEC, NULL);
397 else
398 wcolor_set(rover.window, RVC_REG, NULL);
399 } else if (S_ISDIR(EMODE(j)))
400 wcolor_set(rover.window, RVC_DIR, NULL);
401 else if (S_ISCHR(EMODE(j)))
402 wcolor_set(rover.window, RVC_CHR, NULL);
403 else if (S_ISBLK(EMODE(j)))
404 wcolor_set(rover.window, RVC_BLK, NULL);
405 else if (S_ISFIFO(EMODE(j)))
406 wcolor_set(rover.window, RVC_FIFO, NULL);
407 else if (S_ISSOCK(EMODE(j)))
408 wcolor_set(rover.window, RVC_SOCK, NULL);
409 if (!S_ISDIR(EMODE(j))) {
410 char *suffix, *suffixes = "BKMGTPEZY";
411 off_t human_size = ESIZE(j) * 10;
412 int length = mbstowcs(NULL, ENAME(j), 0);
413 for (suffix = suffixes; human_size >= 10240; suffix++)
414 human_size = (human_size + 512) / 1024;
415 if (*suffix == 'B')
416 swprintf(WBUF, PATH_MAX, L"%s%*d %c", ENAME(j),
417 (int) (COLS - length - 6),
418 (int) human_size / 10, *suffix);
419 else
420 swprintf(WBUF, PATH_MAX, L"%s%*d.%d %c", ENAME(j),
421 (int) (COLS - length - 8),
422 (int) human_size / 10, (int) human_size % 10, *suffix);
423 } else
424 mbstowcs(WBUF, ENAME(j), PATH_MAX);
425 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
426 mvwaddnwstr(rover.window, i + 1, 2, WBUF, COLS - 4);
427 if (marking && MARKED(j)) {
428 wcolor_set(rover.window, RVC_MARKS, NULL);
429 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
430 } else
431 mvwaddch(rover.window, i + 1, 1, ' ');
432 if (j == ESEL)
433 wattr_off(rover.window, A_REVERSE, NULL);
435 for (; i < HEIGHT; i++)
436 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
437 if (rover.nfiles > HEIGHT) {
438 int center, height;
439 center = (SCROLL + HEIGHT / 2) * HEIGHT / rover.nfiles;
440 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
441 if (!height) height = 1;
442 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
443 mvwvline(rover.window, center-height/2+1, COLS-1, RVS_SCROLLBAR, height);
445 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
446 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
447 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
448 if (!rover.nfiles)
449 strcpy(BUF2, "0/0");
450 else
451 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, rover.nfiles);
452 snprintf(BUF1+3, BUFLEN-3, "%12s", BUF2);
453 color_set(RVC_STATUS, NULL);
454 mvaddstr(LINES - 1, STATUSPOS, BUF1);
455 wrefresh(rover.window);
458 /* Show a message on the status bar. */
459 static void
460 message(Color color, char *fmt, ...)
462 int len, pos;
463 va_list args;
465 va_start(args, fmt);
466 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
467 va_end(args);
468 len = strlen(BUF1);
469 pos = (STATUSPOS - len) / 2;
470 attr_on(A_BOLD, NULL);
471 color_set(color, NULL);
472 mvaddstr(LINES - 1, pos, BUF1);
473 color_set(DEFAULT, NULL);
474 attr_off(A_BOLD, NULL);
477 /* Clear message area, leaving only status info. */
478 static void
479 clear_message()
481 mvhline(LINES - 1, 0, ' ', STATUSPOS);
484 /* Comparison used to sort listing entries. */
485 static int
486 rowcmp(const void *a, const void *b)
488 int isdir1, isdir2, cmpdir;
489 const Row *r1 = a;
490 const Row *r2 = b;
491 isdir1 = S_ISDIR(r1->mode);
492 isdir2 = S_ISDIR(r2->mode);
493 cmpdir = isdir2 - isdir1;
494 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
497 /* Get all entries in current working directory. */
498 static int
499 ls(Row **rowsp, uint8_t flags)
501 DIR *dp;
502 struct dirent *ep;
503 struct stat statbuf;
504 Row *rows;
505 int i, n;
507 if(!(dp = opendir("."))) return -1;
508 n = -2; /* We don't want the entries "." and "..". */
509 while (readdir(dp)) n++;
510 rewinddir(dp);
511 rows = malloc(n * sizeof *rows);
512 i = 0;
513 while ((ep = readdir(dp))) {
514 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
515 continue;
516 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
517 continue;
518 lstat(ep->d_name, &statbuf);
519 rows[i].islink = S_ISLNK(statbuf.st_mode);
520 stat(ep->d_name, &statbuf);
521 if (S_ISDIR(statbuf.st_mode)) {
522 if (flags & SHOW_DIRS) {
523 rows[i].name = malloc(strlen(ep->d_name) + 2);
524 strcpy(rows[i].name, ep->d_name);
525 strcat(rows[i].name, "/");
526 rows[i].mode = statbuf.st_mode;
527 i++;
529 } else if (flags & SHOW_FILES) {
530 rows[i].name = malloc(strlen(ep->d_name) + 1);
531 strcpy(rows[i].name, ep->d_name);
532 rows[i].size = statbuf.st_size;
533 rows[i].mode = statbuf.st_mode;
534 i++;
537 n = i; /* Ignore unused space in array caused by filters. */
538 qsort(rows, n, sizeof (*rows), rowcmp);
539 closedir(dp);
540 *rowsp = rows;
541 return n;
544 static void
545 free_rows(Row **rowsp, int nfiles)
547 int i;
549 for (i = 0; i < nfiles; i++)
550 free((*rowsp)[i].name);
551 free(*rowsp);
552 *rowsp = NULL;
555 /* Change working directory to the path in CWD. */
556 static void
557 cd(int reset)
559 int i, j;
561 message(CYAN, "Loading...");
562 refresh();
563 if (reset) ESEL = SCROLL = 0;
564 chdir(CWD);
565 if (rover.nfiles)
566 free_rows(&rover.rows, rover.nfiles);
567 rover.nfiles = ls(&rover.rows, FLAGS);
568 if (!strcmp(CWD, rover.marks.dirpath)) {
569 for (i = 0; i < rover.nfiles; i++) {
570 for (j = 0; j < rover.marks.bulk; j++)
571 if (
572 rover.marks.entries[j] &&
573 !strcmp(rover.marks.entries[j], ENAME(i))
575 break;
576 MARKED(i) = j < rover.marks.bulk;
578 } else
579 for (i = 0; i < rover.nfiles; i++)
580 MARKED(i) = 0;
581 clear_message();
582 update_view();
585 /* Select a target entry, if it is present. */
586 static void
587 try_to_sel(const char *target)
589 ESEL = 0;
590 if (!ISDIR(target))
591 while ((ESEL+1) < rover.nfiles && S_ISDIR(EMODE(ESEL)))
592 ESEL++;
593 while ((ESEL+1) < rover.nfiles && strcoll(ENAME(ESEL), target) < 0)
594 ESEL++;
597 /* Reload CWD, but try to keep selection. */
598 static void
599 reload()
601 if (rover.nfiles) {
602 strcpy(INPUT, ENAME(ESEL));
603 cd(0);
604 try_to_sel(INPUT);
605 update_view();
606 } else
607 cd(1);
610 static off_t
611 count_dir(const char *path)
613 DIR *dp;
614 struct dirent *ep;
615 struct stat statbuf;
616 char subpath[PATH_MAX];
617 off_t total;
619 if(!(dp = opendir(path))) return 0;
620 total = 0;
621 while ((ep = readdir(dp))) {
622 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
623 continue;
624 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
625 lstat(subpath, &statbuf);
626 if (S_ISDIR(statbuf.st_mode)) {
627 strcat(subpath, "/");
628 total += count_dir(subpath);
629 } else
630 total += statbuf.st_size;
632 closedir(dp);
633 return total;
636 static off_t
637 count_marked()
639 int i;
640 char *entry;
641 off_t total;
642 struct stat statbuf;
644 total = 0;
645 chdir(rover.marks.dirpath);
646 for (i = 0; i < rover.marks.bulk; i++) {
647 entry = rover.marks.entries[i];
648 if (entry) {
649 if (ISDIR(entry)) {
650 total += count_dir(entry);
651 } else {
652 lstat(entry, &statbuf);
653 total += statbuf.st_size;
657 chdir(CWD);
658 return total;
661 /* Recursively process a source directory using CWD as destination root.
662 For each node (i.e. directory), do the following:
663 1. call pre(destination);
664 2. call proc() on every child leaf (i.e. files);
665 3. recurse into every child node;
666 4. call pos(source).
667 E.g. to move directory /src/ (and all its contents) inside /dst/:
668 strcpy(CWD, "/dst/");
669 process_dir(adddir, movfile, deldir, "/src/"); */
670 static int
671 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
673 int ret;
674 DIR *dp;
675 struct dirent *ep;
676 struct stat statbuf;
677 char subpath[PATH_MAX];
679 ret = 0;
680 if (pre) {
681 char dstpath[PATH_MAX];
682 strcpy(dstpath, CWD);
683 strcat(dstpath, path + strlen(rover.marks.dirpath));
684 ret |= pre(dstpath);
686 if(!(dp = opendir(path))) return -1;
687 while ((ep = readdir(dp))) {
688 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
689 continue;
690 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
691 stat(subpath, &statbuf);
692 if (S_ISDIR(statbuf.st_mode)) {
693 strcat(subpath, "/");
694 ret |= process_dir(pre, proc, pos, subpath);
695 } else
696 ret |= proc(subpath);
698 closedir(dp);
699 if (pos) ret |= pos(path);
700 return ret;
703 /* Process all marked entries using CWD as destination root.
704 All marked entries that are directories will be recursively processed.
705 See process_dir() for details on the parameters. */
706 static void
707 process_marked(PROCESS pre, PROCESS proc, PROCESS pos,
708 const char *msg_doing, const char *msg_done)
710 int i, ret;
711 char *entry;
712 char path[PATH_MAX];
714 clear_message();
715 message(CYAN, "%s...", msg_doing);
716 refresh();
717 rover.prog = (Prog) {0, count_marked(), msg_doing};
718 for (i = 0; i < rover.marks.bulk; i++) {
719 entry = rover.marks.entries[i];
720 if (entry) {
721 ret = 0;
722 snprintf(path, PATH_MAX, "%s%s", rover.marks.dirpath, entry);
723 if (ISDIR(entry)) {
724 if (!strncmp(path, CWD, strlen(path)))
725 ret = -1;
726 else
727 ret = process_dir(pre, proc, pos, path);
728 } else
729 ret = proc(path);
730 if (!ret) {
731 del_mark(&rover.marks, entry);
732 reload();
736 rover.prog.total = 0;
737 reload();
738 if (!rover.marks.nentries)
739 message(GREEN, "%s all marked entries.", msg_done);
740 else
741 message(RED, "Some errors occured while %s.", msg_doing);
742 RV_ALERT();
745 static void
746 update_progress(off_t delta)
748 int percent;
750 if (!rover.prog.total) return;
751 rover.prog.partial += delta;
752 percent = (int) (rover.prog.partial * 100 / rover.prog.total);
753 message(CYAN, "%s...%d%%", rover.prog.msg, percent);
754 refresh();
757 /* Wrappers for file operations. */
758 static int delfile(const char *path) {
759 int ret;
760 struct stat st;
762 ret = lstat(path, &st);
763 if (ret < 0) return ret;
764 update_progress(st.st_size);
765 return unlink(path);
767 static PROCESS deldir = rmdir;
768 static int addfile(const char *path) {
769 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
770 int ret;
772 ret = creat(path, 0644);
773 if (ret < 0) return ret;
774 return close(ret);
776 static int cpyfile(const char *srcpath) {
777 int src, dst, ret;
778 size_t size;
779 struct stat st;
780 char buf[BUFSIZ];
781 char dstpath[PATH_MAX];
783 ret = src = open(srcpath, O_RDONLY);
784 if (ret < 0) return ret;
785 ret = fstat(src, &st);
786 if (ret < 0) return ret;
787 strcpy(dstpath, CWD);
788 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
789 ret = dst = creat(dstpath, st.st_mode);
790 if (ret < 0) return ret;
791 while ((size = read(src, buf, BUFSIZ)) > 0) {
792 write(dst, buf, size);
793 update_progress(size);
794 sync_signals();
796 close(src);
797 close(dst);
798 return 0;
800 static int adddir(const char *path) {
801 int ret;
802 struct stat st;
804 ret = stat(CWD, &st);
805 if (ret < 0) return ret;
806 return mkdir(path, st.st_mode);
808 static int movfile(const char *srcpath) {
809 int ret;
810 struct stat st;
811 char dstpath[PATH_MAX];
813 strcpy(dstpath, CWD);
814 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
815 ret = rename(srcpath, dstpath);
816 if (ret == 0) {
817 ret = lstat(dstpath, &st);
818 if (ret < 0) return ret;
819 update_progress(st.st_size);
820 } else if (errno == EXDEV) {
821 ret = cpyfile(srcpath);
822 if (ret < 0) return ret;
823 ret = unlink(srcpath);
825 return ret;
828 static void
829 start_line_edit(const char *init_input)
831 curs_set(TRUE);
832 strncpy(INPUT, init_input, BUFLEN);
833 rover.edit.left = mbstowcs(rover.edit.buffer, init_input, BUFLEN);
834 rover.edit.right = BUFLEN - 1;
835 rover.edit.buffer[BUFLEN] = L'\0';
836 rover.edit_scroll = 0;
839 /* Read input and change editing state accordingly. */
840 static EditStat
841 get_line_edit()
843 wchar_t eraser, killer, wch;
844 int ret, length;
846 ret = rover_get_wch((wint_t *) &wch);
847 erasewchar(&eraser);
848 killwchar(&killer);
849 if (ret == KEY_CODE_YES) {
850 if (wch == KEY_ENTER) {
851 curs_set(FALSE);
852 return CONFIRM;
853 } else if (wch == KEY_LEFT) {
854 if (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
855 } else if (wch == KEY_RIGHT) {
856 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
857 } else if (wch == KEY_UP) {
858 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
859 } else if (wch == KEY_DOWN) {
860 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
861 } else if (wch == KEY_BACKSPACE) {
862 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
863 } else if (wch == KEY_DC) {
864 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
866 } else {
867 if (wch == L'\r' || wch == L'\n') {
868 curs_set(FALSE);
869 return CONFIRM;
870 } else if (wch == L'\t') {
871 curs_set(FALSE);
872 return CANCEL;
873 } else if (wch == eraser) {
874 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
875 } else if (wch == killer) {
876 EDIT_CLEAR(rover.edit);
877 clear_message();
878 } else if (iswprint(wch)) {
879 if (!EDIT_FULL(rover.edit)) EDIT_INSERT(rover.edit, wch);
882 /* Encode edit contents in INPUT. */
883 rover.edit.buffer[rover.edit.left] = L'\0';
884 length = wcstombs(INPUT, rover.edit.buffer, BUFLEN);
885 wcstombs(&INPUT[length], &rover.edit.buffer[rover.edit.right+1],
886 BUFLEN-length);
887 return CONTINUE;
890 /* Update line input on the screen. */
891 static void
892 update_input(const char *prompt, Color color)
894 int plen, ilen, maxlen;
896 plen = strlen(prompt);
897 ilen = mbstowcs(NULL, INPUT, 0);
898 maxlen = STATUSPOS - plen - 2;
899 if (ilen - rover.edit_scroll < maxlen)
900 rover.edit_scroll = MAX(ilen - maxlen, 0);
901 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
902 rover.edit_scroll = rover.edit.left - maxlen;
903 else if (rover.edit.left < rover.edit_scroll)
904 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
905 color_set(RVC_PROMPT, NULL);
906 mvaddstr(LINES - 1, 0, prompt);
907 color_set(color, NULL);
908 mbstowcs(WBUF, INPUT, COLS);
909 mvaddnwstr(LINES - 1, plen, &WBUF[rover.edit_scroll], maxlen);
910 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
911 color_set(DEFAULT, NULL);
912 if (rover.edit_scroll)
913 mvaddch(LINES - 1, plen - 1, '<');
914 if (ilen > rover.edit_scroll + maxlen)
915 mvaddch(LINES - 1, plen + maxlen, '>');
916 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
919 int
920 main(int argc, char *argv[])
922 int i, ch;
923 char *program;
924 const char *key;
925 DIR *d;
926 EditStat edit_stat;
927 FILE *save_cwd_file = NULL;
929 if (argc >= 2) {
930 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
931 printf("rover %s\n", RV_VERSION);
932 return 0;
933 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
934 printf(
935 "Usage: rover [-s|--save-cwd FILE] [DIR [DIR [DIR [...]]]]\n"
936 " Browse current directory or the ones specified.\n"
937 " If FILE is given, write last visited path to it.\n\n"
938 " or: rover -h|--help\n"
939 " Print this help message and exit.\n\n"
940 " or: rover -v|--version\n"
941 " Print program version and exit.\n\n"
942 "See rover(1) for more information.\n\n"
943 "Rover homepage: <https://github.com/lecram/rover>.\n"
944 );
945 return 0;
946 } else if (!strcmp(argv[1], "-s") || !strcmp(argv[1], "--save-cwd")) {
947 if (argc > 2) {
948 save_cwd_file = fopen(argv[2], "w");
949 argc -= 2; argv += 2;
950 } else {
951 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
952 return 1;
956 init_term();
957 rover.nfiles = 0;
958 for (i = 0; i < 10; i++) {
959 rover.tabs[i].esel = rover.tabs[i].scroll = 0;
960 rover.tabs[i].flags = SHOW_FILES | SHOW_DIRS;
962 strcpy(rover.tabs[0].cwd, getenv("HOME"));
963 for (i = 1; i < argc && i < 10; i++) {
964 if ((d = opendir(argv[i]))) {
965 realpath(argv[i], rover.tabs[i].cwd);
966 closedir(d);
967 } else
968 strcpy(rover.tabs[i].cwd, rover.tabs[0].cwd);
970 getcwd(rover.tabs[i].cwd, PATH_MAX);
971 for (i++; i < 10; i++)
972 strcpy(rover.tabs[i].cwd, rover.tabs[i-1].cwd);
973 for (i = 0; i < 10; i++)
974 if (rover.tabs[i].cwd[strlen(rover.tabs[i].cwd) - 1] != '/')
975 strcat(rover.tabs[i].cwd, "/");
976 rover.tab = 1;
977 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
978 init_marks(&rover.marks);
979 cd(1);
980 while (1) {
981 ch = rover_getch();
982 key = keyname(ch);
983 clear_message();
984 if (!strcmp(key, RVK_QUIT)) break;
985 else if (ch >= '0' && ch <= '9') {
986 rover.tab = ch - '0';
987 cd(0);
988 } else if (!strcmp(key, RVK_HELP)) {
989 ARGS[0] = "man";
990 ARGS[1] = "rover";
991 ARGS[2] = NULL;
992 spawn();
993 } else if (!strcmp(key, RVK_DOWN)) {
994 if (!rover.nfiles) continue;
995 ESEL = MIN(ESEL + 1, rover.nfiles - 1);
996 update_view();
997 } else if (!strcmp(key, RVK_UP)) {
998 if (!rover.nfiles) continue;
999 ESEL = MAX(ESEL - 1, 0);
1000 update_view();
1001 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
1002 if (!rover.nfiles) continue;
1003 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
1004 if (rover.nfiles > HEIGHT)
1005 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
1006 update_view();
1007 } else if (!strcmp(key, RVK_JUMP_UP)) {
1008 if (!rover.nfiles) continue;
1009 ESEL = MAX(ESEL - RV_JUMP, 0);
1010 SCROLL = MAX(SCROLL - RV_JUMP, 0);
1011 update_view();
1012 } else if (!strcmp(key, RVK_JUMP_TOP)) {
1013 if (!rover.nfiles) continue;
1014 ESEL = 0;
1015 update_view();
1016 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
1017 if (!rover.nfiles) continue;
1018 ESEL = rover.nfiles - 1;
1019 update_view();
1020 } else if (!strcmp(key, RVK_CD_DOWN)) {
1021 if (!rover.nfiles || !S_ISDIR(EMODE(ESEL))) continue;
1022 if (chdir(ENAME(ESEL)) == -1) {
1023 message(RED, "Cannot access \"%s\".", ENAME(ESEL));
1024 continue;
1026 strcat(CWD, ENAME(ESEL));
1027 cd(1);
1028 } else if (!strcmp(key, RVK_CD_UP)) {
1029 char *dirname, first;
1030 if (!strcmp(CWD, "/")) continue;
1031 CWD[strlen(CWD) - 1] = '\0';
1032 dirname = strrchr(CWD, '/') + 1;
1033 first = dirname[0];
1034 dirname[0] = '\0';
1035 cd(1);
1036 dirname[0] = first;
1037 dirname[strlen(dirname)] = '/';
1038 try_to_sel(dirname);
1039 dirname[0] = '\0';
1040 if (rover.nfiles > HEIGHT)
1041 SCROLL = ESEL - HEIGHT / 2;
1042 update_view();
1043 } else if (!strcmp(key, RVK_HOME)) {
1044 strcpy(CWD, getenv("HOME"));
1045 if (CWD[strlen(CWD) - 1] != '/')
1046 strcat(CWD, "/");
1047 cd(1);
1048 } else if (!strcmp(key, RVK_REFRESH)) {
1049 reload();
1050 } else if (!strcmp(key, RVK_SHELL)) {
1051 program = getenv("SHELL");
1052 if (program) {
1053 ARGS[0] = program;
1054 ARGS[1] = NULL;
1055 spawn();
1056 reload();
1058 } else if (!strcmp(key, RVK_VIEW)) {
1059 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1060 program = getenv("PAGER");
1061 if (program) {
1062 ARGS[0] = program;
1063 ARGS[1] = ENAME(ESEL);
1064 ARGS[2] = NULL;
1065 spawn();
1067 } else if (!strcmp(key, RVK_EDIT)) {
1068 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1069 program = getenv("EDITOR");
1070 if (program) {
1071 ARGS[0] = program;
1072 ARGS[1] = ENAME(ESEL);
1073 ARGS[2] = NULL;
1074 spawn();
1075 cd(0);
1077 } else if (!strcmp(key, RVK_SEARCH)) {
1078 int oldsel, oldscroll, length;
1079 if (!rover.nfiles) continue;
1080 oldsel = ESEL;
1081 oldscroll = SCROLL;
1082 start_line_edit("");
1083 update_input(RVP_SEARCH, RED);
1084 while ((edit_stat = get_line_edit()) == CONTINUE) {
1085 int sel;
1086 Color color = RED;
1087 length = strlen(INPUT);
1088 if (length) {
1089 for (sel = 0; sel < rover.nfiles; sel++)
1090 if (!strncmp(ENAME(sel), INPUT, length))
1091 break;
1092 if (sel < rover.nfiles) {
1093 color = GREEN;
1094 ESEL = sel;
1095 if (rover.nfiles > HEIGHT) {
1096 if (sel < 3)
1097 SCROLL = 0;
1098 else if (sel - 3 > rover.nfiles - HEIGHT)
1099 SCROLL = rover.nfiles - HEIGHT;
1100 else
1101 SCROLL = sel - 3;
1104 } else {
1105 ESEL = oldsel;
1106 SCROLL = oldscroll;
1108 update_view();
1109 update_input(RVP_SEARCH, color);
1111 if (edit_stat == CANCEL) {
1112 ESEL = oldsel;
1113 SCROLL = oldscroll;
1115 clear_message();
1116 update_view();
1117 } else if (!strcmp(key, RVK_TG_FILES)) {
1118 FLAGS ^= SHOW_FILES;
1119 reload();
1120 } else if (!strcmp(key, RVK_TG_DIRS)) {
1121 FLAGS ^= SHOW_DIRS;
1122 reload();
1123 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
1124 FLAGS ^= SHOW_HIDDEN;
1125 reload();
1126 } else if (!strcmp(key, RVK_NEW_FILE)) {
1127 int ok = 0;
1128 start_line_edit("");
1129 update_input(RVP_NEW_FILE, RED);
1130 while ((edit_stat = get_line_edit()) == CONTINUE) {
1131 int length = strlen(INPUT);
1132 ok = length;
1133 for (i = 0; i < rover.nfiles; i++) {
1134 if (
1135 !strncmp(ENAME(i), INPUT, length) &&
1136 (!strcmp(ENAME(i) + length, "") ||
1137 !strcmp(ENAME(i) + length, "/"))
1138 ) {
1139 ok = 0;
1140 break;
1143 update_input(RVP_NEW_FILE, ok ? GREEN : RED);
1145 clear_message();
1146 if (edit_stat == CONFIRM) {
1147 if (ok) {
1148 addfile(INPUT);
1149 cd(1);
1150 try_to_sel(INPUT);
1151 update_view();
1152 } else
1153 message(RED, "\"%s\" already exists.", INPUT);
1155 } else if (!strcmp(key, RVK_NEW_DIR)) {
1156 int ok = 0;
1157 start_line_edit("");
1158 update_input(RVP_NEW_DIR, RED);
1159 while ((edit_stat = get_line_edit()) == CONTINUE) {
1160 int length = strlen(INPUT);
1161 ok = length;
1162 for (i = 0; i < rover.nfiles; i++) {
1163 if (
1164 !strncmp(ENAME(i), INPUT, length) &&
1165 (!strcmp(ENAME(i) + length, "") ||
1166 !strcmp(ENAME(i) + length, "/"))
1167 ) {
1168 ok = 0;
1169 break;
1172 update_input(RVP_NEW_DIR, ok ? GREEN : RED);
1174 clear_message();
1175 if (edit_stat == CONFIRM) {
1176 if (ok) {
1177 adddir(INPUT);
1178 cd(1);
1179 strcat(INPUT, "/");
1180 try_to_sel(INPUT);
1181 update_view();
1182 } else
1183 message(RED, "\"%s\" already exists.", INPUT);
1185 } else if (!strcmp(key, RVK_RENAME)) {
1186 int ok = 0;
1187 char *last;
1188 int isdir;
1189 strcpy(INPUT, ENAME(ESEL));
1190 last = INPUT + strlen(INPUT) - 1;
1191 if ((isdir = *last == '/'))
1192 *last = '\0';
1193 start_line_edit(INPUT);
1194 update_input(RVP_RENAME, RED);
1195 while ((edit_stat = get_line_edit()) == CONTINUE) {
1196 int length = strlen(INPUT);
1197 ok = length;
1198 for (i = 0; i < rover.nfiles; i++)
1199 if (
1200 !strncmp(ENAME(i), INPUT, length) &&
1201 (!strcmp(ENAME(i) + length, "") ||
1202 !strcmp(ENAME(i) + length, "/"))
1203 ) {
1204 ok = 0;
1205 break;
1207 update_input(RVP_RENAME, ok ? GREEN : RED);
1209 clear_message();
1210 if (edit_stat == CONFIRM) {
1211 if (isdir)
1212 strcat(INPUT, "/");
1213 if (ok) {
1214 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1215 del_mark(&rover.marks, ENAME(ESEL));
1216 add_mark(&rover.marks, CWD, INPUT);
1218 cd(1);
1219 try_to_sel(INPUT);
1220 update_view();
1221 } else
1222 message(RED, "\"%s\" already exists.", INPUT);
1224 } else if (!strcmp(key, RVK_DELETE)) {
1225 if (rover.nfiles) {
1226 message(YELLOW, "Delete \"%s\"? (Y to confirm)", ENAME(ESEL));
1227 if (rover_getch() == 'Y') {
1228 const char *name = ENAME(ESEL);
1229 int ret = S_ISDIR(EMODE(ESEL)) ? deldir(name) : delfile(name);
1230 reload();
1231 if (ret)
1232 message(RED, "Could not delete \"%s\".", ENAME(ESEL));
1233 } else
1234 clear_message();
1235 } else
1236 message(RED, "No entry selected for deletion.");
1237 } else if (!strcmp(key, RVK_TG_MARK)) {
1238 if (MARKED(ESEL))
1239 del_mark(&rover.marks, ENAME(ESEL));
1240 else
1241 add_mark(&rover.marks, CWD, ENAME(ESEL));
1242 MARKED(ESEL) = !MARKED(ESEL);
1243 ESEL = (ESEL + 1) % rover.nfiles;
1244 update_view();
1245 } else if (!strcmp(key, RVK_INVMARK)) {
1246 for (i = 0; i < rover.nfiles; i++) {
1247 if (MARKED(i))
1248 del_mark(&rover.marks, ENAME(i));
1249 else
1250 add_mark(&rover.marks, CWD, ENAME(i));
1251 MARKED(i) = !MARKED(i);
1253 update_view();
1254 } else if (!strcmp(key, RVK_MARKALL)) {
1255 for (i = 0; i < rover.nfiles; i++)
1256 if (!MARKED(i)) {
1257 add_mark(&rover.marks, CWD, ENAME(i));
1258 MARKED(i) = 1;
1260 update_view();
1261 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1262 if (rover.marks.nentries) {
1263 message(YELLOW, "Delete all marked entries? (Y to confirm)");
1264 if (rover_getch() == 'Y')
1265 process_marked(NULL, delfile, deldir, "Deleting", "Deleted");
1266 else
1267 clear_message();
1268 } else
1269 message(RED, "No entries marked for deletion.");
1270 } else if (!strcmp(key, RVK_MARK_COPY)) {
1271 if (rover.marks.nentries)
1272 process_marked(adddir, cpyfile, NULL, "Copying", "Copied");
1273 else
1274 message(RED, "No entries marked for copying.");
1275 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1276 if (rover.marks.nentries)
1277 process_marked(adddir, movfile, deldir, "Moving", "Moved");
1278 else
1279 message(RED, "No entries marked for moving.");
1282 if (rover.nfiles)
1283 free_rows(&rover.rows, rover.nfiles);
1284 free_marks(&rover.marks);
1285 delwin(rover.window);
1286 if (save_cwd_file != NULL) {
1287 fputs(CWD, save_cwd_file);
1288 fclose(save_cwd_file);
1290 return 0;