Remove some unnecessary parentheses.
[rover.git] / rover.c
blob3f1fdbb322368e754a0ce15f25e6d8b57b4e71d6
1 #define _XOPEN_SOURCE_EXTENDED
2 #define _FILE_OFFSET_BITS 64
4 #include <stdlib.h>
5 #include <stdint.h>
6 #include <ctype.h>
7 #include <wchar.h>
8 #include <wctype.h>
9 #include <string.h>
10 #include <sys/types.h> /* pid_t, ... */
11 #include <stdio.h>
12 #include <limits.h> /* PATH_MAX */
13 #include <locale.h> /* setlocale(), LC_ALL */
14 #include <unistd.h> /* chdir(), getcwd(), read(), close(), ... */
15 #include <dirent.h> /* DIR, struct dirent, opendir(), ... */
16 #include <sys/stat.h>
17 #include <fcntl.h> /* open() */
18 #include <sys/wait.h> /* waitpid() */
19 #include <signal.h> /* struct sigaction, sigaction() */
20 #include <errno.h>
21 #include <curses.h>
23 #include "config.h"
25 /* String buffers. */
26 #define ROWSZ 256
27 static char ROW[ROWSZ];
28 #define STATUSSZ 256
29 static char STATUS[STATUSSZ];
30 #define INPUTSZ 256
31 static char INPUT[INPUTSZ];
33 /* Argument buffers for execvp(). */
34 #define MAXARGS 256
35 static char *ARGS[MAXARGS];
37 /* Listing view parameters. */
38 #define HEIGHT (LINES-4)
39 #define STATUSPOS (COLS-16)
41 /* Listing view flags. */
42 #define SHOW_FILES 0x01u
43 #define SHOW_DIRS 0x02u
44 #define SHOW_HIDDEN 0x04u
46 /* Marks parameters. */
47 #define BULK_INIT 5
48 #define BULK_THRESH 256
50 /* Information associated to each entry in listing. */
51 typedef struct Row {
52 char *name;
53 off_t size;
54 mode_t mode;
55 int islink;
56 int marked;
57 } Row;
59 /* Dynamic array of marked entries. */
60 typedef struct Marks {
61 char dirpath[PATH_MAX];
62 int bulk;
63 int nentries;
64 char **entries;
65 } Marks;
67 /* Line editing state. */
68 typedef struct Edit {
69 wchar_t buffer[INPUTSZ+1];
70 int left, right;
71 } Edit;
73 /* Global state. Some basic info is allocated for ten tabs. */
74 static struct Rover {
75 int tab;
76 int nfiles;
77 int scroll[10];
78 int esel[10];
79 uint8_t flags[10];
80 Row *rows;
81 WINDOW *window;
82 char cwd[10][PATH_MAX];
83 Marks marks;
84 Edit edit;
85 int edit_scroll;
86 volatile sig_atomic_t pending_winch;
87 } rover;
89 /* Macros for accessing global state. */
90 #define ENAME(I) rover.rows[I].name
91 #define ESIZE(I) rover.rows[I].size
92 #define EMODE(I) rover.rows[I].mode
93 #define ISLINK(I) rover.rows[I].islink
94 #define MARKED(I) rover.rows[I].marked
95 #define SCROLL rover.scroll[rover.tab]
96 #define ESEL rover.esel[rover.tab]
97 #define FLAGS rover.flags[rover.tab]
98 #define CWD rover.cwd[rover.tab]
100 /* Helpers. */
101 #define MIN(A, B) ((A) < (B) ? (A) : (B))
102 #define MAX(A, B) ((A) > (B) ? (A) : (B))
103 #define ISDIR(E) (strchr((E), '/') != NULL)
105 /* Line Editing Macros. */
106 #define EDIT_FULL(E) ((E).left == (E).right)
107 #define EDIT_CAN_LEFT(E) ((E).left)
108 #define EDIT_CAN_RIGHT(E) ((E).right < INPUTSZ-1)
109 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
110 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
111 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
112 #define EDIT_BACKSPACE(E) (E).left--
113 #define EDIT_DELETE(E) (E).right++
114 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = INPUTSZ-1; } while(0)
116 typedef enum EditStat {CONTINUE, CONFIRM, CANCEL} EditStat;
117 typedef enum Color {DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK} Color;
118 typedef int (*PROCESS)(const char *path);
120 static void
121 init_marks(Marks *marks)
123 strcpy(marks->dirpath, "");
124 marks->bulk = BULK_INIT;
125 marks->nentries = 0;
126 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
129 /* Unmark all entries. */
130 static void
131 mark_none(Marks *marks)
133 int i;
135 strcpy(marks->dirpath, "");
136 for (i = 0; i < marks->bulk && marks->nentries; i++)
137 if (marks->entries[i]) {
138 free(marks->entries[i]);
139 marks->entries[i] = NULL;
140 marks->nentries--;
142 if (marks->bulk > BULK_THRESH) {
143 /* Reset bulk to free some memory. */
144 free(marks->entries);
145 marks->bulk = BULK_INIT;
146 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
150 static void
151 add_mark(Marks *marks, char *dirpath, char *entry)
153 int i;
155 if (!strcmp(marks->dirpath, dirpath)) {
156 /* Append mark to directory. */
157 if (marks->nentries == marks->bulk) {
158 /* Expand bulk to accomodate new entry. */
159 int extra = marks->bulk / 2;
160 marks->bulk += extra; /* bulk *= 1.5; */
161 marks->entries = realloc(marks->entries,
162 marks->bulk * sizeof *marks->entries);
163 memset(&marks->entries[marks->nentries], 0,
164 extra * sizeof *marks->entries);
165 i = marks->nentries;
166 } else {
167 /* Search for empty slot (there must be one). */
168 for (i = 0; i < marks->bulk; i++)
169 if (!marks->entries[i])
170 break;
172 } else {
173 /* Directory changed. Discard old marks. */
174 mark_none(marks);
175 strcpy(marks->dirpath, dirpath);
176 i = 0;
178 marks->entries[i] = malloc(strlen(entry) + 1);
179 strcpy(marks->entries[i], entry);
180 marks->nentries++;
183 static void
184 del_mark(Marks *marks, char *entry)
186 int i;
188 if (marks->nentries > 1) {
189 for (i = 0; i < marks->bulk; i++)
190 if (marks->entries[i] && !strcmp(marks->entries[i], entry))
191 break;
192 free(marks->entries[i]);
193 marks->entries[i] = NULL;
194 marks->nentries--;
195 } else
196 mark_none(marks);
199 static void
200 free_marks(Marks *marks)
202 int i;
204 for (i = 0; i < marks->bulk && marks->nentries; i++)
205 if (marks->entries[i]) {
206 free(marks->entries[i]);
207 marks->nentries--;
209 free(marks->entries);
212 static void
213 handle_winch(int sig)
215 rover.pending_winch = 1;
218 static void
219 enable_handlers()
221 struct sigaction sa;
223 memset(&sa, 0, sizeof (struct sigaction));
224 sa.sa_handler = handle_winch;
225 sigaction(SIGWINCH, &sa, NULL);
228 static void
229 disable_handlers()
231 struct sigaction sa;
233 memset(&sa, 0, sizeof (struct sigaction));
234 sa.sa_handler = SIG_DFL;
235 sigaction(SIGWINCH, &sa, NULL);
238 static void update_view();
240 /* Handle any signals received since last call. */
241 static void
242 sync_signals()
244 if (rover.pending_winch) {
245 /* SIGWINCH received: resize application accordingly. */
246 delwin(rover.window);
247 endwin();
248 refresh();
249 clear();
250 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
251 SCROLL = MAX(ESEL - HEIGHT, 0);
252 update_view();
253 rover.pending_winch = 0;
257 /* This function must be used in place of getch().
258 It handles signals while waiting for user input. */
259 static int
260 rover_getch()
262 int ch;
264 while ((ch = getch()) == ERR)
265 sync_signals();
266 return ch;
269 /* This function must be used in place of get_wch().
270 It handles signals while waiting for user input. */
271 static int
272 rover_get_wch(wint_t *wch)
274 wint_t ret;
276 while ((ret = get_wch(wch)) == (wint_t) ERR)
277 sync_signals();
278 return ret;
281 /* Do a fork-exec to external program (e.g. $EDITOR). */
282 static void
283 spawn()
285 pid_t pid;
286 int status;
288 setenv("RVSEL", rover.nfiles ? ENAME(ESEL) : "", 1);
289 pid = fork();
290 if (pid > 0) {
291 /* fork() succeeded. */
292 disable_handlers();
293 endwin();
294 waitpid(pid, &status, 0);
295 enable_handlers();
296 kill(getpid(), SIGWINCH);
297 } else if (pid == 0) {
298 /* Child process. */
299 execvp(ARGS[0], ARGS);
303 /* Curses setup. */
304 static void
305 init_term()
307 setlocale(LC_ALL, "");
308 initscr();
309 cbreak(); /* Get one character at a time. */
310 timeout(100); /* For getch(). */
311 noecho();
312 nonl(); /* No NL->CR/NL on output. */
313 intrflush(stdscr, FALSE);
314 keypad(stdscr, TRUE);
315 curs_set(FALSE); /* Hide blinking cursor. */
316 if (has_colors()) {
317 short bg;
318 start_color();
319 #ifdef NCURSES_EXT_FUNCS
320 use_default_colors();
321 bg = -1;
322 #else
323 bg = COLOR_BLACK;
324 #endif
325 init_pair(RED, COLOR_RED, bg);
326 init_pair(GREEN, COLOR_GREEN, bg);
327 init_pair(YELLOW, COLOR_YELLOW, bg);
328 init_pair(BLUE, COLOR_BLUE, bg);
329 init_pair(CYAN, COLOR_CYAN, bg);
330 init_pair(MAGENTA, COLOR_MAGENTA, bg);
331 init_pair(WHITE, COLOR_WHITE, bg);
332 init_pair(BLACK, COLOR_BLACK, bg);
334 atexit((void (*)(void)) endwin);
335 enable_handlers();
338 /* Update the listing view. */
339 static void
340 update_view()
342 int i, j;
343 int numsize;
344 int ishidden, isdir;
345 int marking;
346 wchar_t wbuf[PATH_MAX];
348 mvhline(0, 0, ' ', COLS);
349 attr_on(A_BOLD, NULL);
350 color_set(RVC_TABNUM, NULL);
351 mvaddch(0, COLS - 2, rover.tab + '0');
352 attr_off(A_BOLD, NULL);
353 if (rover.marks.nentries) {
354 numsize = snprintf(STATUS, STATUSSZ, "%d", rover.marks.nentries);
355 color_set(RVC_MARKS, NULL);
356 mvaddstr(0, COLS - 3 - numsize, STATUS);
357 } else
358 numsize = -1;
359 color_set(RVC_CWD, NULL);
360 mbstowcs(wbuf, CWD, PATH_MAX);
361 mvaddnwstr(0, 0, wbuf, COLS - 4 - numsize);
362 wcolor_set(rover.window, RVC_BORDER, NULL);
363 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
364 /* Selection might not be visible, due to cursor wrapping or window
365 shrinking. In that case, the scroll must be moved to make it visible. */
366 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
367 marking = !strcmp(CWD, rover.marks.dirpath);
368 for (i = 0, j = SCROLL; i < HEIGHT && j < rover.nfiles; i++, j++) {
369 ishidden = ENAME(j)[0] == '.';
370 isdir = S_ISDIR(EMODE(j));
371 if (j == ESEL)
372 wattr_on(rover.window, A_REVERSE, NULL);
373 if (ISLINK(j))
374 wcolor_set(rover.window, RVC_LINK, NULL);
375 else if (ishidden)
376 wcolor_set(rover.window, RVC_HIDDEN, NULL);
377 else if (isdir)
378 wcolor_set(rover.window, RVC_DIR, NULL);
379 else
380 wcolor_set(rover.window, RVC_FILE, NULL);
381 if (!isdir) {
382 char *suffix, *suffixes = "BKMGTPEZY";
383 off_t human_size = ESIZE(j) * 10;
384 int length = mbstowcs(NULL, ENAME(j), 0);
385 for (suffix = suffixes; human_size >= 10240; suffix++)
386 human_size = (human_size + 512) / 1024;
387 if (*suffix == 'B')
388 swprintf(wbuf, PATH_MAX, L"%s%*d %c", ENAME(j),
389 (int) (COLS - length - 6),
390 (int) human_size / 10, *suffix);
391 else
392 swprintf(wbuf, PATH_MAX, L"%s%*d.%d %c", ENAME(j),
393 (int) (COLS - length - 8),
394 (int) human_size / 10, (int) human_size % 10, *suffix);
395 } else
396 mbstowcs(wbuf, ENAME(j), PATH_MAX);
397 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
398 mvwaddnwstr(rover.window, i + 1, 2, wbuf, COLS - 4);
399 if (marking && MARKED(j)) {
400 wcolor_set(rover.window, RVC_MARKS, NULL);
401 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
402 } else
403 mvwaddch(rover.window, i + 1, 1, ' ');
404 if (j == ESEL)
405 wattr_off(rover.window, A_REVERSE, NULL);
407 for (; i < HEIGHT; i++)
408 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
409 if (rover.nfiles > HEIGHT) {
410 int center, height;
411 center = (SCROLL + HEIGHT / 2) * HEIGHT / rover.nfiles;
412 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
413 if (!height) height = 1;
414 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
415 mvwvline(rover.window, center-height/2+1, COLS-1, RVS_SCROLLBAR, height);
417 STATUS[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
418 STATUS[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
419 STATUS[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
420 if (!rover.nfiles)
421 strcpy(ROW, "0/0");
422 else
423 snprintf(ROW, ROWSZ, "%d/%d", ESEL + 1, rover.nfiles);
424 snprintf(STATUS+3, STATUSSZ-3, "%12s", ROW);
425 color_set(RVC_STATUS, NULL);
426 mvaddstr(LINES - 1, STATUSPOS, STATUS);
427 wrefresh(rover.window);
430 /* Show a message on the status bar. */
431 static void
432 message(const char *msg, Color color)
434 int len, pos;
436 len = strlen(msg);
437 pos = (STATUSPOS - len) / 2;
438 attr_on(A_BOLD, NULL);
439 color_set(color, NULL);
440 mvaddstr(LINES - 1, pos, msg);
441 color_set(DEFAULT, NULL);
442 attr_off(A_BOLD, NULL);
445 /* Clear message area, leaving only status info. */
446 static void
447 clear_message()
449 mvhline(LINES - 1, 0, ' ', STATUSPOS);
452 /* Comparison used to sort listing entries. */
453 static int
454 rowcmp(const void *a, const void *b)
456 int isdir1, isdir2, cmpdir;
457 const Row *r1 = a;
458 const Row *r2 = b;
459 isdir1 = S_ISDIR(r1->mode);
460 isdir2 = S_ISDIR(r2->mode);
461 cmpdir = isdir2 - isdir1;
462 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
465 /* Get all entries in current working directory. */
466 static int
467 ls(Row **rowsp, uint8_t flags)
469 DIR *dp;
470 struct dirent *ep;
471 struct stat statbuf;
472 Row *rows;
473 int i, n;
475 if(!(dp = opendir("."))) return -1;
476 n = -2; /* We don't want the entries "." and "..". */
477 while (readdir(dp)) n++;
478 rewinddir(dp);
479 rows = malloc(n * sizeof *rows);
480 i = 0;
481 while ((ep = readdir(dp))) {
482 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
483 continue;
484 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
485 continue;
486 lstat(ep->d_name, &statbuf);
487 rows[i].islink = S_ISLNK(statbuf.st_mode);
488 stat(ep->d_name, &statbuf);
489 if (S_ISDIR(statbuf.st_mode)) {
490 if (flags & SHOW_DIRS) {
491 rows[i].name = malloc(strlen(ep->d_name) + 2);
492 strcpy(rows[i].name, ep->d_name);
493 strcat(rows[i].name, "/");
494 rows[i].mode = statbuf.st_mode;
495 i++;
497 } else if (flags & SHOW_FILES) {
498 rows[i].name = malloc(strlen(ep->d_name) + 1);
499 strcpy(rows[i].name, ep->d_name);
500 rows[i].size = statbuf.st_size;
501 rows[i].mode = statbuf.st_mode;
502 i++;
505 n = i; /* Ignore unused space in array caused by filters. */
506 qsort(rows, n, sizeof (*rows), rowcmp);
507 closedir(dp);
508 *rowsp = rows;
509 return n;
512 static void
513 free_rows(Row **rowsp, int nfiles)
515 int i;
517 for (i = 0; i < nfiles; i++)
518 free((*rowsp)[i].name);
519 free(*rowsp);
520 *rowsp = NULL;
523 /* Change working directory to the path in CWD. */
524 static void
525 cd(int reset)
527 int i, j;
529 message("Loading...", CYAN);
530 refresh();
531 if (reset) ESEL = SCROLL = 0;
532 chdir(CWD);
533 if (rover.nfiles)
534 free_rows(&rover.rows, rover.nfiles);
535 rover.nfiles = ls(&rover.rows, FLAGS);
536 if (!strcmp(CWD, rover.marks.dirpath)) {
537 for (i = 0; i < rover.nfiles; i++) {
538 for (j = 0; j < rover.marks.bulk; j++)
539 if (
540 rover.marks.entries[j] &&
541 !strcmp(rover.marks.entries[j], ENAME(i))
543 break;
544 MARKED(i) = j < rover.marks.bulk;
546 } else
547 for (i = 0; i < rover.nfiles; i++)
548 MARKED(i) = 0;
549 clear_message();
550 update_view();
553 /* Select a target entry, if it is present. */
554 static void
555 try_to_sel(const char *target)
557 ESEL = 0;
558 if (!ISDIR(target))
559 while ((ESEL+1) < rover.nfiles && S_ISDIR(EMODE(ESEL)))
560 ESEL++;
561 while ((ESEL+1) < rover.nfiles && strcoll(ENAME(ESEL), target) < 0)
562 ESEL++;
563 if (rover.nfiles > HEIGHT) {
564 SCROLL = ESEL - HEIGHT / 2;
565 SCROLL = MIN(MAX(SCROLL, 0), rover.nfiles - HEIGHT);
569 /* Reload CWD, but try to keep selection. */
570 static void
571 reload()
573 if (rover.nfiles) {
574 strcpy(INPUT, ENAME(ESEL));
575 cd(1);
576 try_to_sel(INPUT);
577 update_view();
578 } else
579 cd(1);
582 /* Recursively process a source directory using CWD as destination root.
583 For each node (i.e. directory), do the following:
584 1. call pre(destination);
585 2. call proc() on every child leaf (i.e. files);
586 3. recurse into every child node;
587 4. call pos(source).
588 E.g. to move directory /src/ (and all its contents) inside /dst/:
589 strcpy(CWD, "/dst/");
590 process_dir(adddir, movfile, deldir, "/src/"); */
591 static int
592 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
594 int ret;
595 DIR *dp;
596 struct dirent *ep;
597 struct stat statbuf;
598 char subpath[PATH_MAX];
600 ret = 0;
601 if (pre) {
602 char dstpath[PATH_MAX];
603 strcpy(dstpath, CWD);
604 strcat(dstpath, path + strlen(rover.marks.dirpath));
605 ret |= pre(dstpath);
607 if(!(dp = opendir(path))) return -1;
608 while ((ep = readdir(dp))) {
609 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
610 continue;
611 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
612 stat(subpath, &statbuf);
613 if (S_ISDIR(statbuf.st_mode)) {
614 strcat(subpath, "/");
615 ret |= process_dir(pre, proc, pos, subpath);
616 } else
617 ret |= proc(subpath);
619 closedir(dp);
620 if (pos) ret |= pos(path);
621 return ret;
624 /* Process all marked entries using CWD as destination root.
625 All marked entries that are directories will be recursively processed.
626 See process_dir() for details on the parameters. */
627 static void
628 process_marked(PROCESS pre, PROCESS proc, PROCESS pos)
630 int i, ret;
631 char path[PATH_MAX];
633 clear_message();
634 message("Processing...", CYAN);
635 refresh();
636 for (i = 0; i < rover.marks.bulk; i++)
637 if (rover.marks.entries[i]) {
638 ret = 0;
639 snprintf(path, PATH_MAX, "%s%s", rover.marks.dirpath, rover.marks.entries[i]);
640 if (ISDIR(rover.marks.entries[i])) {
641 if (!strncmp(path, CWD, strlen(path)))
642 ret = -1;
643 else
644 ret = process_dir(pre, proc, pos, path);
645 } else
646 ret = proc(path);
647 if (!ret) del_mark(&rover.marks, rover.marks.entries[i]);
649 reload();
650 if (!rover.marks.nentries)
651 message("Done.", GREEN);
652 else
653 message("Some errors occured.", RED);
656 /* Wrappers for file operations. */
657 static PROCESS delfile = unlink;
658 static PROCESS deldir = rmdir;
659 static int addfile(const char *path) {
660 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
661 int ret;
663 ret = creat(path, 0644);
664 if (ret < 0) return ret;
665 return close(ret);
667 static int cpyfile(const char *srcpath) {
668 int src, dst, ret;
669 size_t size;
670 struct stat st;
671 char buf[BUFSIZ];
672 char dstpath[PATH_MAX];
674 ret = src = open(srcpath, O_RDONLY);
675 if (ret < 0) return ret;
676 ret = fstat(src, &st);
677 if (ret < 0) return ret;
678 strcpy(dstpath, CWD);
679 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
680 ret = dst = creat(dstpath, st.st_mode);
681 if (ret < 0) return ret;
682 while ((size = read(src, buf, BUFSIZ)) > 0) {
683 write(dst, buf, size);
684 sync_signals();
686 close(src);
687 close(dst);
688 return 0;
690 static int adddir(const char *path) {
691 int ret;
692 struct stat st;
694 ret = stat(CWD, &st);
695 if (ret < 0) return ret;
696 return mkdir(path, st.st_mode);
698 static int movfile(const char *srcpath) {
699 int ret;
700 char dstpath[PATH_MAX];
702 strcpy(dstpath, CWD);
703 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
704 ret = rename(srcpath, dstpath);
705 if (ret < 0 && errno == EXDEV) {
706 ret = cpyfile(srcpath);
707 if (ret < 0) return ret;
708 ret = delfile(srcpath);
710 return ret;
713 static void
714 start_line_edit(const char *init_input)
716 curs_set(TRUE);
717 strncpy(INPUT, init_input, INPUTSZ);
718 rover.edit.left = mbstowcs(rover.edit.buffer, init_input, INPUTSZ);
719 rover.edit.right = INPUTSZ - 1;
720 rover.edit.buffer[INPUTSZ] = L'\0';
721 rover.edit_scroll = 0;
724 /* Read input and change editing state accordingly. */
725 static EditStat
726 get_line_edit()
728 wchar_t eraser, killer, wch;
729 int ret, length;
731 ret = rover_get_wch((wint_t *) &wch);
732 erasewchar(&eraser);
733 killwchar(&killer);
734 if (ret == KEY_CODE_YES) {
735 if (wch == KEY_ENTER) {
736 curs_set(FALSE);
737 return CONFIRM;
738 } else if (wch == KEY_LEFT) {
739 if (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
740 } else if (wch == KEY_RIGHT) {
741 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
742 } else if (wch == KEY_UP) {
743 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
744 } else if (wch == KEY_DOWN) {
745 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
746 } else if (wch == KEY_BACKSPACE) {
747 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
748 } else if (wch == KEY_DC) {
749 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
751 } else {
752 if (wch == L'\r' || wch == L'\n') {
753 curs_set(FALSE);
754 return CONFIRM;
755 } else if (wch == L'\t') {
756 curs_set(FALSE);
757 return CANCEL;
758 } else if (wch == eraser) {
759 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
760 } else if (wch == killer) {
761 EDIT_CLEAR(rover.edit);
762 clear_message();
763 } else if (iswprint(wch)) {
764 if (!EDIT_FULL(rover.edit)) EDIT_INSERT(rover.edit, wch);
767 /* Encode edit contents in INPUT. */
768 rover.edit.buffer[rover.edit.left] = L'\0';
769 length = wcstombs(INPUT, rover.edit.buffer, INPUTSZ);
770 wcstombs(&INPUT[length], &rover.edit.buffer[rover.edit.right+1],
771 INPUTSZ-length);
772 return CONTINUE;
775 /* Update line input on the screen. */
776 static void
777 update_input(char *prompt, Color color)
779 int plen, ilen, maxlen;
780 wchar_t wbuf[COLS];
782 plen = strlen(prompt);
783 ilen = mbstowcs(NULL, INPUT, 0);
784 maxlen = STATUSPOS - plen - 2;
785 if (ilen - rover.edit_scroll < maxlen)
786 rover.edit_scroll = MAX(ilen - maxlen, 0);
787 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
788 rover.edit_scroll = rover.edit.left - maxlen;
789 else if (rover.edit.left < rover.edit_scroll)
790 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
791 color_set(RVC_PROMPT, NULL);
792 mvaddstr(LINES - 1, 0, prompt);
793 color_set(color, NULL);
794 mbstowcs(wbuf, INPUT, COLS);
795 mvaddnwstr(LINES - 1, plen, &wbuf[rover.edit_scroll], maxlen);
796 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
797 color_set(DEFAULT, NULL);
798 if (rover.edit_scroll)
799 mvaddch(LINES - 1, plen - 1, '<');
800 if (ilen > rover.edit_scroll + maxlen)
801 mvaddch(LINES - 1, plen + maxlen, '>');
802 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
806 main(int argc, char *argv[])
808 int i, ch;
809 char *program;
810 const char *key;
811 DIR *d;
812 EditStat edit_stat;
813 const char *save_cwd_file = NULL;
815 if (argc >= 2) {
816 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
817 printf("rover %s\n", RV_VERSION);
818 return 0;
819 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
820 printf(
821 "Usage: rover [DIRECTORY [DIRECTORY [DIRECTORY [...]]]]\n"
822 " or: rover [OPTION]\n"
823 "Browse current working directory or the ones specified.\n\n"
824 "Options:\n"
825 " -h, --help print this help message and exit\n"
826 " -v, --version print program version and exit\n\n"
827 "See rover(1) for more information.\n\n"
828 "Rover homepage: <https://github.com/lecram/rover>.\n"
830 return 0;
831 } else if (argc > 2 && !strcmp(argv[1], "--save-cwd")) {
832 save_cwd_file = argv[2];
833 argc -= 2; argv += 2;
836 init_term();
837 rover.nfiles = 0;
838 for (i = 0; i < 10; i++) {
839 rover.esel[i] = rover.scroll[i] = 0;
840 rover.flags[i] = SHOW_FILES | SHOW_DIRS;
842 strcpy(rover.cwd[0], getenv("HOME"));
843 for (i = 1; i < argc && i < 10; i++) {
844 if ((d = opendir(argv[i]))) {
845 realpath(argv[i], rover.cwd[i]);
846 closedir(d);
847 } else
848 strcpy(rover.cwd[i], rover.cwd[0]);
850 getcwd(rover.cwd[i], PATH_MAX);
851 for (i++; i < 10; i++)
852 strcpy(rover.cwd[i], rover.cwd[i-1]);
853 for (i = 0; i < 10; i++)
854 if (rover.cwd[i][strlen(rover.cwd[i]) - 1] != '/')
855 strcat(rover.cwd[i], "/");
856 rover.tab = 1;
857 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
858 init_marks(&rover.marks);
859 cd(1);
860 while (1) {
861 ch = rover_getch();
862 key = keyname(ch);
863 clear_message();
864 if (!strcmp(key, RVK_QUIT)) break;
865 else if (ch >= '0' && ch <= '9') {
866 rover.tab = ch - '0';
867 cd(0);
868 } else if (!strcmp(key, RVK_HELP)) {
869 ARGS[0] = "man";
870 ARGS[1] = "rover";
871 ARGS[2] = NULL;
872 spawn();
873 } else if (!strcmp(key, RVK_DOWN)) {
874 if (!rover.nfiles) continue;
875 ESEL = (ESEL + 1) % rover.nfiles;
876 update_view();
877 } else if (!strcmp(key, RVK_UP)) {
878 if (!rover.nfiles) continue;
879 ESEL = ESEL ? ESEL - 1 : rover.nfiles - 1;
880 update_view();
881 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
882 if (!rover.nfiles) continue;
883 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
884 if (rover.nfiles > HEIGHT)
885 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
886 update_view();
887 } else if (!strcmp(key, RVK_JUMP_UP)) {
888 if (!rover.nfiles) continue;
889 ESEL = MAX(ESEL - RV_JUMP, 0);
890 SCROLL = MAX(SCROLL - RV_JUMP, 0);
891 update_view();
892 } else if (!strcmp(key, RVK_JUMP_TOP)) {
893 if (!rover.nfiles) continue;
894 ESEL = 0;
895 SCROLL = 0;
896 update_view();
897 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
898 if (!rover.nfiles) continue;
899 ESEL = rover.nfiles - 1;
900 SCROLL = MAX(rover.nfiles - 1 - HEIGHT, 0);
901 update_view();
902 } else if (!strcmp(key, RVK_CD_DOWN)) {
903 if (!rover.nfiles || !S_ISDIR(EMODE(ESEL))) continue;
904 strcat(CWD, ENAME(ESEL));
905 cd(1);
906 } else if (!strcmp(key, RVK_CD_UP)) {
907 char *dirname, first;
908 if (!strcmp(CWD, "/")) continue;
909 CWD[strlen(CWD) - 1] = '\0';
910 dirname = strrchr(CWD, '/') + 1;
911 first = dirname[0];
912 dirname[0] = '\0';
913 cd(1);
914 dirname[0] = first;
915 dirname[strlen(dirname)] = '/';
916 try_to_sel(dirname);
917 dirname[0] = '\0';
918 update_view();
919 } else if (!strcmp(key, RVK_HOME)) {
920 strcpy(CWD, getenv("HOME"));
921 if (CWD[strlen(CWD) - 1] != '/')
922 strcat(CWD, "/");
923 cd(1);
924 } else if (!strcmp(key, RVK_REFRESH)) {
925 reload();
926 } else if (!strcmp(key, RVK_SHELL)) {
927 program = getenv("SHELL");
928 if (program) {
929 ARGS[0] = program;
930 ARGS[1] = NULL;
931 spawn();
932 reload();
934 } else if (!strcmp(key, RVK_VIEW)) {
935 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
936 program = getenv("PAGER");
937 if (program) {
938 ARGS[0] = program;
939 ARGS[1] = ENAME(ESEL);
940 ARGS[2] = NULL;
941 spawn();
943 } else if (!strcmp(key, RVK_EDIT)) {
944 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
945 program = getenv("EDITOR");
946 if (program) {
947 ARGS[0] = program;
948 ARGS[1] = ENAME(ESEL);
949 ARGS[2] = NULL;
950 spawn();
951 cd(0);
953 } else if (!strcmp(key, RVK_SEARCH)) {
954 int oldsel, oldscroll, length;
955 char *prompt = "search: ";
956 if (!rover.nfiles) continue;
957 oldsel = ESEL;
958 oldscroll = SCROLL;
959 start_line_edit("");
960 update_input(prompt, DEFAULT);
961 while ((edit_stat = get_line_edit()) == CONTINUE) {
962 int sel;
963 Color color = RED;
964 length = strlen(INPUT);
965 if (length) {
966 for (sel = 0; sel < rover.nfiles; sel++)
967 if (!strncmp(ENAME(sel), INPUT, length))
968 break;
969 if (sel < rover.nfiles) {
970 color = GREEN;
971 ESEL = sel;
972 if (rover.nfiles > HEIGHT) {
973 if (sel < 3)
974 SCROLL = 0;
975 else if (sel - 3 > rover.nfiles - HEIGHT)
976 SCROLL = rover.nfiles - HEIGHT;
977 else
978 SCROLL = sel - 3;
981 } else {
982 ESEL = oldsel;
983 SCROLL = oldscroll;
985 update_view();
986 update_input(prompt, color);
988 if (edit_stat == CANCEL) {
989 ESEL = oldsel;
990 SCROLL = oldscroll;
992 clear_message();
993 update_view();
994 } else if (!strcmp(key, RVK_TG_FILES)) {
995 FLAGS ^= SHOW_FILES;
996 reload();
997 } else if (!strcmp(key, RVK_TG_DIRS)) {
998 FLAGS ^= SHOW_DIRS;
999 reload();
1000 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
1001 FLAGS ^= SHOW_HIDDEN;
1002 reload();
1003 } else if (!strcmp(key, RVK_NEW_FILE)) {
1004 int ok = 0;
1005 char *prompt = "new file: ";
1006 start_line_edit("");
1007 update_input(prompt, DEFAULT);
1008 while ((edit_stat = get_line_edit()) == CONTINUE) {
1009 int length = strlen(INPUT);
1010 ok = 1;
1011 for (i = 0; i < rover.nfiles; i++) {
1012 if (
1013 !strncmp(ENAME(i), INPUT, length) &&
1014 (!strcmp(ENAME(i) + length, "") ||
1015 !strcmp(ENAME(i) + length, "/"))
1017 ok = 0;
1018 break;
1021 update_input(prompt, ok ? GREEN : RED);
1023 clear_message();
1024 if (edit_stat == CONFIRM && strlen(INPUT)) {
1025 if (ok) {
1026 addfile(INPUT);
1027 cd(1);
1028 try_to_sel(INPUT);
1029 update_view();
1030 } else
1031 message("File already exists.", RED);
1033 } else if (!strcmp(key, RVK_NEW_DIR)) {
1034 int ok = 0;
1035 char *prompt = "new directory: ";
1036 start_line_edit("");
1037 update_input(prompt, DEFAULT);
1038 while ((edit_stat = get_line_edit()) == CONTINUE) {
1039 int length = strlen(INPUT);
1040 ok = 1;
1041 for (i = 0; i < rover.nfiles; i++) {
1042 if (
1043 !strncmp(ENAME(i), INPUT, length) &&
1044 (!strcmp(ENAME(i) + length, "") ||
1045 !strcmp(ENAME(i) + length, "/"))
1047 ok = 0;
1048 break;
1051 update_input(prompt, ok ? GREEN : RED);
1053 clear_message();
1054 if (edit_stat == CONFIRM && strlen(INPUT)) {
1055 if (ok) {
1056 adddir(INPUT);
1057 cd(1);
1058 try_to_sel(INPUT);
1059 update_view();
1060 } else
1061 message("File already exists.", RED);
1063 } else if (!strcmp(key, RVK_RENAME)) {
1064 int ok = 0;
1065 char *prompt = "rename: ";
1066 char *last;
1067 int isdir;
1068 strcpy(INPUT, ENAME(ESEL));
1069 last = INPUT + strlen(INPUT) - 1;
1070 if ((isdir = *last == '/'))
1071 *last = '\0';
1072 start_line_edit(INPUT);
1073 update_input(prompt, RED);
1074 while ((edit_stat = get_line_edit()) == CONTINUE) {
1075 int length = strlen(INPUT);
1076 ok = 1;
1077 for (i = 0; i < rover.nfiles; i++)
1078 if (
1079 !strncmp(ENAME(i), INPUT, length) &&
1080 (!strcmp(ENAME(i) + length, "") ||
1081 !strcmp(ENAME(i) + length, "/"))
1083 ok = 0;
1084 break;
1086 update_input(prompt, ok ? GREEN : RED);
1088 clear_message();
1089 if (edit_stat == CONFIRM && strlen(INPUT)) {
1090 if (isdir)
1091 strcat(INPUT, "/");
1092 if (ok) {
1093 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1094 del_mark(&rover.marks, ENAME(ESEL));
1095 add_mark(&rover.marks, CWD, INPUT);
1097 cd(1);
1098 try_to_sel(INPUT);
1099 update_view();
1100 } else
1101 message("File already exists.", RED);
1103 } else if (!strcmp(key, RVK_DELETE)) {
1104 if (rover.nfiles) {
1105 message("Delete selected entry? (Y to confirm)", YELLOW);
1106 if (rover_getch() == 'Y') {
1107 const char *name = ENAME(ESEL);
1108 int ret = S_ISDIR(EMODE(ESEL)) ? deldir(name) : delfile(name);
1109 reload();
1110 if (ret)
1111 message("Could not delete entry.", RED);
1112 } else
1113 clear_message();
1114 } else
1115 message("No entry selected for deletion.", RED);
1116 } else if (!strcmp(key, RVK_TG_MARK)) {
1117 if (MARKED(ESEL))
1118 del_mark(&rover.marks, ENAME(ESEL));
1119 else
1120 add_mark(&rover.marks, CWD, ENAME(ESEL));
1121 MARKED(ESEL) = !MARKED(ESEL);
1122 ESEL = (ESEL + 1) % rover.nfiles;
1123 update_view();
1124 } else if (!strcmp(key, RVK_INVMARK)) {
1125 for (i = 0; i < rover.nfiles; i++) {
1126 if (MARKED(i))
1127 del_mark(&rover.marks, ENAME(i));
1128 else
1129 add_mark(&rover.marks, CWD, ENAME(i));
1130 MARKED(i) = !MARKED(i);
1132 update_view();
1133 } else if (!strcmp(key, RVK_MARKALL)) {
1134 for (i = 0; i < rover.nfiles; i++)
1135 if (!MARKED(i)) {
1136 add_mark(&rover.marks, CWD, ENAME(i));
1137 MARKED(i) = 1;
1139 update_view();
1140 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1141 if (rover.marks.nentries) {
1142 message("Delete marked entries? (Y to confirm)", YELLOW);
1143 if (rover_getch() == 'Y')
1144 process_marked(NULL, delfile, deldir);
1145 else
1146 clear_message();
1147 } else
1148 message("No entries marked for deletion.", RED);
1149 } else if (!strcmp(key, RVK_MARK_COPY)) {
1150 if (rover.marks.nentries)
1151 process_marked(adddir, cpyfile, NULL);
1152 else
1153 message("No entries marked for copying.", RED);
1154 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1155 if (rover.marks.nentries)
1156 process_marked(adddir, movfile, deldir);
1157 else
1158 message("No entries marked for moving.", RED);
1161 if (rover.nfiles)
1162 free_rows(&rover.rows, rover.nfiles);
1163 free_marks(&rover.marks);
1164 delwin(rover.window);
1165 if (save_cwd_file != NULL) {
1166 FILE *fd = fopen(save_cwd_file, "w");
1167 fputs(CWD, fd);
1168 fclose(fd);
1170 return 0;