Support color customization of other kinds of files.
[rover.git] / rover.c
blobe8371c245f1f182b37fbd43ec523e34fc966843a
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 wcolor_set(rover.window, RVC_REG, NULL);
396 else if (S_ISDIR(EMODE(j)))
397 wcolor_set(rover.window, RVC_DIR, NULL);
398 else if (S_ISCHR(EMODE(j)))
399 wcolor_set(rover.window, RVC_CHR, NULL);
400 else if (S_ISBLK(EMODE(j)))
401 wcolor_set(rover.window, RVC_BLK, NULL);
402 else if (S_ISFIFO(EMODE(j)))
403 wcolor_set(rover.window, RVC_FIFO, NULL);
404 else if (S_ISSOCK(EMODE(j)))
405 wcolor_set(rover.window, RVC_SOCK, NULL);
406 if (!S_ISDIR(EMODE(j))) {
407 char *suffix, *suffixes = "BKMGTPEZY";
408 off_t human_size = ESIZE(j) * 10;
409 int length = mbstowcs(NULL, ENAME(j), 0);
410 for (suffix = suffixes; human_size >= 10240; suffix++)
411 human_size = (human_size + 512) / 1024;
412 if (*suffix == 'B')
413 swprintf(WBUF, PATH_MAX, L"%s%*d %c", ENAME(j),
414 (int) (COLS - length - 6),
415 (int) human_size / 10, *suffix);
416 else
417 swprintf(WBUF, PATH_MAX, L"%s%*d.%d %c", ENAME(j),
418 (int) (COLS - length - 8),
419 (int) human_size / 10, (int) human_size % 10, *suffix);
420 } else
421 mbstowcs(WBUF, ENAME(j), PATH_MAX);
422 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
423 mvwaddnwstr(rover.window, i + 1, 2, WBUF, COLS - 4);
424 if (marking && MARKED(j)) {
425 wcolor_set(rover.window, RVC_MARKS, NULL);
426 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
427 } else
428 mvwaddch(rover.window, i + 1, 1, ' ');
429 if (j == ESEL)
430 wattr_off(rover.window, A_REVERSE, NULL);
432 for (; i < HEIGHT; i++)
433 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
434 if (rover.nfiles > HEIGHT) {
435 int center, height;
436 center = (SCROLL + HEIGHT / 2) * HEIGHT / rover.nfiles;
437 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
438 if (!height) height = 1;
439 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
440 mvwvline(rover.window, center-height/2+1, COLS-1, RVS_SCROLLBAR, height);
442 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
443 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
444 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
445 if (!rover.nfiles)
446 strcpy(BUF2, "0/0");
447 else
448 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, rover.nfiles);
449 snprintf(BUF1+3, BUFLEN-3, "%12s", BUF2);
450 color_set(RVC_STATUS, NULL);
451 mvaddstr(LINES - 1, STATUSPOS, BUF1);
452 wrefresh(rover.window);
455 /* Show a message on the status bar. */
456 static void
457 message(Color color, char *fmt, ...)
459 int len, pos;
460 va_list args;
462 va_start(args, fmt);
463 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
464 va_end(args);
465 len = strlen(BUF1);
466 pos = (STATUSPOS - len) / 2;
467 attr_on(A_BOLD, NULL);
468 color_set(color, NULL);
469 mvaddstr(LINES - 1, pos, BUF1);
470 color_set(DEFAULT, NULL);
471 attr_off(A_BOLD, NULL);
474 /* Clear message area, leaving only status info. */
475 static void
476 clear_message()
478 mvhline(LINES - 1, 0, ' ', STATUSPOS);
481 /* Comparison used to sort listing entries. */
482 static int
483 rowcmp(const void *a, const void *b)
485 int isdir1, isdir2, cmpdir;
486 const Row *r1 = a;
487 const Row *r2 = b;
488 isdir1 = S_ISDIR(r1->mode);
489 isdir2 = S_ISDIR(r2->mode);
490 cmpdir = isdir2 - isdir1;
491 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
494 /* Get all entries in current working directory. */
495 static int
496 ls(Row **rowsp, uint8_t flags)
498 DIR *dp;
499 struct dirent *ep;
500 struct stat statbuf;
501 Row *rows;
502 int i, n;
504 if(!(dp = opendir("."))) return -1;
505 n = -2; /* We don't want the entries "." and "..". */
506 while (readdir(dp)) n++;
507 rewinddir(dp);
508 rows = malloc(n * sizeof *rows);
509 i = 0;
510 while ((ep = readdir(dp))) {
511 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
512 continue;
513 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
514 continue;
515 lstat(ep->d_name, &statbuf);
516 rows[i].islink = S_ISLNK(statbuf.st_mode);
517 stat(ep->d_name, &statbuf);
518 if (S_ISDIR(statbuf.st_mode)) {
519 if (flags & SHOW_DIRS) {
520 rows[i].name = malloc(strlen(ep->d_name) + 2);
521 strcpy(rows[i].name, ep->d_name);
522 strcat(rows[i].name, "/");
523 rows[i].mode = statbuf.st_mode;
524 i++;
526 } else if (flags & SHOW_FILES) {
527 rows[i].name = malloc(strlen(ep->d_name) + 1);
528 strcpy(rows[i].name, ep->d_name);
529 rows[i].size = statbuf.st_size;
530 rows[i].mode = statbuf.st_mode;
531 i++;
534 n = i; /* Ignore unused space in array caused by filters. */
535 qsort(rows, n, sizeof (*rows), rowcmp);
536 closedir(dp);
537 *rowsp = rows;
538 return n;
541 static void
542 free_rows(Row **rowsp, int nfiles)
544 int i;
546 for (i = 0; i < nfiles; i++)
547 free((*rowsp)[i].name);
548 free(*rowsp);
549 *rowsp = NULL;
552 /* Change working directory to the path in CWD. */
553 static void
554 cd(int reset)
556 int i, j;
558 message(CYAN, "Loading...");
559 refresh();
560 if (reset) ESEL = SCROLL = 0;
561 chdir(CWD);
562 if (rover.nfiles)
563 free_rows(&rover.rows, rover.nfiles);
564 rover.nfiles = ls(&rover.rows, FLAGS);
565 if (!strcmp(CWD, rover.marks.dirpath)) {
566 for (i = 0; i < rover.nfiles; i++) {
567 for (j = 0; j < rover.marks.bulk; j++)
568 if (
569 rover.marks.entries[j] &&
570 !strcmp(rover.marks.entries[j], ENAME(i))
572 break;
573 MARKED(i) = j < rover.marks.bulk;
575 } else
576 for (i = 0; i < rover.nfiles; i++)
577 MARKED(i) = 0;
578 clear_message();
579 update_view();
582 /* Select a target entry, if it is present. */
583 static void
584 try_to_sel(const char *target)
586 ESEL = 0;
587 if (!ISDIR(target))
588 while ((ESEL+1) < rover.nfiles && S_ISDIR(EMODE(ESEL)))
589 ESEL++;
590 while ((ESEL+1) < rover.nfiles && strcoll(ENAME(ESEL), target) < 0)
591 ESEL++;
594 /* Reload CWD, but try to keep selection. */
595 static void
596 reload()
598 if (rover.nfiles) {
599 strcpy(INPUT, ENAME(ESEL));
600 cd(0);
601 try_to_sel(INPUT);
602 update_view();
603 } else
604 cd(1);
607 static off_t
608 count_dir(const char *path)
610 DIR *dp;
611 struct dirent *ep;
612 struct stat statbuf;
613 char subpath[PATH_MAX];
614 off_t total;
616 if(!(dp = opendir(path))) return 0;
617 total = 0;
618 while ((ep = readdir(dp))) {
619 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
620 continue;
621 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
622 lstat(subpath, &statbuf);
623 if (S_ISDIR(statbuf.st_mode)) {
624 strcat(subpath, "/");
625 total += count_dir(subpath);
626 } else
627 total += statbuf.st_size;
629 closedir(dp);
630 return total;
633 static off_t
634 count_marked()
636 int i;
637 char *entry;
638 off_t total;
639 struct stat statbuf;
641 total = 0;
642 chdir(rover.marks.dirpath);
643 for (i = 0; i < rover.marks.bulk; i++) {
644 entry = rover.marks.entries[i];
645 if (entry) {
646 if (ISDIR(entry)) {
647 total += count_dir(entry);
648 } else {
649 lstat(entry, &statbuf);
650 total += statbuf.st_size;
654 chdir(CWD);
655 return total;
658 /* Recursively process a source directory using CWD as destination root.
659 For each node (i.e. directory), do the following:
660 1. call pre(destination);
661 2. call proc() on every child leaf (i.e. files);
662 3. recurse into every child node;
663 4. call pos(source).
664 E.g. to move directory /src/ (and all its contents) inside /dst/:
665 strcpy(CWD, "/dst/");
666 process_dir(adddir, movfile, deldir, "/src/"); */
667 static int
668 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
670 int ret;
671 DIR *dp;
672 struct dirent *ep;
673 struct stat statbuf;
674 char subpath[PATH_MAX];
676 ret = 0;
677 if (pre) {
678 char dstpath[PATH_MAX];
679 strcpy(dstpath, CWD);
680 strcat(dstpath, path + strlen(rover.marks.dirpath));
681 ret |= pre(dstpath);
683 if(!(dp = opendir(path))) return -1;
684 while ((ep = readdir(dp))) {
685 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
686 continue;
687 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
688 stat(subpath, &statbuf);
689 if (S_ISDIR(statbuf.st_mode)) {
690 strcat(subpath, "/");
691 ret |= process_dir(pre, proc, pos, subpath);
692 } else
693 ret |= proc(subpath);
695 closedir(dp);
696 if (pos) ret |= pos(path);
697 return ret;
700 /* Process all marked entries using CWD as destination root.
701 All marked entries that are directories will be recursively processed.
702 See process_dir() for details on the parameters. */
703 static void
704 process_marked(PROCESS pre, PROCESS proc, PROCESS pos,
705 const char *msg_doing, const char *msg_done)
707 int i, ret;
708 char *entry;
709 char path[PATH_MAX];
711 clear_message();
712 message(CYAN, "%s...", msg_doing);
713 refresh();
714 rover.prog = (Prog) {0, count_marked(), msg_doing};
715 for (i = 0; i < rover.marks.bulk; i++) {
716 entry = rover.marks.entries[i];
717 if (entry) {
718 ret = 0;
719 snprintf(path, PATH_MAX, "%s%s", rover.marks.dirpath, entry);
720 if (ISDIR(entry)) {
721 if (!strncmp(path, CWD, strlen(path)))
722 ret = -1;
723 else
724 ret = process_dir(pre, proc, pos, path);
725 } else
726 ret = proc(path);
727 if (!ret) {
728 del_mark(&rover.marks, entry);
729 reload();
733 rover.prog.total = 0;
734 reload();
735 if (!rover.marks.nentries)
736 message(GREEN, "%s all marked entries.", msg_done);
737 else
738 message(RED, "Some errors occured while %s.", msg_doing);
739 RV_ALERT();
742 static void
743 update_progress(off_t delta)
745 int percent;
747 if (!rover.prog.total) return;
748 rover.prog.partial += delta;
749 percent = (int) (rover.prog.partial * 100 / rover.prog.total);
750 message(CYAN, "%s...%d%%", rover.prog.msg, percent);
751 refresh();
754 /* Wrappers for file operations. */
755 static int delfile(const char *path) {
756 int ret;
757 struct stat st;
759 ret = lstat(path, &st);
760 if (ret < 0) return ret;
761 update_progress(st.st_size);
762 return unlink(path);
764 static PROCESS deldir = rmdir;
765 static int addfile(const char *path) {
766 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
767 int ret;
769 ret = creat(path, 0644);
770 if (ret < 0) return ret;
771 return close(ret);
773 static int cpyfile(const char *srcpath) {
774 int src, dst, ret;
775 size_t size;
776 struct stat st;
777 char buf[BUFSIZ];
778 char dstpath[PATH_MAX];
780 ret = src = open(srcpath, O_RDONLY);
781 if (ret < 0) return ret;
782 ret = fstat(src, &st);
783 if (ret < 0) return ret;
784 strcpy(dstpath, CWD);
785 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
786 ret = dst = creat(dstpath, st.st_mode);
787 if (ret < 0) return ret;
788 while ((size = read(src, buf, BUFSIZ)) > 0) {
789 write(dst, buf, size);
790 update_progress(size);
791 sync_signals();
793 close(src);
794 close(dst);
795 return 0;
797 static int adddir(const char *path) {
798 int ret;
799 struct stat st;
801 ret = stat(CWD, &st);
802 if (ret < 0) return ret;
803 return mkdir(path, st.st_mode);
805 static int movfile(const char *srcpath) {
806 int ret;
807 struct stat st;
808 char dstpath[PATH_MAX];
810 strcpy(dstpath, CWD);
811 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
812 ret = rename(srcpath, dstpath);
813 if (ret == 0) {
814 ret = lstat(srcpath, &st);
815 if (ret < 0) return ret;
816 update_progress(st.st_size);
817 } else if (errno == EXDEV) {
818 ret = cpyfile(srcpath);
819 if (ret < 0) return ret;
820 ret = unlink(srcpath);
822 return ret;
825 static void
826 start_line_edit(const char *init_input)
828 curs_set(TRUE);
829 strncpy(INPUT, init_input, BUFLEN);
830 rover.edit.left = mbstowcs(rover.edit.buffer, init_input, BUFLEN);
831 rover.edit.right = BUFLEN - 1;
832 rover.edit.buffer[BUFLEN] = L'\0';
833 rover.edit_scroll = 0;
836 /* Read input and change editing state accordingly. */
837 static EditStat
838 get_line_edit()
840 wchar_t eraser, killer, wch;
841 int ret, length;
843 ret = rover_get_wch((wint_t *) &wch);
844 erasewchar(&eraser);
845 killwchar(&killer);
846 if (ret == KEY_CODE_YES) {
847 if (wch == KEY_ENTER) {
848 curs_set(FALSE);
849 return CONFIRM;
850 } else if (wch == KEY_LEFT) {
851 if (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
852 } else if (wch == KEY_RIGHT) {
853 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
854 } else if (wch == KEY_UP) {
855 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
856 } else if (wch == KEY_DOWN) {
857 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
858 } else if (wch == KEY_BACKSPACE) {
859 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
860 } else if (wch == KEY_DC) {
861 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
863 } else {
864 if (wch == L'\r' || wch == L'\n') {
865 curs_set(FALSE);
866 return CONFIRM;
867 } else if (wch == L'\t') {
868 curs_set(FALSE);
869 return CANCEL;
870 } else if (wch == eraser) {
871 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
872 } else if (wch == killer) {
873 EDIT_CLEAR(rover.edit);
874 clear_message();
875 } else if (iswprint(wch)) {
876 if (!EDIT_FULL(rover.edit)) EDIT_INSERT(rover.edit, wch);
879 /* Encode edit contents in INPUT. */
880 rover.edit.buffer[rover.edit.left] = L'\0';
881 length = wcstombs(INPUT, rover.edit.buffer, BUFLEN);
882 wcstombs(&INPUT[length], &rover.edit.buffer[rover.edit.right+1],
883 BUFLEN-length);
884 return CONTINUE;
887 /* Update line input on the screen. */
888 static void
889 update_input(const char *prompt, Color color)
891 int plen, ilen, maxlen;
893 plen = strlen(prompt);
894 ilen = mbstowcs(NULL, INPUT, 0);
895 maxlen = STATUSPOS - plen - 2;
896 if (ilen - rover.edit_scroll < maxlen)
897 rover.edit_scroll = MAX(ilen - maxlen, 0);
898 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
899 rover.edit_scroll = rover.edit.left - maxlen;
900 else if (rover.edit.left < rover.edit_scroll)
901 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
902 color_set(RVC_PROMPT, NULL);
903 mvaddstr(LINES - 1, 0, prompt);
904 color_set(color, NULL);
905 mbstowcs(WBUF, INPUT, COLS);
906 mvaddnwstr(LINES - 1, plen, &WBUF[rover.edit_scroll], maxlen);
907 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
908 color_set(DEFAULT, NULL);
909 if (rover.edit_scroll)
910 mvaddch(LINES - 1, plen - 1, '<');
911 if (ilen > rover.edit_scroll + maxlen)
912 mvaddch(LINES - 1, plen + maxlen, '>');
913 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
917 main(int argc, char *argv[])
919 int i, ch;
920 char *program;
921 const char *key;
922 DIR *d;
923 EditStat edit_stat;
924 FILE *save_cwd_file = NULL;
926 if (argc >= 2) {
927 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
928 printf("rover %s\n", RV_VERSION);
929 return 0;
930 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
931 printf(
932 "Usage: rover [-s|--save-cwd FILE] [DIR [DIR [DIR [...]]]]\n"
933 " Browse current directory or the ones specified.\n"
934 " If FILE is given, write last visited path to it.\n\n"
935 " or: rover -h|--help\n"
936 " Print this help message and exit.\n\n"
937 " or: rover -v|--version\n"
938 " Print program version and exit.\n\n"
939 "See rover(1) for more information.\n\n"
940 "Rover homepage: <https://github.com/lecram/rover>.\n"
942 return 0;
943 } else if (!strcmp(argv[1], "-s") || !strcmp(argv[1], "--save-cwd")) {
944 if (argc > 2) {
945 save_cwd_file = fopen(argv[2], "w");
946 argc -= 2; argv += 2;
947 } else {
948 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
949 return 1;
953 init_term();
954 rover.nfiles = 0;
955 for (i = 0; i < 10; i++) {
956 rover.tabs[i].esel = rover.tabs[i].scroll = 0;
957 rover.tabs[i].flags = SHOW_FILES | SHOW_DIRS;
959 strcpy(rover.tabs[0].cwd, getenv("HOME"));
960 for (i = 1; i < argc && i < 10; i++) {
961 if ((d = opendir(argv[i]))) {
962 realpath(argv[i], rover.tabs[i].cwd);
963 closedir(d);
964 } else
965 strcpy(rover.tabs[i].cwd, rover.tabs[0].cwd);
967 getcwd(rover.tabs[i].cwd, PATH_MAX);
968 for (i++; i < 10; i++)
969 strcpy(rover.tabs[i].cwd, rover.tabs[i-1].cwd);
970 for (i = 0; i < 10; i++)
971 if (rover.tabs[i].cwd[strlen(rover.tabs[i].cwd) - 1] != '/')
972 strcat(rover.tabs[i].cwd, "/");
973 rover.tab = 1;
974 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
975 init_marks(&rover.marks);
976 cd(1);
977 while (1) {
978 ch = rover_getch();
979 key = keyname(ch);
980 clear_message();
981 if (!strcmp(key, RVK_QUIT)) break;
982 else if (ch >= '0' && ch <= '9') {
983 rover.tab = ch - '0';
984 cd(0);
985 } else if (!strcmp(key, RVK_HELP)) {
986 ARGS[0] = "man";
987 ARGS[1] = "rover";
988 ARGS[2] = NULL;
989 spawn();
990 } else if (!strcmp(key, RVK_DOWN)) {
991 if (!rover.nfiles) continue;
992 ESEL = MIN(ESEL + 1, rover.nfiles - 1);
993 update_view();
994 } else if (!strcmp(key, RVK_UP)) {
995 if (!rover.nfiles) continue;
996 ESEL = MAX(ESEL - 1, 0);
997 update_view();
998 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
999 if (!rover.nfiles) continue;
1000 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
1001 if (rover.nfiles > HEIGHT)
1002 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
1003 update_view();
1004 } else if (!strcmp(key, RVK_JUMP_UP)) {
1005 if (!rover.nfiles) continue;
1006 ESEL = MAX(ESEL - RV_JUMP, 0);
1007 SCROLL = MAX(SCROLL - RV_JUMP, 0);
1008 update_view();
1009 } else if (!strcmp(key, RVK_JUMP_TOP)) {
1010 if (!rover.nfiles) continue;
1011 ESEL = 0;
1012 update_view();
1013 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
1014 if (!rover.nfiles) continue;
1015 ESEL = rover.nfiles - 1;
1016 update_view();
1017 } else if (!strcmp(key, RVK_CD_DOWN)) {
1018 if (!rover.nfiles || !S_ISDIR(EMODE(ESEL))) continue;
1019 if (chdir(ENAME(ESEL)) == -1) {
1020 message(RED, "Cannot access \"%s\".", ENAME(ESEL));
1021 continue;
1023 strcat(CWD, ENAME(ESEL));
1024 cd(1);
1025 } else if (!strcmp(key, RVK_CD_UP)) {
1026 char *dirname, first;
1027 if (!strcmp(CWD, "/")) continue;
1028 CWD[strlen(CWD) - 1] = '\0';
1029 dirname = strrchr(CWD, '/') + 1;
1030 first = dirname[0];
1031 dirname[0] = '\0';
1032 cd(1);
1033 dirname[0] = first;
1034 dirname[strlen(dirname)] = '/';
1035 try_to_sel(dirname);
1036 dirname[0] = '\0';
1037 if (rover.nfiles > HEIGHT)
1038 SCROLL = ESEL - HEIGHT / 2;
1039 update_view();
1040 } else if (!strcmp(key, RVK_HOME)) {
1041 strcpy(CWD, getenv("HOME"));
1042 if (CWD[strlen(CWD) - 1] != '/')
1043 strcat(CWD, "/");
1044 cd(1);
1045 } else if (!strcmp(key, RVK_REFRESH)) {
1046 reload();
1047 } else if (!strcmp(key, RVK_SHELL)) {
1048 program = getenv("SHELL");
1049 if (program) {
1050 ARGS[0] = program;
1051 ARGS[1] = NULL;
1052 spawn();
1053 reload();
1055 } else if (!strcmp(key, RVK_VIEW)) {
1056 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1057 program = getenv("PAGER");
1058 if (program) {
1059 ARGS[0] = program;
1060 ARGS[1] = ENAME(ESEL);
1061 ARGS[2] = NULL;
1062 spawn();
1064 } else if (!strcmp(key, RVK_EDIT)) {
1065 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
1066 program = getenv("EDITOR");
1067 if (program) {
1068 ARGS[0] = program;
1069 ARGS[1] = ENAME(ESEL);
1070 ARGS[2] = NULL;
1071 spawn();
1072 cd(0);
1074 } else if (!strcmp(key, RVK_SEARCH)) {
1075 int oldsel, oldscroll, length;
1076 if (!rover.nfiles) continue;
1077 oldsel = ESEL;
1078 oldscroll = SCROLL;
1079 start_line_edit("");
1080 update_input(RVP_SEARCH, RED);
1081 while ((edit_stat = get_line_edit()) == CONTINUE) {
1082 int sel;
1083 Color color = RED;
1084 length = strlen(INPUT);
1085 if (length) {
1086 for (sel = 0; sel < rover.nfiles; sel++)
1087 if (!strncmp(ENAME(sel), INPUT, length))
1088 break;
1089 if (sel < rover.nfiles) {
1090 color = GREEN;
1091 ESEL = sel;
1092 if (rover.nfiles > HEIGHT) {
1093 if (sel < 3)
1094 SCROLL = 0;
1095 else if (sel - 3 > rover.nfiles - HEIGHT)
1096 SCROLL = rover.nfiles - HEIGHT;
1097 else
1098 SCROLL = sel - 3;
1101 } else {
1102 ESEL = oldsel;
1103 SCROLL = oldscroll;
1105 update_view();
1106 update_input(RVP_SEARCH, color);
1108 if (edit_stat == CANCEL) {
1109 ESEL = oldsel;
1110 SCROLL = oldscroll;
1112 clear_message();
1113 update_view();
1114 } else if (!strcmp(key, RVK_TG_FILES)) {
1115 FLAGS ^= SHOW_FILES;
1116 reload();
1117 } else if (!strcmp(key, RVK_TG_DIRS)) {
1118 FLAGS ^= SHOW_DIRS;
1119 reload();
1120 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
1121 FLAGS ^= SHOW_HIDDEN;
1122 reload();
1123 } else if (!strcmp(key, RVK_NEW_FILE)) {
1124 int ok = 0;
1125 start_line_edit("");
1126 update_input(RVP_NEW_FILE, RED);
1127 while ((edit_stat = get_line_edit()) == CONTINUE) {
1128 int length = strlen(INPUT);
1129 ok = length;
1130 for (i = 0; i < rover.nfiles; i++) {
1131 if (
1132 !strncmp(ENAME(i), INPUT, length) &&
1133 (!strcmp(ENAME(i) + length, "") ||
1134 !strcmp(ENAME(i) + length, "/"))
1136 ok = 0;
1137 break;
1140 update_input(RVP_NEW_FILE, ok ? GREEN : RED);
1142 clear_message();
1143 if (edit_stat == CONFIRM) {
1144 if (ok) {
1145 addfile(INPUT);
1146 cd(1);
1147 try_to_sel(INPUT);
1148 update_view();
1149 } else
1150 message(RED, "\"%s\" already exists.", INPUT);
1152 } else if (!strcmp(key, RVK_NEW_DIR)) {
1153 int ok = 0;
1154 start_line_edit("");
1155 update_input(RVP_NEW_DIR, RED);
1156 while ((edit_stat = get_line_edit()) == CONTINUE) {
1157 int length = strlen(INPUT);
1158 ok = length;
1159 for (i = 0; i < rover.nfiles; i++) {
1160 if (
1161 !strncmp(ENAME(i), INPUT, length) &&
1162 (!strcmp(ENAME(i) + length, "") ||
1163 !strcmp(ENAME(i) + length, "/"))
1165 ok = 0;
1166 break;
1169 update_input(RVP_NEW_DIR, ok ? GREEN : RED);
1171 clear_message();
1172 if (edit_stat == CONFIRM) {
1173 if (ok) {
1174 adddir(INPUT);
1175 cd(1);
1176 strcat(INPUT, "/");
1177 try_to_sel(INPUT);
1178 update_view();
1179 } else
1180 message(RED, "\"%s\" already exists.", INPUT);
1182 } else if (!strcmp(key, RVK_RENAME)) {
1183 int ok = 0;
1184 char *last;
1185 int isdir;
1186 strcpy(INPUT, ENAME(ESEL));
1187 last = INPUT + strlen(INPUT) - 1;
1188 if ((isdir = *last == '/'))
1189 *last = '\0';
1190 start_line_edit(INPUT);
1191 update_input(RVP_RENAME, RED);
1192 while ((edit_stat = get_line_edit()) == CONTINUE) {
1193 int length = strlen(INPUT);
1194 ok = length;
1195 for (i = 0; i < rover.nfiles; i++)
1196 if (
1197 !strncmp(ENAME(i), INPUT, length) &&
1198 (!strcmp(ENAME(i) + length, "") ||
1199 !strcmp(ENAME(i) + length, "/"))
1201 ok = 0;
1202 break;
1204 update_input(RVP_RENAME, ok ? GREEN : RED);
1206 clear_message();
1207 if (edit_stat == CONFIRM) {
1208 if (isdir)
1209 strcat(INPUT, "/");
1210 if (ok) {
1211 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1212 del_mark(&rover.marks, ENAME(ESEL));
1213 add_mark(&rover.marks, CWD, INPUT);
1215 cd(1);
1216 try_to_sel(INPUT);
1217 update_view();
1218 } else
1219 message(RED, "\"%s\" already exists.", INPUT);
1221 } else if (!strcmp(key, RVK_DELETE)) {
1222 if (rover.nfiles) {
1223 message(YELLOW, "Delete \"%s\"? (Y to confirm)", ENAME(ESEL));
1224 if (rover_getch() == 'Y') {
1225 const char *name = ENAME(ESEL);
1226 int ret = S_ISDIR(EMODE(ESEL)) ? deldir(name) : delfile(name);
1227 reload();
1228 if (ret)
1229 message(RED, "Could not delete \"%s\".", ENAME(ESEL));
1230 } else
1231 clear_message();
1232 } else
1233 message(RED, "No entry selected for deletion.");
1234 } else if (!strcmp(key, RVK_TG_MARK)) {
1235 if (MARKED(ESEL))
1236 del_mark(&rover.marks, ENAME(ESEL));
1237 else
1238 add_mark(&rover.marks, CWD, ENAME(ESEL));
1239 MARKED(ESEL) = !MARKED(ESEL);
1240 ESEL = (ESEL + 1) % rover.nfiles;
1241 update_view();
1242 } else if (!strcmp(key, RVK_INVMARK)) {
1243 for (i = 0; i < rover.nfiles; i++) {
1244 if (MARKED(i))
1245 del_mark(&rover.marks, ENAME(i));
1246 else
1247 add_mark(&rover.marks, CWD, ENAME(i));
1248 MARKED(i) = !MARKED(i);
1250 update_view();
1251 } else if (!strcmp(key, RVK_MARKALL)) {
1252 for (i = 0; i < rover.nfiles; i++)
1253 if (!MARKED(i)) {
1254 add_mark(&rover.marks, CWD, ENAME(i));
1255 MARKED(i) = 1;
1257 update_view();
1258 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1259 if (rover.marks.nentries) {
1260 message(YELLOW, "Delete all marked entries? (Y to confirm)");
1261 if (rover_getch() == 'Y')
1262 process_marked(NULL, delfile, deldir, "Deleting", "Deleted");
1263 else
1264 clear_message();
1265 } else
1266 message(RED, "No entries marked for deletion.");
1267 } else if (!strcmp(key, RVK_MARK_COPY)) {
1268 if (rover.marks.nentries)
1269 process_marked(adddir, cpyfile, NULL, "Copying", "Copied");
1270 else
1271 message(RED, "No entries marked for copying.");
1272 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1273 if (rover.marks.nentries)
1274 process_marked(adddir, movfile, deldir, "Moving", "Moved");
1275 else
1276 message(RED, "No entries marked for moving.");
1279 if (rover.nfiles)
1280 free_rows(&rover.rows, rover.nfiles);
1281 free_marks(&rover.marks);
1282 delwin(rover.window);
1283 if (save_cwd_file != NULL) {
1284 fputs(CWD, save_cwd_file);
1285 fclose(save_cwd_file);
1287 return 0;