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