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 /* 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 /* Listing view parameters. */
41 #define HEIGHT (LINES-4)
42 #define STATUSPOS (COLS-16)
44 /* Listing view flags. */
45 #define SHOW_FILES 0x01u
46 #define SHOW_DIRS 0x02u
47 #define SHOW_HIDDEN 0x04u
49 /* Marks parameters. */
50 #define BULK_INIT 5
51 #define BULK_THRESH 256
53 /* Information associated to each entry in listing. */
54 typedef struct Row {
55 char *name;
56 off_t size;
57 mode_t mode;
58 int islink;
59 int marked;
60 } Row;
62 /* Dynamic array of marked entries. */
63 typedef struct Marks {
64 char dirpath[PATH_MAX];
65 int bulk;
66 int nentries;
67 char **entries;
68 } Marks;
70 /* Line editing state. */
71 typedef struct Edit {
72 wchar_t buffer[BUFLEN+1];
73 int left, right;
74 } Edit;
76 /* Each tab only stores the following information. */
77 typedef struct Tab {
78 int scroll;
79 int esel;
80 uint8_t flags;
81 char cwd[PATH_MAX];
82 } Tab;
84 typedef struct Prog {
85 off_t partial;
86 off_t total;
87 const char *msg;
88 } Prog;
90 /* Global state. */
91 static struct Rover {
92 int tab;
93 int nfiles;
94 Row *rows;
95 WINDOW *window;
96 Marks marks;
97 Edit edit;
98 int edit_scroll;
99 volatile sig_atomic_t pending_winch;
100 Prog prog;
101 Tab tabs[10];
102 } rover;
104 /* Macros for accessing global state. */
105 #define ENAME(I) rover.rows[I].name
106 #define ESIZE(I) rover.rows[I].size
107 #define EMODE(I) rover.rows[I].mode
108 #define ISLINK(I) rover.rows[I].islink
109 #define MARKED(I) rover.rows[I].marked
110 #define SCROLL rover.tabs[rover.tab].scroll
111 #define ESEL rover.tabs[rover.tab].esel
112 #define FLAGS rover.tabs[rover.tab].flags
113 #define CWD rover.tabs[rover.tab].cwd
115 /* Helpers. */
116 #define MIN(A, B) ((A) < (B) ? (A) : (B))
117 #define MAX(A, B) ((A) > (B) ? (A) : (B))
118 #define ISDIR(E) (strchr((E), '/') != NULL)
120 /* Line Editing Macros. */
121 #define EDIT_FULL(E) ((E).left == (E).right)
122 #define EDIT_CAN_LEFT(E) ((E).left)
123 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
124 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
125 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
126 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
127 #define EDIT_BACKSPACE(E) (E).left--
128 #define EDIT_DELETE(E) (E).right++
129 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
131 typedef enum EditStat {CONTINUE, CONFIRM, CANCEL} EditStat;
132 typedef enum Color {DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK} Color;
133 typedef int (*PROCESS)(const char *path);
135 static void
136 init_marks(Marks *marks)
138 strcpy(marks->dirpath, "");
139 marks->bulk = BULK_INIT;
140 marks->nentries = 0;
141 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
144 /* Unmark all entries. */
145 static void
146 mark_none(Marks *marks)
148 int i;
150 strcpy(marks->dirpath, "");
151 for (i = 0; i < marks->bulk && marks->nentries; i++)
152 if (marks->entries[i]) {
153 free(marks->entries[i]);
154 marks->entries[i] = NULL;
155 marks->nentries--;
157 if (marks->bulk > BULK_THRESH) {
158 /* Reset bulk to free some memory. */
159 free(marks->entries);
160 marks->bulk = BULK_INIT;
161 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
165 static void
166 add_mark(Marks *marks, char *dirpath, char *entry)
168 int i;
170 if (!strcmp(marks->dirpath, dirpath)) {
171 /* Append mark to directory. */
172 if (marks->nentries == marks->bulk) {
173 /* Expand bulk to accomodate new entry. */
174 int extra = marks->bulk / 2;
175 marks->bulk += extra; /* bulk *= 1.5; */
176 marks->entries = realloc(marks->entries,
177 marks->bulk * sizeof *marks->entries);
178 memset(&marks->entries[marks->nentries], 0,
179 extra * sizeof *marks->entries);
180 i = marks->nentries;
181 } else {
182 /* Search for empty slot (there must be one). */
183 for (i = 0; i < marks->bulk; i++)
184 if (!marks->entries[i])
185 break;
187 } else {
188 /* Directory changed. Discard old marks. */
189 mark_none(marks);
190 strcpy(marks->dirpath, dirpath);
191 i = 0;
193 marks->entries[i] = malloc(strlen(entry) + 1);
194 strcpy(marks->entries[i], entry);
195 marks->nentries++;
198 static void
199 del_mark(Marks *marks, char *entry)
201 int i;
203 if (marks->nentries > 1) {
204 for (i = 0; i < marks->bulk; i++)
205 if (marks->entries[i] && !strcmp(marks->entries[i], entry))
206 break;
207 free(marks->entries[i]);
208 marks->entries[i] = NULL;
209 marks->nentries--;
210 } else
211 mark_none(marks);
214 static void
215 free_marks(Marks *marks)
217 int i;
219 for (i = 0; i < marks->bulk && marks->nentries; i++)
220 if (marks->entries[i]) {
221 free(marks->entries[i]);
222 marks->nentries--;
224 free(marks->entries);
227 static void
228 handle_winch(int sig)
230 rover.pending_winch = 1;
233 static void
234 enable_handlers()
236 struct sigaction sa;
238 memset(&sa, 0, sizeof (struct sigaction));
239 sa.sa_handler = handle_winch;
240 sigaction(SIGWINCH, &sa, NULL);
243 static void
244 disable_handlers()
246 struct sigaction sa;
248 memset(&sa, 0, sizeof (struct sigaction));
249 sa.sa_handler = SIG_DFL;
250 sigaction(SIGWINCH, &sa, NULL);
253 static void update_view();
255 /* Handle any signals received since last call. */
256 static void
257 sync_signals()
259 if (rover.pending_winch) {
260 /* SIGWINCH received: resize application accordingly. */
261 delwin(rover.window);
262 endwin();
263 refresh();
264 clear();
265 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
266 if (HEIGHT < rover.nfiles && SCROLL + HEIGHT > rover.nfiles)
267 SCROLL = ESEL - HEIGHT;
268 update_view();
269 rover.pending_winch = 0;
273 /* This function must be used in place of getch().
274 It handles signals while waiting for user input. */
275 static int
276 rover_getch()
278 int ch;
280 while ((ch = getch()) == ERR)
281 sync_signals();
282 return ch;
285 /* This function must be used in place of get_wch().
286 It handles signals while waiting for user input. */
287 static int
288 rover_get_wch(wint_t *wch)
290 wint_t ret;
292 while ((ret = get_wch(wch)) == (wint_t) ERR)
293 sync_signals();
294 return ret;
297 /* Do a fork-exec to external program (e.g. $EDITOR). */
298 static void
299 spawn(char **args)
301 pid_t pid;
302 int status;
304 setenv("RVSEL", rover.nfiles ? ENAME(ESEL) : "", 1);
305 pid = fork();
306 if (pid > 0) {
307 /* fork() succeeded. */
308 disable_handlers();
309 endwin();
310 waitpid(pid, &status, 0);
311 enable_handlers();
312 kill(getpid(), SIGWINCH);
313 } else if (pid == 0) {
314 /* Child process. */
315 execvp(args[0], args);
319 /* Curses setup. */
320 static void
321 init_term()
323 setlocale(LC_ALL, "");
324 initscr();
325 cbreak(); /* Get one character at a time. */
326 timeout(100); /* For getch(). */
327 noecho();
328 nonl(); /* No NL->CR/NL on output. */
329 intrflush(stdscr, FALSE);
330 keypad(stdscr, TRUE);
331 curs_set(FALSE); /* Hide blinking cursor. */
332 if (has_colors()) {
333 short bg;
334 start_color();
335 #ifdef NCURSES_EXT_FUNCS
336 use_default_colors();
337 bg = -1;
338 #else
339 bg = COLOR_BLACK;
340 #endif
341 init_pair(RED, COLOR_RED, bg);
342 init_pair(GREEN, COLOR_GREEN, bg);
343 init_pair(YELLOW, COLOR_YELLOW, bg);
344 init_pair(BLUE, COLOR_BLUE, bg);
345 init_pair(CYAN, COLOR_CYAN, bg);
346 init_pair(MAGENTA, COLOR_MAGENTA, bg);
347 init_pair(WHITE, COLOR_WHITE, bg);
348 init_pair(BLACK, COLOR_BLACK, bg);
350 atexit((void (*)(void)) endwin);
351 enable_handlers();
354 /* Update the listing view. */
355 static void
356 update_view()
358 int i, j;
359 int numsize;
360 int ishidden;
361 int marking;
363 mvhline(0, 0, ' ', COLS);
364 attr_on(A_BOLD, NULL);
365 color_set(RVC_TABNUM, NULL);
366 mvaddch(0, COLS - 2, rover.tab + '0');
367 attr_off(A_BOLD, NULL);
368 if (rover.marks.nentries) {
369 numsize = snprintf(BUF1, BUFLEN, "%d", rover.marks.nentries);
370 color_set(RVC_MARKS, NULL);
371 mvaddstr(0, COLS - 3 - numsize, BUF1);
372 } else
373 numsize = -1;
374 color_set(RVC_CWD, NULL);
375 mbstowcs(WBUF, CWD, PATH_MAX);
376 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
377 wcolor_set(rover.window, RVC_BORDER, NULL);
378 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
379 ESEL = MAX(MIN(ESEL, rover.nfiles - 1), 0);
380 /* Selection might not be visible, due to cursor wrapping or window
381 shrinking. In that case, the scroll must be moved to make it visible. */
382 if (rover.nfiles > HEIGHT) {
383 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
384 SCROLL = MIN(MAX(SCROLL, 0), rover.nfiles - HEIGHT);
385 } else
386 SCROLL = 0;
387 marking = !strcmp(CWD, rover.marks.dirpath);
388 for (i = 0, j = SCROLL; i < HEIGHT && j < rover.nfiles; i++, j++) {
389 ishidden = ENAME(j)[0] == '.';
390 if (j == ESEL)
391 wattr_on(rover.window, A_REVERSE, NULL);
392 if (ISLINK(j))
393 wcolor_set(rover.window, RVC_LINK, NULL);
394 else if (ishidden)
395 wcolor_set(rover.window, RVC_HIDDEN, NULL);
396 else if (S_ISREG(EMODE(j))) {
397 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
398 wcolor_set(rover.window, RVC_EXEC, NULL);
399 else
400 wcolor_set(rover.window, RVC_REG, NULL);
401 } else if (S_ISDIR(EMODE(j)))
402 wcolor_set(rover.window, RVC_DIR, NULL);
403 else if (S_ISCHR(EMODE(j)))
404 wcolor_set(rover.window, RVC_CHR, NULL);
405 else if (S_ISBLK(EMODE(j)))
406 wcolor_set(rover.window, RVC_BLK, NULL);
407 else if (S_ISFIFO(EMODE(j)))
408 wcolor_set(rover.window, RVC_FIFO, NULL);
409 else if (S_ISSOCK(EMODE(j)))
410 wcolor_set(rover.window, RVC_SOCK, NULL);
411 if (S_ISDIR(EMODE(j))) {
412 mbstowcs(WBUF, ENAME(j), PATH_MAX);
413 if (ISLINK(j))
414 wcscat(WBUF, L"/");
415 } else {
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);
430 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
431 mvwaddnwstr(rover.window, i + 1, 2, WBUF, COLS - 4);
432 if (marking && MARKED(j)) {
433 wcolor_set(rover.window, RVC_MARKS, NULL);
434 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
435 } else
436 mvwaddch(rover.window, i + 1, 1, ' ');
437 if (j == ESEL)
438 wattr_off(rover.window, A_REVERSE, NULL);
440 for (; i < HEIGHT; i++)
441 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
442 if (rover.nfiles > HEIGHT) {
443 int center, height;
444 center = (SCROLL + HEIGHT / 2) * HEIGHT / rover.nfiles;
445 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
446 if (!height) height = 1;
447 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
448 mvwvline(rover.window, center-height/2+1, COLS-1, RVS_SCROLLBAR, height);
450 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
451 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
452 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
453 if (!rover.nfiles)
454 strcpy(BUF2, "0/0");
455 else
456 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, rover.nfiles);
457 snprintf(BUF1+3, BUFLEN-3, "%12s", BUF2);
458 color_set(RVC_STATUS, NULL);
459 mvaddstr(LINES - 1, STATUSPOS, BUF1);
460 wrefresh(rover.window);
463 /* Show a message on the status bar. */
464 static void
465 message(Color color, char *fmt, ...)
467 int len, pos;
468 va_list args;
470 va_start(args, fmt);
471 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
472 va_end(args);
473 len = strlen(BUF1);
474 pos = (STATUSPOS - len) / 2;
475 attr_on(A_BOLD, NULL);
476 color_set(color, NULL);
477 mvaddstr(LINES - 1, pos, BUF1);
478 color_set(DEFAULT, NULL);
479 attr_off(A_BOLD, NULL);
482 /* Clear message area, leaving only status info. */
483 static void
484 clear_message()
486 mvhline(LINES - 1, 0, ' ', STATUSPOS);
489 /* Comparison used to sort listing entries. */
490 static int
491 rowcmp(const void *a, const void *b)
493 int isdir1, isdir2, cmpdir;
494 const Row *r1 = a;
495 const Row *r2 = b;
496 isdir1 = S_ISDIR(r1->mode);
497 isdir2 = S_ISDIR(r2->mode);
498 cmpdir = isdir2 - isdir1;
499 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
502 /* Get all entries in current working directory. */
503 static int
504 ls(Row **rowsp, uint8_t flags)
506 DIR *dp;
507 struct dirent *ep;
508 struct stat statbuf;
509 Row *rows;
510 int i, n;
512 if(!(dp = opendir("."))) return -1;
513 n = -2; /* We don't want the entries "." and "..". */
514 while (readdir(dp)) n++;
515 rewinddir(dp);
516 rows = malloc(n * sizeof *rows);
517 i = 0;
518 while ((ep = readdir(dp))) {
519 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
520 continue;
521 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
522 continue;
523 lstat(ep->d_name, &statbuf);
524 rows[i].islink = S_ISLNK(statbuf.st_mode);
525 stat(ep->d_name, &statbuf);
526 if (S_ISDIR(statbuf.st_mode)) {
527 if (flags & SHOW_DIRS) {
528 rows[i].name = malloc(strlen(ep->d_name) + 2);
529 strcpy(rows[i].name, ep->d_name);
530 if (!rows[i].islink)
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 lstat(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 strcpy(dstpath, CWD);
790 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
791 ret = lstat(srcpath, &st);
792 if (ret < 0) return ret;
793 if (S_ISLNK(st.st_mode)) {
794 ret = readlink(srcpath, BUF1, BUFLEN);
795 if (ret < 0) return ret;
796 BUF1[ret] = '\0';
797 ret = symlink(BUF1, dstpath);
798 } else {
799 ret = src = open(srcpath, O_RDONLY);
800 if (ret < 0) return ret;
801 ret = dst = creat(dstpath, st.st_mode);
802 if (ret < 0) return ret;
803 while ((size = read(src, buf, BUFSIZ)) > 0) {
804 write(dst, buf, size);
805 update_progress(size);
806 sync_signals();
808 close(src);
809 close(dst);
810 ret = 0;
812 return ret;
814 static int adddir(const char *path) {
815 int ret;
816 struct stat st;
818 ret = stat(CWD, &st);
819 if (ret < 0) return ret;
820 return mkdir(path, st.st_mode);
822 static int movfile(const char *srcpath) {
823 int ret;
824 struct stat st;
825 char dstpath[PATH_MAX];
827 strcpy(dstpath, CWD);
828 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
829 ret = rename(srcpath, dstpath);
830 if (ret == 0) {
831 ret = lstat(dstpath, &st);
832 if (ret < 0) return ret;
833 update_progress(st.st_size);
834 } else if (errno == EXDEV) {
835 ret = cpyfile(srcpath);
836 if (ret < 0) return ret;
837 ret = unlink(srcpath);
839 return ret;
842 static void
843 start_line_edit(const char *init_input)
845 curs_set(TRUE);
846 strncpy(INPUT, init_input, BUFLEN);
847 rover.edit.left = mbstowcs(rover.edit.buffer, init_input, BUFLEN);
848 rover.edit.right = BUFLEN - 1;
849 rover.edit.buffer[BUFLEN] = L'\0';
850 rover.edit_scroll = 0;
853 /* Read input and change editing state accordingly. */
854 static EditStat
855 get_line_edit()
857 wchar_t eraser, killer, wch;
858 int ret, length;
860 ret = rover_get_wch((wint_t *) &wch);
861 erasewchar(&eraser);
862 killwchar(&killer);
863 if (ret == KEY_CODE_YES) {
864 if (wch == KEY_ENTER) {
865 curs_set(FALSE);
866 return CONFIRM;
867 } else if (wch == KEY_LEFT) {
868 if (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
869 } else if (wch == KEY_RIGHT) {
870 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
871 } else if (wch == KEY_UP) {
872 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
873 } else if (wch == KEY_DOWN) {
874 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
875 } else if (wch == KEY_BACKSPACE) {
876 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
877 } else if (wch == KEY_DC) {
878 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
880 } else {
881 if (wch == L'\r' || wch == L'\n') {
882 curs_set(FALSE);
883 return CONFIRM;
884 } else if (wch == L'\t') {
885 curs_set(FALSE);
886 return CANCEL;
887 } else if (wch == eraser) {
888 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
889 } else if (wch == killer) {
890 EDIT_CLEAR(rover.edit);
891 clear_message();
892 } else if (iswprint(wch)) {
893 if (!EDIT_FULL(rover.edit)) EDIT_INSERT(rover.edit, wch);
896 /* Encode edit contents in INPUT. */
897 rover.edit.buffer[rover.edit.left] = L'\0';
898 length = wcstombs(INPUT, rover.edit.buffer, BUFLEN);
899 wcstombs(&INPUT[length], &rover.edit.buffer[rover.edit.right+1],
900 BUFLEN-length);
901 return CONTINUE;
904 /* Update line input on the screen. */
905 static void
906 update_input(const char *prompt, Color color)
908 int plen, ilen, maxlen;
910 plen = strlen(prompt);
911 ilen = mbstowcs(NULL, INPUT, 0);
912 maxlen = STATUSPOS - plen - 2;
913 if (ilen - rover.edit_scroll < maxlen)
914 rover.edit_scroll = MAX(ilen - maxlen, 0);
915 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
916 rover.edit_scroll = rover.edit.left - maxlen;
917 else if (rover.edit.left < rover.edit_scroll)
918 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
919 color_set(RVC_PROMPT, NULL);
920 mvaddstr(LINES - 1, 0, prompt);
921 color_set(color, NULL);
922 mbstowcs(WBUF, INPUT, COLS);
923 mvaddnwstr(LINES - 1, plen, &WBUF[rover.edit_scroll], maxlen);
924 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
925 color_set(DEFAULT, NULL);
926 if (rover.edit_scroll)
927 mvaddch(LINES - 1, plen - 1, '<');
928 if (ilen > rover.edit_scroll + maxlen)
929 mvaddch(LINES - 1, plen + maxlen, '>');
930 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
933 int
934 main(int argc, char *argv[])
936 int i, ch;
937 char *program;
938 char *entry;
939 const char *key;
940 DIR *d;
941 EditStat edit_stat;
942 FILE *save_cwd_file = NULL;
943 FILE *save_marks_file = NULL;
945 if (argc >= 2) {
946 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
947 printf("rover %s\n", RV_VERSION);
948 return 0;
949 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
950 printf(
951 "Usage: rover"
952 " [-d|--save-cwd FILE]"
953 " [-m|--save-marks FILE]"
954 " [DIR [DIR [DIR [...]]]]\n"
955 " Browse current directory or the ones specified.\n"
956 " If FILE is given, write last visited path to it.\n\n"
957 " or: rover -h|--help\n"
958 " Print this help message and exit.\n\n"
959 " or: rover -v|--version\n"
960 " Print program version and exit.\n\n"
961 "See rover(1) for more information.\n\n"
962 "Rover homepage: <https://github.com/lecram/rover>.\n"
963 );
964 return 0;
965 } else if (!strcmp(argv[1], "-d") || !strcmp(argv[1], "--save-cwd")) {
966 if (argc > 2) {
967 save_cwd_file = fopen(argv[2], "w");
968 argc -= 2; argv += 2;
969 } else {
970 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
971 return 1;
973 } else if (!strcmp(argv[1], "-m") || !strcmp(argv[1], "--save-marks")) {
974 if (argc > 2) {
975 save_marks_file = fopen(argv[2], "a");
976 argc -= 2; argv += 2;
977 } else {
978 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
979 return 1;
983 init_term();
984 rover.nfiles = 0;
985 for (i = 0; i < 10; i++) {
986 rover.tabs[i].esel = rover.tabs[i].scroll = 0;
987 rover.tabs[i].flags = SHOW_FILES | SHOW_DIRS;
989 strcpy(rover.tabs[0].cwd, getenv("HOME"));
990 for (i = 1; i < argc && i < 10; i++) {
991 if ((d = opendir(argv[i]))) {
992 realpath(argv[i], rover.tabs[i].cwd);
993 closedir(d);
994 } else
995 strcpy(rover.tabs[i].cwd, rover.tabs[0].cwd);
997 getcwd(rover.tabs[i].cwd, PATH_MAX);
998 for (i++; i < 10; i++)
999 strcpy(rover.tabs[i].cwd, rover.tabs[i-1].cwd);
1000 for (i = 0; i < 10; i++)
1001 if (rover.tabs[i].cwd[strlen(rover.tabs[i].cwd) - 1] != '/')
1002 strcat(rover.tabs[i].cwd, "/");
1003 rover.tab = 1;
1004 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1005 init_marks(&rover.marks);
1006 cd(1);
1007 while (1) {
1008 ch = rover_getch();
1009 key = keyname(ch);
1010 clear_message();
1011 if (!strcmp(key, RVK_QUIT)) break;
1012 else if (ch >= '0' && ch <= '9') {
1013 rover.tab = ch - '0';
1014 cd(0);
1015 } else if (!strcmp(key, RVK_HELP)) {
1016 spawn((char *[]) {"man", "rover", NULL});
1017 } else if (!strcmp(key, RVK_DOWN)) {
1018 if (!rover.nfiles) continue;
1019 ESEL = MIN(ESEL + 1, rover.nfiles - 1);
1020 update_view();
1021 } else if (!strcmp(key, RVK_UP)) {
1022 if (!rover.nfiles) continue;
1023 ESEL = MAX(ESEL - 1, 0);
1024 update_view();
1025 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
1026 if (!rover.nfiles) continue;
1027 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
1028 if (rover.nfiles > HEIGHT)
1029 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
1030 update_view();
1031 } else if (!strcmp(key, RVK_JUMP_UP)) {
1032 if (!rover.nfiles) continue;
1033 ESEL = MAX(ESEL - RV_JUMP, 0);
1034 SCROLL = MAX(SCROLL - RV_JUMP, 0);
1035 update_view();
1036 } else if (!strcmp(key, RVK_JUMP_TOP)) {
1037 if (!rover.nfiles) continue;
1038 ESEL = 0;
1039 update_view();
1040 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
1041 if (!rover.nfiles) continue;
1042 ESEL = rover.nfiles - 1;
1043 update_view();
1044 } else if (!strcmp(key, RVK_CD_DOWN)) {
1045 if (!rover.nfiles || !S_ISDIR(EMODE(ESEL))) continue;
1046 if (chdir(ENAME(ESEL)) == -1) {
1047 message(RED, "Cannot access \"%s\".", ENAME(ESEL));
1048 continue;
1050 strcat(CWD, ENAME(ESEL));
1051 cd(1);
1052 } else if (!strcmp(key, RVK_CD_UP)) {
1053 char *dirname, first;
1054 if (!strcmp(CWD, "/")) continue;
1055 CWD[strlen(CWD) - 1] = '\0';
1056 dirname = strrchr(CWD, '/') + 1;
1057 first = dirname[0];
1058 dirname[0] = '\0';
1059 cd(1);
1060 dirname[0] = first;
1061 dirname[strlen(dirname)] = '/';
1062 try_to_sel(dirname);
1063 dirname[0] = '\0';
1064 if (rover.nfiles > HEIGHT)
1065 SCROLL = ESEL - HEIGHT / 2;
1066 update_view();
1067 } else if (!strcmp(key, RVK_HOME)) {
1068 strcpy(CWD, getenv("HOME"));
1069 if (CWD[strlen(CWD) - 1] != '/')
1070 strcat(CWD, "/");
1071 cd(1);
1072 } else if (!strcmp(key, RVK_REFRESH)) {
1073 reload();
1074 } else if (!strcmp(key, RVK_SHELL)) {
1075 program = getenv("SHELL");
1076 if (program) {
1077 #ifdef RV_SHELL
1078 spawn((char *[]) {RV_SHELL, "-c", program, NULL});
1079 #else
1080 spawn((char *[]) {program, NULL});
1081 #endif
1082 reload();
1084 } else if (!strcmp(key, RVK_VIEW)) {
1085 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1086 program = getenv("PAGER");
1087 if (program) {
1088 #ifdef RV_SHELL
1089 strncpy(BUF1, program, BUFLEN - 1);
1090 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
1091 strncat(BUF1, ENAME(ESEL),
1092 BUFLEN - strlen(program) - strlen(ENAME(ESEL)) - 2);
1093 spawn((char *[]) {RV_SHELL, "-c", BUF1, NULL});
1094 #else
1095 spawn((char *[]) {program, ENAME(ESEL), NULL});
1096 #endif
1098 } else if (!strcmp(key, RVK_EDIT)) {
1099 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1100 program = getenv("EDITOR");
1101 if (program) {
1102 #ifdef RV_SHELL
1103 strncpy(BUF1, program, BUFLEN - 1);
1104 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
1105 strncat(BUF1, ENAME(ESEL),
1106 BUFLEN - strlen(program) - strlen(ENAME(ESEL)) - 2);
1107 spawn((char *[]) {RV_SHELL, "-c", BUF1, NULL});
1108 #else
1109 spawn((char *[]) {program, ENAME(ESEL), NULL});
1110 #endif
1111 cd(0);
1113 } else if (!strcmp(key, RVK_SEARCH)) {
1114 int oldsel, oldscroll, length;
1115 if (!rover.nfiles) continue;
1116 oldsel = ESEL;
1117 oldscroll = SCROLL;
1118 start_line_edit("");
1119 update_input(RVP_SEARCH, RED);
1120 while ((edit_stat = get_line_edit()) == CONTINUE) {
1121 int sel;
1122 Color color = RED;
1123 length = strlen(INPUT);
1124 if (length) {
1125 for (sel = 0; sel < rover.nfiles; sel++)
1126 if (!strncmp(ENAME(sel), INPUT, length))
1127 break;
1128 if (sel < rover.nfiles) {
1129 color = GREEN;
1130 ESEL = sel;
1131 if (rover.nfiles > HEIGHT) {
1132 if (sel < 3)
1133 SCROLL = 0;
1134 else if (sel - 3 > rover.nfiles - HEIGHT)
1135 SCROLL = rover.nfiles - HEIGHT;
1136 else
1137 SCROLL = sel - 3;
1140 } else {
1141 ESEL = oldsel;
1142 SCROLL = oldscroll;
1144 update_view();
1145 update_input(RVP_SEARCH, color);
1147 if (edit_stat == CANCEL) {
1148 ESEL = oldsel;
1149 SCROLL = oldscroll;
1151 clear_message();
1152 update_view();
1153 } else if (!strcmp(key, RVK_TG_FILES)) {
1154 FLAGS ^= SHOW_FILES;
1155 reload();
1156 } else if (!strcmp(key, RVK_TG_DIRS)) {
1157 FLAGS ^= SHOW_DIRS;
1158 reload();
1159 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
1160 FLAGS ^= SHOW_HIDDEN;
1161 reload();
1162 } else if (!strcmp(key, RVK_NEW_FILE)) {
1163 int ok = 0;
1164 start_line_edit("");
1165 update_input(RVP_NEW_FILE, RED);
1166 while ((edit_stat = get_line_edit()) == CONTINUE) {
1167 int length = strlen(INPUT);
1168 ok = length;
1169 for (i = 0; i < rover.nfiles; i++) {
1170 if (
1171 !strncmp(ENAME(i), INPUT, length) &&
1172 (!strcmp(ENAME(i) + length, "") ||
1173 !strcmp(ENAME(i) + length, "/"))
1174 ) {
1175 ok = 0;
1176 break;
1179 update_input(RVP_NEW_FILE, ok ? GREEN : RED);
1181 clear_message();
1182 if (edit_stat == CONFIRM) {
1183 if (ok) {
1184 if (addfile(INPUT) == 0) {
1185 cd(1);
1186 try_to_sel(INPUT);
1187 update_view();
1188 } else
1189 message(RED, "Could not create \"%s\".", INPUT);
1190 } else
1191 message(RED, "\"%s\" already exists.", INPUT);
1193 } else if (!strcmp(key, RVK_NEW_DIR)) {
1194 int ok = 0;
1195 start_line_edit("");
1196 update_input(RVP_NEW_DIR, RED);
1197 while ((edit_stat = get_line_edit()) == CONTINUE) {
1198 int length = strlen(INPUT);
1199 ok = length;
1200 for (i = 0; i < rover.nfiles; i++) {
1201 if (
1202 !strncmp(ENAME(i), INPUT, length) &&
1203 (!strcmp(ENAME(i) + length, "") ||
1204 !strcmp(ENAME(i) + length, "/"))
1205 ) {
1206 ok = 0;
1207 break;
1210 update_input(RVP_NEW_DIR, ok ? GREEN : RED);
1212 clear_message();
1213 if (edit_stat == CONFIRM) {
1214 if (ok) {
1215 if (adddir(INPUT) == 0) {
1216 cd(1);
1217 strcat(INPUT, "/");
1218 try_to_sel(INPUT);
1219 update_view();
1220 } else
1221 message(RED, "Could not create \"%s/\".", INPUT);
1222 } else
1223 message(RED, "\"%s\" already exists.", INPUT);
1225 } else if (!strcmp(key, RVK_RENAME)) {
1226 int ok = 0;
1227 char *last;
1228 int isdir;
1229 strcpy(INPUT, ENAME(ESEL));
1230 last = INPUT + strlen(INPUT) - 1;
1231 if ((isdir = *last == '/'))
1232 *last = '\0';
1233 start_line_edit(INPUT);
1234 update_input(RVP_RENAME, RED);
1235 while ((edit_stat = get_line_edit()) == CONTINUE) {
1236 int length = strlen(INPUT);
1237 ok = length;
1238 for (i = 0; i < rover.nfiles; i++)
1239 if (
1240 !strncmp(ENAME(i), INPUT, length) &&
1241 (!strcmp(ENAME(i) + length, "") ||
1242 !strcmp(ENAME(i) + length, "/"))
1243 ) {
1244 ok = 0;
1245 break;
1247 update_input(RVP_RENAME, ok ? GREEN : RED);
1249 clear_message();
1250 if (edit_stat == CONFIRM) {
1251 if (isdir)
1252 strcat(INPUT, "/");
1253 if (ok) {
1254 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1255 del_mark(&rover.marks, ENAME(ESEL));
1256 add_mark(&rover.marks, CWD, INPUT);
1258 cd(1);
1259 try_to_sel(INPUT);
1260 update_view();
1261 } else
1262 message(RED, "\"%s\" already exists.", INPUT);
1264 } else if (!strcmp(key, RVK_DELETE)) {
1265 if (rover.nfiles) {
1266 message(YELLOW, "Delete \"%s\"? (Y/n)", ENAME(ESEL));
1267 if (rover_getch() == 'Y') {
1268 const char *name = ENAME(ESEL);
1269 int ret = ISDIR(ENAME(ESEL)) ? deldir(name) : delfile(name);
1270 reload();
1271 if (ret)
1272 message(RED, "Could not delete \"%s\".", ENAME(ESEL));
1273 } else
1274 clear_message();
1275 } else
1276 message(RED, "No entry selected for deletion.");
1277 } else if (!strcmp(key, RVK_TG_MARK)) {
1278 if (MARKED(ESEL))
1279 del_mark(&rover.marks, ENAME(ESEL));
1280 else
1281 add_mark(&rover.marks, CWD, ENAME(ESEL));
1282 MARKED(ESEL) = !MARKED(ESEL);
1283 ESEL = (ESEL + 1) % rover.nfiles;
1284 update_view();
1285 } else if (!strcmp(key, RVK_INVMARK)) {
1286 for (i = 0; i < rover.nfiles; i++) {
1287 if (MARKED(i))
1288 del_mark(&rover.marks, ENAME(i));
1289 else
1290 add_mark(&rover.marks, CWD, ENAME(i));
1291 MARKED(i) = !MARKED(i);
1293 update_view();
1294 } else if (!strcmp(key, RVK_MARKALL)) {
1295 for (i = 0; i < rover.nfiles; i++)
1296 if (!MARKED(i)) {
1297 add_mark(&rover.marks, CWD, ENAME(i));
1298 MARKED(i) = 1;
1300 update_view();
1301 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1302 if (rover.marks.nentries) {
1303 message(YELLOW, "Delete all marked entries? (Y/n)");
1304 if (rover_getch() == 'Y')
1305 process_marked(NULL, delfile, deldir, "Deleting", "Deleted");
1306 else
1307 clear_message();
1308 } else
1309 message(RED, "No entries marked for deletion.");
1310 } else if (!strcmp(key, RVK_MARK_COPY)) {
1311 if (rover.marks.nentries)
1312 process_marked(adddir, cpyfile, NULL, "Copying", "Copied");
1313 else
1314 message(RED, "No entries marked for copying.");
1315 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1316 if (rover.marks.nentries)
1317 process_marked(adddir, movfile, deldir, "Moving", "Moved");
1318 else
1319 message(RED, "No entries marked for moving.");
1322 if (rover.nfiles)
1323 free_rows(&rover.rows, rover.nfiles);
1324 delwin(rover.window);
1325 if (save_cwd_file != NULL) {
1326 fputs(CWD, save_cwd_file);
1327 fclose(save_cwd_file);
1329 if (save_marks_file != NULL) {
1330 for (i = 0; i < rover.marks.bulk; i++) {
1331 entry = rover.marks.entries[i];
1332 if (entry)
1333 fprintf(save_marks_file, "%s%s\n", rover.marks.dirpath, entry);
1335 fclose(save_marks_file);
1337 free_marks(&rover.marks);
1338 return 0;