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 static int
320 open_with_env(const char *env, char *path)
322 char *program = getenv(env);
323 if (program) {
324 #ifdef RV_SHELL
325 strncpy(BUF1, program, BUFLEN - 1);
326 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
327 strncat(BUF1, path, BUFLEN - strlen(program) - strlen(path) - 2);
328 spawn((char *[]) {RV_SHELL, "-c", BUF1, NULL});
329 #else
330 spawn((char *[]) {program, path, NULL});
331 #endif
332 return 1;
334 return 0;
337 /* Curses setup. */
338 static void
339 init_term()
341 setlocale(LC_ALL, "");
342 initscr();
343 cbreak(); /* Get one character at a time. */
344 timeout(100); /* For getch(). */
345 noecho();
346 nonl(); /* No NL->CR/NL on output. */
347 intrflush(stdscr, FALSE);
348 keypad(stdscr, TRUE);
349 curs_set(FALSE); /* Hide blinking cursor. */
350 if (has_colors()) {
351 short bg;
352 start_color();
353 #ifdef NCURSES_EXT_FUNCS
354 use_default_colors();
355 bg = -1;
356 #else
357 bg = COLOR_BLACK;
358 #endif
359 init_pair(RED, COLOR_RED, bg);
360 init_pair(GREEN, COLOR_GREEN, bg);
361 init_pair(YELLOW, COLOR_YELLOW, bg);
362 init_pair(BLUE, COLOR_BLUE, bg);
363 init_pair(CYAN, COLOR_CYAN, bg);
364 init_pair(MAGENTA, COLOR_MAGENTA, bg);
365 init_pair(WHITE, COLOR_WHITE, bg);
366 init_pair(BLACK, COLOR_BLACK, bg);
368 atexit((void (*)(void)) endwin);
369 enable_handlers();
372 /* Update the listing view. */
373 static void
374 update_view()
376 int i, j;
377 int numsize;
378 int ishidden;
379 int marking;
381 mvhline(0, 0, ' ', COLS);
382 attr_on(A_BOLD, NULL);
383 color_set(RVC_TABNUM, NULL);
384 mvaddch(0, COLS - 2, rover.tab + '0');
385 attr_off(A_BOLD, NULL);
386 if (rover.marks.nentries) {
387 numsize = snprintf(BUF1, BUFLEN, "%d", rover.marks.nentries);
388 color_set(RVC_MARKS, NULL);
389 mvaddstr(0, COLS - 3 - numsize, BUF1);
390 } else
391 numsize = -1;
392 color_set(RVC_CWD, NULL);
393 mbstowcs(WBUF, CWD, PATH_MAX);
394 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
395 wcolor_set(rover.window, RVC_BORDER, NULL);
396 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
397 ESEL = MAX(MIN(ESEL, rover.nfiles - 1), 0);
398 /* Selection might not be visible, due to cursor wrapping or window
399 shrinking. In that case, the scroll must be moved to make it visible. */
400 if (rover.nfiles > HEIGHT) {
401 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
402 SCROLL = MIN(MAX(SCROLL, 0), rover.nfiles - HEIGHT);
403 } else
404 SCROLL = 0;
405 marking = !strcmp(CWD, rover.marks.dirpath);
406 for (i = 0, j = SCROLL; i < HEIGHT && j < rover.nfiles; i++, j++) {
407 ishidden = ENAME(j)[0] == '.';
408 if (j == ESEL)
409 wattr_on(rover.window, A_REVERSE, NULL);
410 if (ISLINK(j))
411 wcolor_set(rover.window, RVC_LINK, NULL);
412 else if (ishidden)
413 wcolor_set(rover.window, RVC_HIDDEN, NULL);
414 else if (S_ISREG(EMODE(j))) {
415 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
416 wcolor_set(rover.window, RVC_EXEC, NULL);
417 else
418 wcolor_set(rover.window, RVC_REG, NULL);
419 } else if (S_ISDIR(EMODE(j)))
420 wcolor_set(rover.window, RVC_DIR, NULL);
421 else if (S_ISCHR(EMODE(j)))
422 wcolor_set(rover.window, RVC_CHR, NULL);
423 else if (S_ISBLK(EMODE(j)))
424 wcolor_set(rover.window, RVC_BLK, NULL);
425 else if (S_ISFIFO(EMODE(j)))
426 wcolor_set(rover.window, RVC_FIFO, NULL);
427 else if (S_ISSOCK(EMODE(j)))
428 wcolor_set(rover.window, RVC_SOCK, NULL);
429 if (S_ISDIR(EMODE(j))) {
430 mbstowcs(WBUF, ENAME(j), PATH_MAX);
431 if (ISLINK(j))
432 wcscat(WBUF, L"/");
433 } else {
434 char *suffix, *suffixes = "BKMGTPEZY";
435 off_t human_size = ESIZE(j) * 10;
436 int length = mbstowcs(NULL, ENAME(j), 0);
437 for (suffix = suffixes; human_size >= 10240; suffix++)
438 human_size = (human_size + 512) / 1024;
439 if (*suffix == 'B')
440 swprintf(WBUF, PATH_MAX, L"%s%*d %c", ENAME(j),
441 (int) (COLS - length - 6),
442 (int) human_size / 10, *suffix);
443 else
444 swprintf(WBUF, PATH_MAX, L"%s%*d.%d %c", ENAME(j),
445 (int) (COLS - length - 8),
446 (int) human_size / 10, (int) human_size % 10, *suffix);
448 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
449 mvwaddnwstr(rover.window, i + 1, 2, WBUF, COLS - 4);
450 if (marking && MARKED(j)) {
451 wcolor_set(rover.window, RVC_MARKS, NULL);
452 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
453 } else
454 mvwaddch(rover.window, i + 1, 1, ' ');
455 if (j == ESEL)
456 wattr_off(rover.window, A_REVERSE, NULL);
458 for (; i < HEIGHT; i++)
459 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
460 if (rover.nfiles > HEIGHT) {
461 int center, height;
462 center = (SCROLL + HEIGHT / 2) * HEIGHT / rover.nfiles;
463 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
464 if (!height) height = 1;
465 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
466 mvwvline(rover.window, center-height/2+1, COLS-1, RVS_SCROLLBAR, height);
468 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
469 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
470 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
471 if (!rover.nfiles)
472 strcpy(BUF2, "0/0");
473 else
474 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, rover.nfiles);
475 snprintf(BUF1+3, BUFLEN-3, "%12s", BUF2);
476 color_set(RVC_STATUS, NULL);
477 mvaddstr(LINES - 1, STATUSPOS, BUF1);
478 wrefresh(rover.window);
481 /* Show a message on the status bar. */
482 static void
483 message(Color color, char *fmt, ...)
485 int len, pos;
486 va_list args;
488 va_start(args, fmt);
489 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
490 va_end(args);
491 len = strlen(BUF1);
492 pos = (STATUSPOS - len) / 2;
493 attr_on(A_BOLD, NULL);
494 color_set(color, NULL);
495 mvaddstr(LINES - 1, pos, BUF1);
496 color_set(DEFAULT, NULL);
497 attr_off(A_BOLD, NULL);
500 /* Clear message area, leaving only status info. */
501 static void
502 clear_message()
504 mvhline(LINES - 1, 0, ' ', STATUSPOS);
507 /* Comparison used to sort listing entries. */
508 static int
509 rowcmp(const void *a, const void *b)
511 int isdir1, isdir2, cmpdir;
512 const Row *r1 = a;
513 const Row *r2 = b;
514 isdir1 = S_ISDIR(r1->mode);
515 isdir2 = S_ISDIR(r2->mode);
516 cmpdir = isdir2 - isdir1;
517 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
520 /* Get all entries in current working directory. */
521 static int
522 ls(Row **rowsp, uint8_t flags)
524 DIR *dp;
525 struct dirent *ep;
526 struct stat statbuf;
527 Row *rows;
528 int i, n;
530 if(!(dp = opendir("."))) return -1;
531 n = -2; /* We don't want the entries "." and "..". */
532 while (readdir(dp)) n++;
533 rewinddir(dp);
534 rows = malloc(n * sizeof *rows);
535 i = 0;
536 while ((ep = readdir(dp))) {
537 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
538 continue;
539 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
540 continue;
541 lstat(ep->d_name, &statbuf);
542 rows[i].islink = S_ISLNK(statbuf.st_mode);
543 stat(ep->d_name, &statbuf);
544 if (S_ISDIR(statbuf.st_mode)) {
545 if (flags & SHOW_DIRS) {
546 rows[i].name = malloc(strlen(ep->d_name) + 2);
547 strcpy(rows[i].name, ep->d_name);
548 if (!rows[i].islink)
549 strcat(rows[i].name, "/");
550 rows[i].mode = statbuf.st_mode;
551 i++;
553 } else if (flags & SHOW_FILES) {
554 rows[i].name = malloc(strlen(ep->d_name) + 1);
555 strcpy(rows[i].name, ep->d_name);
556 rows[i].size = statbuf.st_size;
557 rows[i].mode = statbuf.st_mode;
558 i++;
561 n = i; /* Ignore unused space in array caused by filters. */
562 qsort(rows, n, sizeof (*rows), rowcmp);
563 closedir(dp);
564 *rowsp = rows;
565 return n;
568 static void
569 free_rows(Row **rowsp, int nfiles)
571 int i;
573 for (i = 0; i < nfiles; i++)
574 free((*rowsp)[i].name);
575 free(*rowsp);
576 *rowsp = NULL;
579 /* Change working directory to the path in CWD. */
580 static void
581 cd(int reset)
583 int i, j;
585 message(CYAN, "Loading...");
586 refresh();
587 if (reset) ESEL = SCROLL = 0;
588 chdir(CWD);
589 if (rover.nfiles)
590 free_rows(&rover.rows, rover.nfiles);
591 rover.nfiles = ls(&rover.rows, FLAGS);
592 if (!strcmp(CWD, rover.marks.dirpath)) {
593 for (i = 0; i < rover.nfiles; i++) {
594 for (j = 0; j < rover.marks.bulk; j++)
595 if (
596 rover.marks.entries[j] &&
597 !strcmp(rover.marks.entries[j], ENAME(i))
599 break;
600 MARKED(i) = j < rover.marks.bulk;
602 } else
603 for (i = 0; i < rover.nfiles; i++)
604 MARKED(i) = 0;
605 clear_message();
606 update_view();
609 /* Select a target entry, if it is present. */
610 static void
611 try_to_sel(const char *target)
613 ESEL = 0;
614 if (!ISDIR(target))
615 while ((ESEL+1) < rover.nfiles && S_ISDIR(EMODE(ESEL)))
616 ESEL++;
617 while ((ESEL+1) < rover.nfiles && strcoll(ENAME(ESEL), target) < 0)
618 ESEL++;
621 /* Reload CWD, but try to keep selection. */
622 static void
623 reload()
625 if (rover.nfiles) {
626 strcpy(INPUT, ENAME(ESEL));
627 cd(0);
628 try_to_sel(INPUT);
629 update_view();
630 } else
631 cd(1);
634 static off_t
635 count_dir(const char *path)
637 DIR *dp;
638 struct dirent *ep;
639 struct stat statbuf;
640 char subpath[PATH_MAX];
641 off_t total;
643 if(!(dp = opendir(path))) return 0;
644 total = 0;
645 while ((ep = readdir(dp))) {
646 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
647 continue;
648 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
649 lstat(subpath, &statbuf);
650 if (S_ISDIR(statbuf.st_mode)) {
651 strcat(subpath, "/");
652 total += count_dir(subpath);
653 } else
654 total += statbuf.st_size;
656 closedir(dp);
657 return total;
660 static off_t
661 count_marked()
663 int i;
664 char *entry;
665 off_t total;
666 struct stat statbuf;
668 total = 0;
669 chdir(rover.marks.dirpath);
670 for (i = 0; i < rover.marks.bulk; i++) {
671 entry = rover.marks.entries[i];
672 if (entry) {
673 if (ISDIR(entry)) {
674 total += count_dir(entry);
675 } else {
676 lstat(entry, &statbuf);
677 total += statbuf.st_size;
681 chdir(CWD);
682 return total;
685 /* Recursively process a source directory using CWD as destination root.
686 For each node (i.e. directory), do the following:
687 1. call pre(destination);
688 2. call proc() on every child leaf (i.e. files);
689 3. recurse into every child node;
690 4. call pos(source).
691 E.g. to move directory /src/ (and all its contents) inside /dst/:
692 strcpy(CWD, "/dst/");
693 process_dir(adddir, movfile, deldir, "/src/"); */
694 static int
695 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
697 int ret;
698 DIR *dp;
699 struct dirent *ep;
700 struct stat statbuf;
701 char subpath[PATH_MAX];
703 ret = 0;
704 if (pre) {
705 char dstpath[PATH_MAX];
706 strcpy(dstpath, CWD);
707 strcat(dstpath, path + strlen(rover.marks.dirpath));
708 ret |= pre(dstpath);
710 if(!(dp = opendir(path))) return -1;
711 while ((ep = readdir(dp))) {
712 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
713 continue;
714 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
715 lstat(subpath, &statbuf);
716 if (S_ISDIR(statbuf.st_mode)) {
717 strcat(subpath, "/");
718 ret |= process_dir(pre, proc, pos, subpath);
719 } else
720 ret |= proc(subpath);
722 closedir(dp);
723 if (pos) ret |= pos(path);
724 return ret;
727 /* Process all marked entries using CWD as destination root.
728 All marked entries that are directories will be recursively processed.
729 See process_dir() for details on the parameters. */
730 static void
731 process_marked(PROCESS pre, PROCESS proc, PROCESS pos,
732 const char *msg_doing, const char *msg_done)
734 int i, ret;
735 char *entry;
736 char path[PATH_MAX];
738 clear_message();
739 message(CYAN, "%s...", msg_doing);
740 refresh();
741 rover.prog = (Prog) {0, count_marked(), msg_doing};
742 for (i = 0; i < rover.marks.bulk; i++) {
743 entry = rover.marks.entries[i];
744 if (entry) {
745 ret = 0;
746 snprintf(path, PATH_MAX, "%s%s", rover.marks.dirpath, entry);
747 if (ISDIR(entry)) {
748 if (!strncmp(path, CWD, strlen(path)))
749 ret = -1;
750 else
751 ret = process_dir(pre, proc, pos, path);
752 } else
753 ret = proc(path);
754 if (!ret) {
755 del_mark(&rover.marks, entry);
756 reload();
760 rover.prog.total = 0;
761 reload();
762 if (!rover.marks.nentries)
763 message(GREEN, "%s all marked entries.", msg_done);
764 else
765 message(RED, "Some errors occured while %s.", msg_doing);
766 RV_ALERT();
769 static void
770 update_progress(off_t delta)
772 int percent;
774 if (!rover.prog.total) return;
775 rover.prog.partial += delta;
776 percent = (int) (rover.prog.partial * 100 / rover.prog.total);
777 message(CYAN, "%s...%d%%", rover.prog.msg, percent);
778 refresh();
781 /* Wrappers for file operations. */
782 static int delfile(const char *path) {
783 int ret;
784 struct stat st;
786 ret = lstat(path, &st);
787 if (ret < 0) return ret;
788 update_progress(st.st_size);
789 return unlink(path);
791 static PROCESS deldir = rmdir;
792 static int addfile(const char *path) {
793 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
794 int ret;
796 ret = creat(path, 0644);
797 if (ret < 0) return ret;
798 return close(ret);
800 static int cpyfile(const char *srcpath) {
801 int src, dst, ret;
802 size_t size;
803 struct stat st;
804 char buf[BUFSIZ];
805 char dstpath[PATH_MAX];
807 strcpy(dstpath, CWD);
808 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
809 ret = lstat(srcpath, &st);
810 if (ret < 0) return ret;
811 if (S_ISLNK(st.st_mode)) {
812 ret = readlink(srcpath, BUF1, BUFLEN);
813 if (ret < 0) return ret;
814 BUF1[ret] = '\0';
815 ret = symlink(BUF1, dstpath);
816 } else {
817 ret = src = open(srcpath, O_RDONLY);
818 if (ret < 0) return ret;
819 ret = dst = creat(dstpath, st.st_mode);
820 if (ret < 0) return ret;
821 while ((size = read(src, buf, BUFSIZ)) > 0) {
822 write(dst, buf, size);
823 update_progress(size);
824 sync_signals();
826 close(src);
827 close(dst);
828 ret = 0;
830 return ret;
832 static int adddir(const char *path) {
833 int ret;
834 struct stat st;
836 ret = stat(CWD, &st);
837 if (ret < 0) return ret;
838 return mkdir(path, st.st_mode);
840 static int movfile(const char *srcpath) {
841 int ret;
842 struct stat st;
843 char dstpath[PATH_MAX];
845 strcpy(dstpath, CWD);
846 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
847 ret = rename(srcpath, dstpath);
848 if (ret == 0) {
849 ret = lstat(dstpath, &st);
850 if (ret < 0) return ret;
851 update_progress(st.st_size);
852 } else if (errno == EXDEV) {
853 ret = cpyfile(srcpath);
854 if (ret < 0) return ret;
855 ret = unlink(srcpath);
857 return ret;
860 static void
861 start_line_edit(const char *init_input)
863 curs_set(TRUE);
864 strncpy(INPUT, init_input, BUFLEN);
865 rover.edit.left = mbstowcs(rover.edit.buffer, init_input, BUFLEN);
866 rover.edit.right = BUFLEN - 1;
867 rover.edit.buffer[BUFLEN] = L'\0';
868 rover.edit_scroll = 0;
871 /* Read input and change editing state accordingly. */
872 static EditStat
873 get_line_edit()
875 wchar_t eraser, killer, wch;
876 int ret, length;
878 ret = rover_get_wch((wint_t *) &wch);
879 erasewchar(&eraser);
880 killwchar(&killer);
881 if (ret == KEY_CODE_YES) {
882 if (wch == KEY_ENTER) {
883 curs_set(FALSE);
884 return CONFIRM;
885 } else if (wch == KEY_LEFT) {
886 if (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
887 } else if (wch == KEY_RIGHT) {
888 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
889 } else if (wch == KEY_UP) {
890 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
891 } else if (wch == KEY_DOWN) {
892 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
893 } else if (wch == KEY_BACKSPACE) {
894 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
895 } else if (wch == KEY_DC) {
896 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
898 } else {
899 if (wch == L'\r' || wch == L'\n') {
900 curs_set(FALSE);
901 return CONFIRM;
902 } else if (wch == L'\t') {
903 curs_set(FALSE);
904 return CANCEL;
905 } else if (wch == eraser) {
906 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
907 } else if (wch == killer) {
908 EDIT_CLEAR(rover.edit);
909 clear_message();
910 } else if (iswprint(wch)) {
911 if (!EDIT_FULL(rover.edit)) EDIT_INSERT(rover.edit, wch);
914 /* Encode edit contents in INPUT. */
915 rover.edit.buffer[rover.edit.left] = L'\0';
916 length = wcstombs(INPUT, rover.edit.buffer, BUFLEN);
917 wcstombs(&INPUT[length], &rover.edit.buffer[rover.edit.right+1],
918 BUFLEN-length);
919 return CONTINUE;
922 /* Update line input on the screen. */
923 static void
924 update_input(const char *prompt, Color color)
926 int plen, ilen, maxlen;
928 plen = strlen(prompt);
929 ilen = mbstowcs(NULL, INPUT, 0);
930 maxlen = STATUSPOS - plen - 2;
931 if (ilen - rover.edit_scroll < maxlen)
932 rover.edit_scroll = MAX(ilen - maxlen, 0);
933 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
934 rover.edit_scroll = rover.edit.left - maxlen;
935 else if (rover.edit.left < rover.edit_scroll)
936 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
937 color_set(RVC_PROMPT, NULL);
938 mvaddstr(LINES - 1, 0, prompt);
939 color_set(color, NULL);
940 mbstowcs(WBUF, INPUT, COLS);
941 mvaddnwstr(LINES - 1, plen, &WBUF[rover.edit_scroll], maxlen);
942 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
943 color_set(DEFAULT, NULL);
944 if (rover.edit_scroll)
945 mvaddch(LINES - 1, plen - 1, '<');
946 if (ilen > rover.edit_scroll + maxlen)
947 mvaddch(LINES - 1, plen + maxlen, '>');
948 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
951 int
952 main(int argc, char *argv[])
954 int i, ch;
955 char *program;
956 char *entry;
957 const char *key;
958 DIR *d;
959 EditStat edit_stat;
960 FILE *save_cwd_file = NULL;
961 FILE *save_marks_file = NULL;
963 if (argc >= 2) {
964 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
965 printf("rover %s\n", RV_VERSION);
966 return 0;
967 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
968 printf(
969 "Usage: rover [OPTIONS] [DIR [DIR [...]]]\n"
970 " Browse current directory or the ones specified.\n\n"
971 " or: rover -h|--help\n"
972 " Print this help message and exit.\n\n"
973 " or: rover -v|--version\n"
974 " Print program version and exit.\n\n"
975 "See rover(1) for more information.\n"
976 "Rover homepage: <https://github.com/lecram/rover>.\n"
977 );
978 return 0;
979 } else if (!strcmp(argv[1], "-d") || !strcmp(argv[1], "--save-cwd")) {
980 if (argc > 2) {
981 save_cwd_file = fopen(argv[2], "w");
982 argc -= 2; argv += 2;
983 } else {
984 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
985 return 1;
987 } else if (!strcmp(argv[1], "-m") || !strcmp(argv[1], "--save-marks")) {
988 if (argc > 2) {
989 save_marks_file = fopen(argv[2], "a");
990 argc -= 2; argv += 2;
991 } else {
992 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
993 return 1;
997 init_term();
998 rover.nfiles = 0;
999 for (i = 0; i < 10; i++) {
1000 rover.tabs[i].esel = rover.tabs[i].scroll = 0;
1001 rover.tabs[i].flags = SHOW_FILES | SHOW_DIRS;
1003 strcpy(rover.tabs[0].cwd, getenv("HOME"));
1004 for (i = 1; i < argc && i < 10; i++) {
1005 if ((d = opendir(argv[i]))) {
1006 realpath(argv[i], rover.tabs[i].cwd);
1007 closedir(d);
1008 } else
1009 strcpy(rover.tabs[i].cwd, rover.tabs[0].cwd);
1011 getcwd(rover.tabs[i].cwd, PATH_MAX);
1012 for (i++; i < 10; i++)
1013 strcpy(rover.tabs[i].cwd, rover.tabs[i-1].cwd);
1014 for (i = 0; i < 10; i++)
1015 if (rover.tabs[i].cwd[strlen(rover.tabs[i].cwd) - 1] != '/')
1016 strcat(rover.tabs[i].cwd, "/");
1017 rover.tab = 1;
1018 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1019 init_marks(&rover.marks);
1020 cd(1);
1021 while (1) {
1022 ch = rover_getch();
1023 key = keyname(ch);
1024 clear_message();
1025 if (!strcmp(key, RVK_QUIT)) break;
1026 else if (ch >= '0' && ch <= '9') {
1027 rover.tab = ch - '0';
1028 cd(0);
1029 } else if (!strcmp(key, RVK_HELP)) {
1030 spawn((char *[]) {"man", "rover", NULL});
1031 } else if (!strcmp(key, RVK_DOWN)) {
1032 if (!rover.nfiles) continue;
1033 ESEL = MIN(ESEL + 1, rover.nfiles - 1);
1034 update_view();
1035 } else if (!strcmp(key, RVK_UP)) {
1036 if (!rover.nfiles) continue;
1037 ESEL = MAX(ESEL - 1, 0);
1038 update_view();
1039 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
1040 if (!rover.nfiles) continue;
1041 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
1042 if (rover.nfiles > HEIGHT)
1043 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
1044 update_view();
1045 } else if (!strcmp(key, RVK_JUMP_UP)) {
1046 if (!rover.nfiles) continue;
1047 ESEL = MAX(ESEL - RV_JUMP, 0);
1048 SCROLL = MAX(SCROLL - RV_JUMP, 0);
1049 update_view();
1050 } else if (!strcmp(key, RVK_JUMP_TOP)) {
1051 if (!rover.nfiles) continue;
1052 ESEL = 0;
1053 update_view();
1054 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
1055 if (!rover.nfiles) continue;
1056 ESEL = rover.nfiles - 1;
1057 update_view();
1058 } else if (!strcmp(key, RVK_CD_DOWN)) {
1059 if (!rover.nfiles || !S_ISDIR(EMODE(ESEL))) continue;
1060 if (chdir(ENAME(ESEL)) == -1) {
1061 message(RED, "Cannot access \"%s\".", ENAME(ESEL));
1062 continue;
1064 strcat(CWD, ENAME(ESEL));
1065 cd(1);
1066 } else if (!strcmp(key, RVK_CD_UP)) {
1067 char *dirname, first;
1068 if (!strcmp(CWD, "/")) continue;
1069 CWD[strlen(CWD) - 1] = '\0';
1070 dirname = strrchr(CWD, '/') + 1;
1071 first = dirname[0];
1072 dirname[0] = '\0';
1073 cd(1);
1074 dirname[0] = first;
1075 dirname[strlen(dirname)] = '/';
1076 try_to_sel(dirname);
1077 dirname[0] = '\0';
1078 if (rover.nfiles > HEIGHT)
1079 SCROLL = ESEL - HEIGHT / 2;
1080 update_view();
1081 } else if (!strcmp(key, RVK_HOME)) {
1082 strcpy(CWD, getenv("HOME"));
1083 if (CWD[strlen(CWD) - 1] != '/')
1084 strcat(CWD, "/");
1085 cd(1);
1086 } else if (!strcmp(key, RVK_REFRESH)) {
1087 reload();
1088 } else if (!strcmp(key, RVK_SHELL)) {
1089 program = getenv("SHELL");
1090 if (program) {
1091 #ifdef RV_SHELL
1092 spawn((char *[]) {RV_SHELL, "-c", program, NULL});
1093 #else
1094 spawn((char *[]) {program, NULL});
1095 #endif
1096 reload();
1098 } else if (!strcmp(key, RVK_VIEW)) {
1099 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1100 if (open_with_env("PAGER", ENAME(ESEL)))
1101 cd(0);
1102 } else if (!strcmp(key, RVK_EDIT)) {
1103 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1104 if (open_with_env("EDITOR", ENAME(ESEL)))
1105 cd(0);
1106 } else if (!strcmp(key, RVK_OPEN)) {
1107 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1108 if (open_with_env("ROVER_OPEN", ENAME(ESEL)))
1109 cd(0);
1110 } else if (!strcmp(key, RVK_SEARCH)) {
1111 int oldsel, oldscroll, length;
1112 if (!rover.nfiles) continue;
1113 oldsel = ESEL;
1114 oldscroll = SCROLL;
1115 start_line_edit("");
1116 update_input(RVP_SEARCH, RED);
1117 while ((edit_stat = get_line_edit()) == CONTINUE) {
1118 int sel;
1119 Color color = RED;
1120 length = strlen(INPUT);
1121 if (length) {
1122 for (sel = 0; sel < rover.nfiles; sel++)
1123 if (!strncmp(ENAME(sel), INPUT, length))
1124 break;
1125 if (sel < rover.nfiles) {
1126 color = GREEN;
1127 ESEL = sel;
1128 if (rover.nfiles > HEIGHT) {
1129 if (sel < 3)
1130 SCROLL = 0;
1131 else if (sel - 3 > rover.nfiles - HEIGHT)
1132 SCROLL = rover.nfiles - HEIGHT;
1133 else
1134 SCROLL = sel - 3;
1137 } else {
1138 ESEL = oldsel;
1139 SCROLL = oldscroll;
1141 update_view();
1142 update_input(RVP_SEARCH, color);
1144 if (edit_stat == CANCEL) {
1145 ESEL = oldsel;
1146 SCROLL = oldscroll;
1148 clear_message();
1149 update_view();
1150 } else if (!strcmp(key, RVK_TG_FILES)) {
1151 FLAGS ^= SHOW_FILES;
1152 reload();
1153 } else if (!strcmp(key, RVK_TG_DIRS)) {
1154 FLAGS ^= SHOW_DIRS;
1155 reload();
1156 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
1157 FLAGS ^= SHOW_HIDDEN;
1158 reload();
1159 } else if (!strcmp(key, RVK_NEW_FILE)) {
1160 int ok = 0;
1161 start_line_edit("");
1162 update_input(RVP_NEW_FILE, RED);
1163 while ((edit_stat = get_line_edit()) == CONTINUE) {
1164 int length = strlen(INPUT);
1165 ok = length;
1166 for (i = 0; i < rover.nfiles; i++) {
1167 if (
1168 !strncmp(ENAME(i), INPUT, length) &&
1169 (!strcmp(ENAME(i) + length, "") ||
1170 !strcmp(ENAME(i) + length, "/"))
1171 ) {
1172 ok = 0;
1173 break;
1176 update_input(RVP_NEW_FILE, ok ? GREEN : RED);
1178 clear_message();
1179 if (edit_stat == CONFIRM) {
1180 if (ok) {
1181 if (addfile(INPUT) == 0) {
1182 cd(1);
1183 try_to_sel(INPUT);
1184 update_view();
1185 } else
1186 message(RED, "Could not create \"%s\".", INPUT);
1187 } else
1188 message(RED, "\"%s\" already exists.", INPUT);
1190 } else if (!strcmp(key, RVK_NEW_DIR)) {
1191 int ok = 0;
1192 start_line_edit("");
1193 update_input(RVP_NEW_DIR, RED);
1194 while ((edit_stat = get_line_edit()) == CONTINUE) {
1195 int length = strlen(INPUT);
1196 ok = length;
1197 for (i = 0; i < rover.nfiles; i++) {
1198 if (
1199 !strncmp(ENAME(i), INPUT, length) &&
1200 (!strcmp(ENAME(i) + length, "") ||
1201 !strcmp(ENAME(i) + length, "/"))
1202 ) {
1203 ok = 0;
1204 break;
1207 update_input(RVP_NEW_DIR, ok ? GREEN : RED);
1209 clear_message();
1210 if (edit_stat == CONFIRM) {
1211 if (ok) {
1212 if (adddir(INPUT) == 0) {
1213 cd(1);
1214 strcat(INPUT, "/");
1215 try_to_sel(INPUT);
1216 update_view();
1217 } else
1218 message(RED, "Could not create \"%s/\".", INPUT);
1219 } else
1220 message(RED, "\"%s\" already exists.", INPUT);
1222 } else if (!strcmp(key, RVK_RENAME)) {
1223 int ok = 0;
1224 char *last;
1225 int isdir;
1226 strcpy(INPUT, ENAME(ESEL));
1227 last = INPUT + strlen(INPUT) - 1;
1228 if ((isdir = *last == '/'))
1229 *last = '\0';
1230 start_line_edit(INPUT);
1231 update_input(RVP_RENAME, RED);
1232 while ((edit_stat = get_line_edit()) == CONTINUE) {
1233 int length = strlen(INPUT);
1234 ok = length;
1235 for (i = 0; i < rover.nfiles; i++)
1236 if (
1237 !strncmp(ENAME(i), INPUT, length) &&
1238 (!strcmp(ENAME(i) + length, "") ||
1239 !strcmp(ENAME(i) + length, "/"))
1240 ) {
1241 ok = 0;
1242 break;
1244 update_input(RVP_RENAME, ok ? GREEN : RED);
1246 clear_message();
1247 if (edit_stat == CONFIRM) {
1248 if (isdir)
1249 strcat(INPUT, "/");
1250 if (ok) {
1251 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1252 del_mark(&rover.marks, ENAME(ESEL));
1253 add_mark(&rover.marks, CWD, INPUT);
1255 cd(1);
1256 try_to_sel(INPUT);
1257 update_view();
1258 } else
1259 message(RED, "\"%s\" already exists.", INPUT);
1261 } else if (!strcmp(key, RVK_DELETE)) {
1262 if (rover.nfiles) {
1263 message(YELLOW, "Delete \"%s\"? (Y/n)", ENAME(ESEL));
1264 if (rover_getch() == 'Y') {
1265 const char *name = ENAME(ESEL);
1266 int ret = ISDIR(ENAME(ESEL)) ? deldir(name) : delfile(name);
1267 reload();
1268 if (ret)
1269 message(RED, "Could not delete \"%s\".", ENAME(ESEL));
1270 } else
1271 clear_message();
1272 } else
1273 message(RED, "No entry selected for deletion.");
1274 } else if (!strcmp(key, RVK_TG_MARK)) {
1275 if (MARKED(ESEL))
1276 del_mark(&rover.marks, ENAME(ESEL));
1277 else
1278 add_mark(&rover.marks, CWD, ENAME(ESEL));
1279 MARKED(ESEL) = !MARKED(ESEL);
1280 ESEL = (ESEL + 1) % rover.nfiles;
1281 update_view();
1282 } else if (!strcmp(key, RVK_INVMARK)) {
1283 for (i = 0; i < rover.nfiles; i++) {
1284 if (MARKED(i))
1285 del_mark(&rover.marks, ENAME(i));
1286 else
1287 add_mark(&rover.marks, CWD, ENAME(i));
1288 MARKED(i) = !MARKED(i);
1290 update_view();
1291 } else if (!strcmp(key, RVK_MARKALL)) {
1292 for (i = 0; i < rover.nfiles; i++)
1293 if (!MARKED(i)) {
1294 add_mark(&rover.marks, CWD, ENAME(i));
1295 MARKED(i) = 1;
1297 update_view();
1298 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1299 if (rover.marks.nentries) {
1300 message(YELLOW, "Delete all marked entries? (Y/n)");
1301 if (rover_getch() == 'Y')
1302 process_marked(NULL, delfile, deldir, "Deleting", "Deleted");
1303 else
1304 clear_message();
1305 } else
1306 message(RED, "No entries marked for deletion.");
1307 } else if (!strcmp(key, RVK_MARK_COPY)) {
1308 if (rover.marks.nentries)
1309 process_marked(adddir, cpyfile, NULL, "Copying", "Copied");
1310 else
1311 message(RED, "No entries marked for copying.");
1312 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1313 if (rover.marks.nentries)
1314 process_marked(adddir, movfile, deldir, "Moving", "Moved");
1315 else
1316 message(RED, "No entries marked for moving.");
1319 if (rover.nfiles)
1320 free_rows(&rover.rows, rover.nfiles);
1321 delwin(rover.window);
1322 if (save_cwd_file != NULL) {
1323 fputs(CWD, save_cwd_file);
1324 fclose(save_cwd_file);
1326 if (save_marks_file != NULL) {
1327 for (i = 0; i < rover.marks.bulk; i++) {
1328 entry = rover.marks.entries[i];
1329 if (entry)
1330 fprintf(save_marks_file, "%s%s\n", rover.marks.dirpath, entry);
1332 fclose(save_marks_file);
1334 free_marks(&rover.marks);
1335 return 0;