Better messages for batch processing.
[rover.git] / rover.c
blob6abfcabd4118371d8a324d9a0a6ddd84b87ddf86
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 /* Global state. */
83 static struct Rover {
84 int tab;
85 int nfiles;
86 Row *rows;
87 WINDOW *window;
88 Marks marks;
89 Edit edit;
90 int edit_scroll;
91 volatile sig_atomic_t pending_winch;
92 Tab tabs[10];
93 } rover;
95 /* Macros for accessing global state. */
96 #define ENAME(I) rover.rows[I].name
97 #define ESIZE(I) rover.rows[I].size
98 #define EMODE(I) rover.rows[I].mode
99 #define ISLINK(I) rover.rows[I].islink
100 #define MARKED(I) rover.rows[I].marked
101 #define SCROLL rover.tabs[rover.tab].scroll
102 #define ESEL rover.tabs[rover.tab].esel
103 #define FLAGS rover.tabs[rover.tab].flags
104 #define CWD rover.tabs[rover.tab].cwd
106 /* Helpers. */
107 #define MIN(A, B) ((A) < (B) ? (A) : (B))
108 #define MAX(A, B) ((A) > (B) ? (A) : (B))
109 #define ISDIR(E) (strchr((E), '/') != NULL)
111 /* Line Editing Macros. */
112 #define EDIT_FULL(E) ((E).left == (E).right)
113 #define EDIT_CAN_LEFT(E) ((E).left)
114 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
115 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
116 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
117 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
118 #define EDIT_BACKSPACE(E) (E).left--
119 #define EDIT_DELETE(E) (E).right++
120 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
122 typedef enum EditStat {CONTINUE, CONFIRM, CANCEL} EditStat;
123 typedef enum Color {DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK} Color;
124 typedef int (*PROCESS)(const char *path);
126 static void
127 init_marks(Marks *marks)
129 strcpy(marks->dirpath, "");
130 marks->bulk = BULK_INIT;
131 marks->nentries = 0;
132 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
135 /* Unmark all entries. */
136 static void
137 mark_none(Marks *marks)
139 int i;
141 strcpy(marks->dirpath, "");
142 for (i = 0; i < marks->bulk && marks->nentries; i++)
143 if (marks->entries[i]) {
144 free(marks->entries[i]);
145 marks->entries[i] = NULL;
146 marks->nentries--;
148 if (marks->bulk > BULK_THRESH) {
149 /* Reset bulk to free some memory. */
150 free(marks->entries);
151 marks->bulk = BULK_INIT;
152 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
156 static void
157 add_mark(Marks *marks, char *dirpath, char *entry)
159 int i;
161 if (!strcmp(marks->dirpath, dirpath)) {
162 /* Append mark to directory. */
163 if (marks->nentries == marks->bulk) {
164 /* Expand bulk to accomodate new entry. */
165 int extra = marks->bulk / 2;
166 marks->bulk += extra; /* bulk *= 1.5; */
167 marks->entries = realloc(marks->entries,
168 marks->bulk * sizeof *marks->entries);
169 memset(&marks->entries[marks->nentries], 0,
170 extra * sizeof *marks->entries);
171 i = marks->nentries;
172 } else {
173 /* Search for empty slot (there must be one). */
174 for (i = 0; i < marks->bulk; i++)
175 if (!marks->entries[i])
176 break;
178 } else {
179 /* Directory changed. Discard old marks. */
180 mark_none(marks);
181 strcpy(marks->dirpath, dirpath);
182 i = 0;
184 marks->entries[i] = malloc(strlen(entry) + 1);
185 strcpy(marks->entries[i], entry);
186 marks->nentries++;
189 static void
190 del_mark(Marks *marks, char *entry)
192 int i;
194 if (marks->nentries > 1) {
195 for (i = 0; i < marks->bulk; i++)
196 if (marks->entries[i] && !strcmp(marks->entries[i], entry))
197 break;
198 free(marks->entries[i]);
199 marks->entries[i] = NULL;
200 marks->nentries--;
201 } else
202 mark_none(marks);
205 static void
206 free_marks(Marks *marks)
208 int i;
210 for (i = 0; i < marks->bulk && marks->nentries; i++)
211 if (marks->entries[i]) {
212 free(marks->entries[i]);
213 marks->nentries--;
215 free(marks->entries);
218 static void
219 handle_winch(int sig)
221 rover.pending_winch = 1;
224 static void
225 enable_handlers()
227 struct sigaction sa;
229 memset(&sa, 0, sizeof (struct sigaction));
230 sa.sa_handler = handle_winch;
231 sigaction(SIGWINCH, &sa, NULL);
234 static void
235 disable_handlers()
237 struct sigaction sa;
239 memset(&sa, 0, sizeof (struct sigaction));
240 sa.sa_handler = SIG_DFL;
241 sigaction(SIGWINCH, &sa, NULL);
244 static void update_view();
246 /* Handle any signals received since last call. */
247 static void
248 sync_signals()
250 if (rover.pending_winch) {
251 /* SIGWINCH received: resize application accordingly. */
252 delwin(rover.window);
253 endwin();
254 refresh();
255 clear();
256 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
257 if (HEIGHT < rover.nfiles && SCROLL + HEIGHT > rover.nfiles)
258 SCROLL = ESEL - HEIGHT;
259 update_view();
260 rover.pending_winch = 0;
264 /* This function must be used in place of getch().
265 It handles signals while waiting for user input. */
266 static int
267 rover_getch()
269 int ch;
271 while ((ch = getch()) == ERR)
272 sync_signals();
273 return ch;
276 /* This function must be used in place of get_wch().
277 It handles signals while waiting for user input. */
278 static int
279 rover_get_wch(wint_t *wch)
281 wint_t ret;
283 while ((ret = get_wch(wch)) == (wint_t) ERR)
284 sync_signals();
285 return ret;
288 /* Do a fork-exec to external program (e.g. $EDITOR). */
289 static void
290 spawn()
292 pid_t pid;
293 int status;
295 setenv("RVSEL", rover.nfiles ? ENAME(ESEL) : "", 1);
296 pid = fork();
297 if (pid > 0) {
298 /* fork() succeeded. */
299 disable_handlers();
300 endwin();
301 waitpid(pid, &status, 0);
302 enable_handlers();
303 kill(getpid(), SIGWINCH);
304 } else if (pid == 0) {
305 /* Child process. */
306 execvp(ARGS[0], ARGS);
310 /* Curses setup. */
311 static void
312 init_term()
314 setlocale(LC_ALL, "");
315 initscr();
316 cbreak(); /* Get one character at a time. */
317 timeout(100); /* For getch(). */
318 noecho();
319 nonl(); /* No NL->CR/NL on output. */
320 intrflush(stdscr, FALSE);
321 keypad(stdscr, TRUE);
322 curs_set(FALSE); /* Hide blinking cursor. */
323 if (has_colors()) {
324 short bg;
325 start_color();
326 #ifdef NCURSES_EXT_FUNCS
327 use_default_colors();
328 bg = -1;
329 #else
330 bg = COLOR_BLACK;
331 #endif
332 init_pair(RED, COLOR_RED, bg);
333 init_pair(GREEN, COLOR_GREEN, bg);
334 init_pair(YELLOW, COLOR_YELLOW, bg);
335 init_pair(BLUE, COLOR_BLUE, bg);
336 init_pair(CYAN, COLOR_CYAN, bg);
337 init_pair(MAGENTA, COLOR_MAGENTA, bg);
338 init_pair(WHITE, COLOR_WHITE, bg);
339 init_pair(BLACK, COLOR_BLACK, bg);
341 atexit((void (*)(void)) endwin);
342 enable_handlers();
345 /* Update the listing view. */
346 static void
347 update_view()
349 int i, j;
350 int numsize;
351 int ishidden, isdir;
352 int marking;
354 mvhline(0, 0, ' ', COLS);
355 attr_on(A_BOLD, NULL);
356 color_set(RVC_TABNUM, NULL);
357 mvaddch(0, COLS - 2, rover.tab + '0');
358 attr_off(A_BOLD, NULL);
359 if (rover.marks.nentries) {
360 numsize = snprintf(BUF1, BUFLEN, "%d", rover.marks.nentries);
361 color_set(RVC_MARKS, NULL);
362 mvaddstr(0, COLS - 3 - numsize, BUF1);
363 } else
364 numsize = -1;
365 color_set(RVC_CWD, NULL);
366 mbstowcs(WBUF, CWD, PATH_MAX);
367 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
368 wcolor_set(rover.window, RVC_BORDER, NULL);
369 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
370 /* Selection might not be visible, due to cursor wrapping or window
371 shrinking. In that case, the scroll must be moved to make it visible. */
372 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
373 marking = !strcmp(CWD, rover.marks.dirpath);
374 for (i = 0, j = SCROLL; i < HEIGHT && j < rover.nfiles; i++, j++) {
375 ishidden = ENAME(j)[0] == '.';
376 isdir = S_ISDIR(EMODE(j));
377 if (j == ESEL)
378 wattr_on(rover.window, A_REVERSE, NULL);
379 if (ISLINK(j))
380 wcolor_set(rover.window, RVC_LINK, NULL);
381 else if (ishidden)
382 wcolor_set(rover.window, RVC_HIDDEN, NULL);
383 else if (isdir)
384 wcolor_set(rover.window, RVC_DIR, NULL);
385 else
386 wcolor_set(rover.window, RVC_FILE, NULL);
387 if (!isdir) {
388 char *suffix, *suffixes = "BKMGTPEZY";
389 off_t human_size = ESIZE(j) * 10;
390 int length = mbstowcs(NULL, ENAME(j), 0);
391 for (suffix = suffixes; human_size >= 10240; suffix++)
392 human_size = (human_size + 512) / 1024;
393 if (*suffix == 'B')
394 swprintf(WBUF, PATH_MAX, L"%s%*d %c", ENAME(j),
395 (int) (COLS - length - 6),
396 (int) human_size / 10, *suffix);
397 else
398 swprintf(WBUF, PATH_MAX, L"%s%*d.%d %c", ENAME(j),
399 (int) (COLS - length - 8),
400 (int) human_size / 10, (int) human_size % 10, *suffix);
401 } else
402 mbstowcs(WBUF, ENAME(j), PATH_MAX);
403 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
404 mvwaddnwstr(rover.window, i + 1, 2, WBUF, COLS - 4);
405 if (marking && MARKED(j)) {
406 wcolor_set(rover.window, RVC_MARKS, NULL);
407 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
408 } else
409 mvwaddch(rover.window, i + 1, 1, ' ');
410 if (j == ESEL)
411 wattr_off(rover.window, A_REVERSE, NULL);
413 for (; i < HEIGHT; i++)
414 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
415 if (rover.nfiles > HEIGHT) {
416 int center, height;
417 center = (SCROLL + HEIGHT / 2) * HEIGHT / rover.nfiles;
418 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
419 if (!height) height = 1;
420 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
421 mvwvline(rover.window, center-height/2+1, COLS-1, RVS_SCROLLBAR, height);
423 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
424 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
425 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
426 if (!rover.nfiles)
427 strcpy(BUF2, "0/0");
428 else
429 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, rover.nfiles);
430 snprintf(BUF1+3, BUFLEN-3, "%12s", BUF2);
431 color_set(RVC_STATUS, NULL);
432 mvaddstr(LINES - 1, STATUSPOS, BUF1);
433 wrefresh(rover.window);
436 /* Show a message on the status bar. */
437 static void
438 message(Color color, char *fmt, ...)
440 int len, pos;
441 va_list args;
443 va_start(args, fmt);
444 vsprintf(BUF1, fmt, args);
445 va_end(args);
446 len = strlen(BUF1);
447 pos = (STATUSPOS - len) / 2;
448 attr_on(A_BOLD, NULL);
449 color_set(color, NULL);
450 mvaddstr(LINES - 1, pos, BUF1);
451 color_set(DEFAULT, NULL);
452 attr_off(A_BOLD, NULL);
455 /* Clear message area, leaving only status info. */
456 static void
457 clear_message()
459 mvhline(LINES - 1, 0, ' ', STATUSPOS);
462 /* Comparison used to sort listing entries. */
463 static int
464 rowcmp(const void *a, const void *b)
466 int isdir1, isdir2, cmpdir;
467 const Row *r1 = a;
468 const Row *r2 = b;
469 isdir1 = S_ISDIR(r1->mode);
470 isdir2 = S_ISDIR(r2->mode);
471 cmpdir = isdir2 - isdir1;
472 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
475 /* Get all entries in current working directory. */
476 static int
477 ls(Row **rowsp, uint8_t flags)
479 DIR *dp;
480 struct dirent *ep;
481 struct stat statbuf;
482 Row *rows;
483 int i, n;
485 if(!(dp = opendir("."))) return -1;
486 n = -2; /* We don't want the entries "." and "..". */
487 while (readdir(dp)) n++;
488 rewinddir(dp);
489 rows = malloc(n * sizeof *rows);
490 i = 0;
491 while ((ep = readdir(dp))) {
492 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
493 continue;
494 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
495 continue;
496 lstat(ep->d_name, &statbuf);
497 rows[i].islink = S_ISLNK(statbuf.st_mode);
498 stat(ep->d_name, &statbuf);
499 if (S_ISDIR(statbuf.st_mode)) {
500 if (flags & SHOW_DIRS) {
501 rows[i].name = malloc(strlen(ep->d_name) + 2);
502 strcpy(rows[i].name, ep->d_name);
503 strcat(rows[i].name, "/");
504 rows[i].mode = statbuf.st_mode;
505 i++;
507 } else if (flags & SHOW_FILES) {
508 rows[i].name = malloc(strlen(ep->d_name) + 1);
509 strcpy(rows[i].name, ep->d_name);
510 rows[i].size = statbuf.st_size;
511 rows[i].mode = statbuf.st_mode;
512 i++;
515 n = i; /* Ignore unused space in array caused by filters. */
516 qsort(rows, n, sizeof (*rows), rowcmp);
517 closedir(dp);
518 *rowsp = rows;
519 return n;
522 static void
523 free_rows(Row **rowsp, int nfiles)
525 int i;
527 for (i = 0; i < nfiles; i++)
528 free((*rowsp)[i].name);
529 free(*rowsp);
530 *rowsp = NULL;
533 /* Change working directory to the path in CWD. */
534 static void
535 cd(int reset)
537 int i, j;
539 message(CYAN, "Loading...");
540 refresh();
541 if (reset) ESEL = SCROLL = 0;
542 chdir(CWD);
543 if (rover.nfiles)
544 free_rows(&rover.rows, rover.nfiles);
545 rover.nfiles = ls(&rover.rows, FLAGS);
546 if (!strcmp(CWD, rover.marks.dirpath)) {
547 for (i = 0; i < rover.nfiles; i++) {
548 for (j = 0; j < rover.marks.bulk; j++)
549 if (
550 rover.marks.entries[j] &&
551 !strcmp(rover.marks.entries[j], ENAME(i))
553 break;
554 MARKED(i) = j < rover.marks.bulk;
556 } else
557 for (i = 0; i < rover.nfiles; i++)
558 MARKED(i) = 0;
559 clear_message();
560 update_view();
563 /* Select a target entry, if it is present. */
564 static void
565 try_to_sel(const char *target)
567 ESEL = 0;
568 if (!ISDIR(target))
569 while ((ESEL+1) < rover.nfiles && S_ISDIR(EMODE(ESEL)))
570 ESEL++;
571 while ((ESEL+1) < rover.nfiles && strcoll(ENAME(ESEL), target) < 0)
572 ESEL++;
573 if (rover.nfiles > HEIGHT) {
574 SCROLL = ESEL - HEIGHT / 2;
575 SCROLL = MIN(MAX(SCROLL, 0), rover.nfiles - HEIGHT);
579 /* Reload CWD, but try to keep selection. */
580 static void
581 reload()
583 if (rover.nfiles) {
584 strcpy(INPUT, ENAME(ESEL));
585 cd(1);
586 try_to_sel(INPUT);
587 update_view();
588 } else
589 cd(1);
592 /* Recursively process a source directory using CWD as destination root.
593 For each node (i.e. directory), do the following:
594 1. call pre(destination);
595 2. call proc() on every child leaf (i.e. files);
596 3. recurse into every child node;
597 4. call pos(source).
598 E.g. to move directory /src/ (and all its contents) inside /dst/:
599 strcpy(CWD, "/dst/");
600 process_dir(adddir, movfile, deldir, "/src/"); */
601 static int
602 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
604 int ret;
605 DIR *dp;
606 struct dirent *ep;
607 struct stat statbuf;
608 char subpath[PATH_MAX];
610 ret = 0;
611 if (pre) {
612 char dstpath[PATH_MAX];
613 strcpy(dstpath, CWD);
614 strcat(dstpath, path + strlen(rover.marks.dirpath));
615 ret |= pre(dstpath);
617 if(!(dp = opendir(path))) return -1;
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 stat(subpath, &statbuf);
623 if (S_ISDIR(statbuf.st_mode)) {
624 strcat(subpath, "/");
625 ret |= process_dir(pre, proc, pos, subpath);
626 } else
627 ret |= proc(subpath);
629 closedir(dp);
630 if (pos) ret |= pos(path);
631 return ret;
634 /* Process all marked entries using CWD as destination root.
635 All marked entries that are directories will be recursively processed.
636 See process_dir() for details on the parameters. */
637 static void
638 process_marked(PROCESS pre, PROCESS proc, PROCESS pos,
639 const char *msg_doing, const char *msg_done)
641 int i, ret;
642 char path[PATH_MAX];
644 clear_message();
645 message(CYAN, "%s...", msg_doing);
646 refresh();
647 for (i = 0; i < rover.marks.bulk; i++)
648 if (rover.marks.entries[i]) {
649 ret = 0;
650 snprintf(path, PATH_MAX, "%s%s", rover.marks.dirpath, rover.marks.entries[i]);
651 if (ISDIR(rover.marks.entries[i])) {
652 if (!strncmp(path, CWD, strlen(path)))
653 ret = -1;
654 else
655 ret = process_dir(pre, proc, pos, path);
656 } else
657 ret = proc(path);
658 if (!ret) del_mark(&rover.marks, rover.marks.entries[i]);
660 reload();
661 if (!rover.marks.nentries)
662 message(GREEN, "%s all marked entries.", msg_done);
663 else
664 message(RED, "Some errors occured while %s.", msg_doing);
667 /* Wrappers for file operations. */
668 static PROCESS delfile = unlink;
669 static PROCESS deldir = rmdir;
670 static int addfile(const char *path) {
671 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
672 int ret;
674 ret = creat(path, 0644);
675 if (ret < 0) return ret;
676 return close(ret);
678 static int cpyfile(const char *srcpath) {
679 int src, dst, ret;
680 size_t size;
681 struct stat st;
682 char buf[BUFSIZ];
683 char dstpath[PATH_MAX];
685 ret = src = open(srcpath, O_RDONLY);
686 if (ret < 0) return ret;
687 ret = fstat(src, &st);
688 if (ret < 0) return ret;
689 strcpy(dstpath, CWD);
690 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
691 ret = dst = creat(dstpath, st.st_mode);
692 if (ret < 0) return ret;
693 while ((size = read(src, buf, BUFSIZ)) > 0) {
694 write(dst, buf, size);
695 sync_signals();
697 close(src);
698 close(dst);
699 return 0;
701 static int adddir(const char *path) {
702 int ret;
703 struct stat st;
705 ret = stat(CWD, &st);
706 if (ret < 0) return ret;
707 return mkdir(path, st.st_mode);
709 static int movfile(const char *srcpath) {
710 int ret;
711 char dstpath[PATH_MAX];
713 strcpy(dstpath, CWD);
714 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
715 ret = rename(srcpath, dstpath);
716 if (ret < 0 && errno == EXDEV) {
717 ret = cpyfile(srcpath);
718 if (ret < 0) return ret;
719 ret = delfile(srcpath);
721 return ret;
724 static void
725 start_line_edit(const char *init_input)
727 curs_set(TRUE);
728 strncpy(INPUT, init_input, BUFLEN);
729 rover.edit.left = mbstowcs(rover.edit.buffer, init_input, BUFLEN);
730 rover.edit.right = BUFLEN - 1;
731 rover.edit.buffer[BUFLEN] = L'\0';
732 rover.edit_scroll = 0;
735 /* Read input and change editing state accordingly. */
736 static EditStat
737 get_line_edit()
739 wchar_t eraser, killer, wch;
740 int ret, length;
742 ret = rover_get_wch((wint_t *) &wch);
743 erasewchar(&eraser);
744 killwchar(&killer);
745 if (ret == KEY_CODE_YES) {
746 if (wch == KEY_ENTER) {
747 curs_set(FALSE);
748 return CONFIRM;
749 } else if (wch == KEY_LEFT) {
750 if (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
751 } else if (wch == KEY_RIGHT) {
752 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
753 } else if (wch == KEY_UP) {
754 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
755 } else if (wch == KEY_DOWN) {
756 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
757 } else if (wch == KEY_BACKSPACE) {
758 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
759 } else if (wch == KEY_DC) {
760 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
762 } else {
763 if (wch == L'\r' || wch == L'\n') {
764 curs_set(FALSE);
765 return CONFIRM;
766 } else if (wch == L'\t') {
767 curs_set(FALSE);
768 return CANCEL;
769 } else if (wch == eraser) {
770 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
771 } else if (wch == killer) {
772 EDIT_CLEAR(rover.edit);
773 clear_message();
774 } else if (iswprint(wch)) {
775 if (!EDIT_FULL(rover.edit)) EDIT_INSERT(rover.edit, wch);
778 /* Encode edit contents in INPUT. */
779 rover.edit.buffer[rover.edit.left] = L'\0';
780 length = wcstombs(INPUT, rover.edit.buffer, BUFLEN);
781 wcstombs(&INPUT[length], &rover.edit.buffer[rover.edit.right+1],
782 BUFLEN-length);
783 return CONTINUE;
786 /* Update line input on the screen. */
787 static void
788 update_input(const char *prompt, Color color)
790 int plen, ilen, maxlen;
792 plen = strlen(prompt);
793 ilen = mbstowcs(NULL, INPUT, 0);
794 maxlen = STATUSPOS - plen - 2;
795 if (ilen - rover.edit_scroll < maxlen)
796 rover.edit_scroll = MAX(ilen - maxlen, 0);
797 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
798 rover.edit_scroll = rover.edit.left - maxlen;
799 else if (rover.edit.left < rover.edit_scroll)
800 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
801 color_set(RVC_PROMPT, NULL);
802 mvaddstr(LINES - 1, 0, prompt);
803 color_set(color, NULL);
804 mbstowcs(WBUF, INPUT, COLS);
805 mvaddnwstr(LINES - 1, plen, &WBUF[rover.edit_scroll], maxlen);
806 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
807 color_set(DEFAULT, NULL);
808 if (rover.edit_scroll)
809 mvaddch(LINES - 1, plen - 1, '<');
810 if (ilen > rover.edit_scroll + maxlen)
811 mvaddch(LINES - 1, plen + maxlen, '>');
812 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
816 main(int argc, char *argv[])
818 int i, ch;
819 char *program;
820 const char *key;
821 DIR *d;
822 EditStat edit_stat;
823 FILE *save_cwd_file = NULL;
825 if (argc >= 2) {
826 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
827 printf("rover %s\n", RV_VERSION);
828 return 0;
829 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
830 printf(
831 "Usage: rover [-s|--save-cwd FILE] [DIR [DIR [DIR [...]]]]\n"
832 " Browse current directory or the ones specified.\n"
833 " If FILE is given, write last visited path to it.\n\n"
834 " or: rover -h|--help\n"
835 " Print this help message and exit.\n\n"
836 " or: rover -v|--version\n"
837 " Print program version and exit.\n\n"
838 "See rover(1) for more information.\n\n"
839 "Rover homepage: <https://github.com/lecram/rover>.\n"
841 return 0;
842 } else if (!strcmp(argv[1], "-s") || !strcmp(argv[1], "--save-cwd")) {
843 if (argc > 2) {
844 save_cwd_file = fopen(argv[2], "w");
845 argc -= 2; argv += 2;
846 } else {
847 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
848 return 1;
852 init_term();
853 rover.nfiles = 0;
854 for (i = 0; i < 10; i++) {
855 rover.tabs[i].esel = rover.tabs[i].scroll = 0;
856 rover.tabs[i].flags = SHOW_FILES | SHOW_DIRS;
858 strcpy(rover.tabs[0].cwd, getenv("HOME"));
859 for (i = 1; i < argc && i < 10; i++) {
860 if ((d = opendir(argv[i]))) {
861 realpath(argv[i], rover.tabs[i].cwd);
862 closedir(d);
863 } else
864 strcpy(rover.tabs[i].cwd, rover.tabs[0].cwd);
866 getcwd(rover.tabs[i].cwd, PATH_MAX);
867 for (i++; i < 10; i++)
868 strcpy(rover.tabs[i].cwd, rover.tabs[i-1].cwd);
869 for (i = 0; i < 10; i++)
870 if (rover.tabs[i].cwd[strlen(rover.tabs[i].cwd) - 1] != '/')
871 strcat(rover.tabs[i].cwd, "/");
872 rover.tab = 1;
873 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
874 init_marks(&rover.marks);
875 cd(1);
876 while (1) {
877 ch = rover_getch();
878 key = keyname(ch);
879 clear_message();
880 if (!strcmp(key, RVK_QUIT)) break;
881 else if (ch >= '0' && ch <= '9') {
882 rover.tab = ch - '0';
883 cd(0);
884 } else if (!strcmp(key, RVK_HELP)) {
885 ARGS[0] = "man";
886 ARGS[1] = "rover";
887 ARGS[2] = NULL;
888 spawn();
889 } else if (!strcmp(key, RVK_DOWN)) {
890 if (!rover.nfiles) continue;
891 ESEL = MIN(ESEL + 1, rover.nfiles - 1);
892 update_view();
893 } else if (!strcmp(key, RVK_UP)) {
894 if (!rover.nfiles) continue;
895 ESEL = MAX(ESEL - 1, 0);
896 update_view();
897 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
898 if (!rover.nfiles) continue;
899 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
900 if (rover.nfiles > HEIGHT)
901 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
902 update_view();
903 } else if (!strcmp(key, RVK_JUMP_UP)) {
904 if (!rover.nfiles) continue;
905 ESEL = MAX(ESEL - RV_JUMP, 0);
906 SCROLL = MAX(SCROLL - RV_JUMP, 0);
907 update_view();
908 } else if (!strcmp(key, RVK_JUMP_TOP)) {
909 if (!rover.nfiles) continue;
910 ESEL = 0;
911 update_view();
912 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
913 if (!rover.nfiles) continue;
914 ESEL = rover.nfiles - 1;
915 update_view();
916 } else if (!strcmp(key, RVK_CD_DOWN)) {
917 if (!rover.nfiles || !S_ISDIR(EMODE(ESEL))) continue;
918 if (chdir(ENAME(ESEL)) == -1) {
919 message(RED, "Access denied.");
920 continue;
922 strcat(CWD, ENAME(ESEL));
923 cd(1);
924 } else if (!strcmp(key, RVK_CD_UP)) {
925 char *dirname, first;
926 if (!strcmp(CWD, "/")) continue;
927 CWD[strlen(CWD) - 1] = '\0';
928 dirname = strrchr(CWD, '/') + 1;
929 first = dirname[0];
930 dirname[0] = '\0';
931 cd(1);
932 dirname[0] = first;
933 dirname[strlen(dirname)] = '/';
934 try_to_sel(dirname);
935 dirname[0] = '\0';
936 update_view();
937 } else if (!strcmp(key, RVK_HOME)) {
938 strcpy(CWD, getenv("HOME"));
939 if (CWD[strlen(CWD) - 1] != '/')
940 strcat(CWD, "/");
941 cd(1);
942 } else if (!strcmp(key, RVK_REFRESH)) {
943 reload();
944 } else if (!strcmp(key, RVK_SHELL)) {
945 program = getenv("SHELL");
946 if (program) {
947 ARGS[0] = program;
948 ARGS[1] = NULL;
949 spawn();
950 reload();
952 } else if (!strcmp(key, RVK_VIEW)) {
953 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
954 program = getenv("PAGER");
955 if (program) {
956 ARGS[0] = program;
957 ARGS[1] = ENAME(ESEL);
958 ARGS[2] = NULL;
959 spawn();
961 } else if (!strcmp(key, RVK_EDIT)) {
962 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
963 program = getenv("EDITOR");
964 if (program) {
965 ARGS[0] = program;
966 ARGS[1] = ENAME(ESEL);
967 ARGS[2] = NULL;
968 spawn();
969 cd(0);
971 } else if (!strcmp(key, RVK_SEARCH)) {
972 int oldsel, oldscroll, length;
973 if (!rover.nfiles) continue;
974 oldsel = ESEL;
975 oldscroll = SCROLL;
976 start_line_edit("");
977 update_input(RVP_SEARCH, RED);
978 while ((edit_stat = get_line_edit()) == CONTINUE) {
979 int sel;
980 Color color = RED;
981 length = strlen(INPUT);
982 if (length) {
983 for (sel = 0; sel < rover.nfiles; sel++)
984 if (!strncmp(ENAME(sel), INPUT, length))
985 break;
986 if (sel < rover.nfiles) {
987 color = GREEN;
988 ESEL = sel;
989 if (rover.nfiles > HEIGHT) {
990 if (sel < 3)
991 SCROLL = 0;
992 else if (sel - 3 > rover.nfiles - HEIGHT)
993 SCROLL = rover.nfiles - HEIGHT;
994 else
995 SCROLL = sel - 3;
998 } else {
999 ESEL = oldsel;
1000 SCROLL = oldscroll;
1002 update_view();
1003 update_input(RVP_SEARCH, color);
1005 if (edit_stat == CANCEL) {
1006 ESEL = oldsel;
1007 SCROLL = oldscroll;
1009 clear_message();
1010 update_view();
1011 } else if (!strcmp(key, RVK_TG_FILES)) {
1012 FLAGS ^= SHOW_FILES;
1013 reload();
1014 } else if (!strcmp(key, RVK_TG_DIRS)) {
1015 FLAGS ^= SHOW_DIRS;
1016 reload();
1017 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
1018 FLAGS ^= SHOW_HIDDEN;
1019 reload();
1020 } else if (!strcmp(key, RVK_NEW_FILE)) {
1021 int ok = 0;
1022 start_line_edit("");
1023 update_input(RVP_NEW_FILE, RED);
1024 while ((edit_stat = get_line_edit()) == CONTINUE) {
1025 int length = strlen(INPUT);
1026 ok = length;
1027 for (i = 0; i < rover.nfiles; i++) {
1028 if (
1029 !strncmp(ENAME(i), INPUT, length) &&
1030 (!strcmp(ENAME(i) + length, "") ||
1031 !strcmp(ENAME(i) + length, "/"))
1033 ok = 0;
1034 break;
1037 update_input(RVP_NEW_FILE, ok ? GREEN : RED);
1039 clear_message();
1040 if (edit_stat == CONFIRM) {
1041 if (ok) {
1042 addfile(INPUT);
1043 cd(1);
1044 try_to_sel(INPUT);
1045 update_view();
1046 } else
1047 message(RED, "File already exists.");
1049 } else if (!strcmp(key, RVK_NEW_DIR)) {
1050 int ok = 0;
1051 start_line_edit("");
1052 update_input(RVP_NEW_DIR, RED);
1053 while ((edit_stat = get_line_edit()) == CONTINUE) {
1054 int length = strlen(INPUT);
1055 ok = length;
1056 for (i = 0; i < rover.nfiles; i++) {
1057 if (
1058 !strncmp(ENAME(i), INPUT, length) &&
1059 (!strcmp(ENAME(i) + length, "") ||
1060 !strcmp(ENAME(i) + length, "/"))
1062 ok = 0;
1063 break;
1066 update_input(RVP_NEW_DIR, ok ? GREEN : RED);
1068 clear_message();
1069 if (edit_stat == CONFIRM) {
1070 if (ok) {
1071 adddir(INPUT);
1072 cd(1);
1073 strcat(INPUT, "/");
1074 try_to_sel(INPUT);
1075 update_view();
1076 } else
1077 message(RED, "File already exists.");
1079 } else if (!strcmp(key, RVK_RENAME)) {
1080 int ok = 0;
1081 char *last;
1082 int isdir;
1083 strcpy(INPUT, ENAME(ESEL));
1084 last = INPUT + strlen(INPUT) - 1;
1085 if ((isdir = *last == '/'))
1086 *last = '\0';
1087 start_line_edit(INPUT);
1088 update_input(RVP_RENAME, RED);
1089 while ((edit_stat = get_line_edit()) == CONTINUE) {
1090 int length = strlen(INPUT);
1091 ok = length;
1092 for (i = 0; i < rover.nfiles; i++)
1093 if (
1094 !strncmp(ENAME(i), INPUT, length) &&
1095 (!strcmp(ENAME(i) + length, "") ||
1096 !strcmp(ENAME(i) + length, "/"))
1098 ok = 0;
1099 break;
1101 update_input(RVP_RENAME, ok ? GREEN : RED);
1103 clear_message();
1104 if (edit_stat == CONFIRM) {
1105 if (isdir)
1106 strcat(INPUT, "/");
1107 if (ok) {
1108 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1109 del_mark(&rover.marks, ENAME(ESEL));
1110 add_mark(&rover.marks, CWD, INPUT);
1112 cd(1);
1113 try_to_sel(INPUT);
1114 update_view();
1115 } else
1116 message(RED, "File already exists.");
1118 } else if (!strcmp(key, RVK_DELETE)) {
1119 if (rover.nfiles) {
1120 message(YELLOW, "Delete selected entry? (Y to confirm)");
1121 if (rover_getch() == 'Y') {
1122 const char *name = ENAME(ESEL);
1123 int ret = S_ISDIR(EMODE(ESEL)) ? deldir(name) : delfile(name);
1124 reload();
1125 if (ret)
1126 message(RED, "Could not delete entry.");
1127 } else
1128 clear_message();
1129 } else
1130 message(RED, "No entry selected for deletion.");
1131 } else if (!strcmp(key, RVK_TG_MARK)) {
1132 if (MARKED(ESEL))
1133 del_mark(&rover.marks, ENAME(ESEL));
1134 else
1135 add_mark(&rover.marks, CWD, ENAME(ESEL));
1136 MARKED(ESEL) = !MARKED(ESEL);
1137 ESEL = (ESEL + 1) % rover.nfiles;
1138 update_view();
1139 } else if (!strcmp(key, RVK_INVMARK)) {
1140 for (i = 0; i < rover.nfiles; i++) {
1141 if (MARKED(i))
1142 del_mark(&rover.marks, ENAME(i));
1143 else
1144 add_mark(&rover.marks, CWD, ENAME(i));
1145 MARKED(i) = !MARKED(i);
1147 update_view();
1148 } else if (!strcmp(key, RVK_MARKALL)) {
1149 for (i = 0; i < rover.nfiles; i++)
1150 if (!MARKED(i)) {
1151 add_mark(&rover.marks, CWD, ENAME(i));
1152 MARKED(i) = 1;
1154 update_view();
1155 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1156 if (rover.marks.nentries) {
1157 message(YELLOW, "Delete marked entries? (Y to confirm)");
1158 if (rover_getch() == 'Y')
1159 process_marked(NULL, delfile, deldir, "Deleting", "Deleted");
1160 else
1161 clear_message();
1162 } else
1163 message(RED, "No entries marked for deletion.");
1164 } else if (!strcmp(key, RVK_MARK_COPY)) {
1165 if (rover.marks.nentries)
1166 process_marked(adddir, cpyfile, NULL, "Copying", "Copied");
1167 else
1168 message(RED, "No entries marked for copying.");
1169 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1170 if (rover.marks.nentries)
1171 process_marked(adddir, movfile, deldir, "Moving", "Moved");
1172 else
1173 message(RED, "No entries marked for moving.");
1176 if (rover.nfiles)
1177 free_rows(&rover.rows, rover.nfiles);
1178 free_marks(&rover.marks);
1179 delwin(rover.window);
1180 if (save_cwd_file != NULL) {
1181 fputs(CWD, save_cwd_file);
1182 fclose(save_cwd_file);
1184 return 0;