Reorganize string buffers.
[rover.git] / rover.c
blob92cee602966ddb579499ce20c95544537dd361a2
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 BUFLEN 256
27 static char BUF1[BUFLEN];
28 static char BUF2[BUFLEN];
29 static char INPUT[BUFLEN];
30 static wchar_t WBUF[BUFLEN];
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[BUFLEN+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 < BUFLEN-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 = BUFLEN-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 int
271 rover_get_wch(wint_t *wch)
273 wint_t ret;
275 while ((ret = get_wch(wch)) == (wint_t) ERR)
276 sync_signals();
277 return ret;
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;
346 mvhline(0, 0, ' ', COLS);
347 attr_on(A_BOLD, NULL);
348 color_set(RVC_TABNUM, NULL);
349 mvaddch(0, COLS - 2, rover.tab + '0');
350 attr_off(A_BOLD, NULL);
351 if (rover.marks.nentries) {
352 numsize = snprintf(BUF1, BUFLEN, "%d", rover.marks.nentries);
353 color_set(RVC_MARKS, NULL);
354 mvaddstr(0, COLS - 3 - numsize, BUF1);
355 } else
356 numsize = -1;
357 color_set(RVC_CWD, NULL);
358 mbstowcs(WBUF, CWD, PATH_MAX);
359 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
360 wcolor_set(rover.window, RVC_BORDER, NULL);
361 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
362 /* Selection might not be visible, due to cursor wrapping or window
363 shrinking. In that case, the scroll must be moved to make it visible. */
364 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
365 marking = !strcmp(CWD, rover.marks.dirpath);
366 for (i = 0, j = SCROLL; i < HEIGHT && j < rover.nfiles; i++, j++) {
367 ishidden = ENAME(j)[0] == '.';
368 isdir = S_ISDIR(EMODE(j));
369 if (j == ESEL)
370 wattr_on(rover.window, A_REVERSE, NULL);
371 if (ISLINK(j))
372 wcolor_set(rover.window, RVC_LINK, NULL);
373 else if (ishidden)
374 wcolor_set(rover.window, RVC_HIDDEN, NULL);
375 else if (isdir)
376 wcolor_set(rover.window, RVC_DIR, NULL);
377 else
378 wcolor_set(rover.window, RVC_FILE, NULL);
379 if (!isdir) {
380 char *suffix, *suffixes = "BKMGTPEZY";
381 off_t human_size = ESIZE(j) * 10;
382 int length = mbstowcs(NULL, ENAME(j), 0);
383 for (suffix = suffixes; human_size >= 10240; suffix++)
384 human_size = (human_size + 512) / 1024;
385 if (*suffix == 'B')
386 swprintf(WBUF, PATH_MAX, L"%s%*d %c", ENAME(j),
387 (int) (COLS - length - 6),
388 (int) human_size / 10, *suffix);
389 else
390 swprintf(WBUF, PATH_MAX, L"%s%*d.%d %c", ENAME(j),
391 (int) (COLS - length - 8),
392 (int) human_size / 10, (int) human_size % 10, *suffix);
393 } else
394 mbstowcs(WBUF, ENAME(j), PATH_MAX);
395 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
396 mvwaddnwstr(rover.window, i + 1, 2, WBUF, COLS - 4);
397 if (marking && MARKED(j)) {
398 wcolor_set(rover.window, RVC_MARKS, NULL);
399 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
400 } else
401 mvwaddch(rover.window, i + 1, 1, ' ');
402 if (j == ESEL)
403 wattr_off(rover.window, A_REVERSE, NULL);
405 for (; i < HEIGHT; i++)
406 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
407 if (rover.nfiles > HEIGHT) {
408 int center, height;
409 center = (SCROLL + HEIGHT / 2) * HEIGHT / rover.nfiles;
410 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
411 if (!height) height = 1;
412 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
413 mvwvline(rover.window, center-height/2+1, COLS-1, RVS_SCROLLBAR, height);
415 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
416 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
417 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
418 if (!rover.nfiles)
419 strcpy(BUF2, "0/0");
420 else
421 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, rover.nfiles);
422 snprintf(BUF1+3, BUFLEN-3, "%12s", BUF2);
423 color_set(RVC_STATUS, NULL);
424 mvaddstr(LINES - 1, STATUSPOS, BUF1);
425 wrefresh(rover.window);
428 /* Show a message on the status bar. */
429 static void
430 message(const char *msg, Color color)
432 int len, pos;
434 len = strlen(msg);
435 pos = (STATUSPOS - len) / 2;
436 attr_on(A_BOLD, NULL);
437 color_set(color, NULL);
438 mvaddstr(LINES - 1, pos, msg);
439 color_set(DEFAULT, NULL);
440 attr_off(A_BOLD, NULL);
443 /* Clear message area, leaving only status info. */
444 static void
445 clear_message()
447 mvhline(LINES - 1, 0, ' ', STATUSPOS);
450 /* Comparison used to sort listing entries. */
451 static int
452 rowcmp(const void *a, const void *b)
454 int isdir1, isdir2, cmpdir;
455 const Row *r1 = a;
456 const Row *r2 = b;
457 isdir1 = S_ISDIR(r1->mode);
458 isdir2 = S_ISDIR(r2->mode);
459 cmpdir = isdir2 - isdir1;
460 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
463 /* Get all entries in current working directory. */
464 static int
465 ls(Row **rowsp, uint8_t flags)
467 DIR *dp;
468 struct dirent *ep;
469 struct stat statbuf;
470 Row *rows;
471 int i, n;
473 if(!(dp = opendir("."))) return -1;
474 n = -2; /* We don't want the entries "." and "..". */
475 while (readdir(dp)) n++;
476 rewinddir(dp);
477 rows = malloc(n * sizeof *rows);
478 i = 0;
479 while ((ep = readdir(dp))) {
480 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
481 continue;
482 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
483 continue;
484 lstat(ep->d_name, &statbuf);
485 rows[i].islink = S_ISLNK(statbuf.st_mode);
486 stat(ep->d_name, &statbuf);
487 if (S_ISDIR(statbuf.st_mode)) {
488 if (flags & SHOW_DIRS) {
489 rows[i].name = malloc(strlen(ep->d_name) + 2);
490 strcpy(rows[i].name, ep->d_name);
491 strcat(rows[i].name, "/");
492 rows[i].mode = statbuf.st_mode;
493 i++;
495 } else if (flags & SHOW_FILES) {
496 rows[i].name = malloc(strlen(ep->d_name) + 1);
497 strcpy(rows[i].name, ep->d_name);
498 rows[i].size = statbuf.st_size;
499 rows[i].mode = statbuf.st_mode;
500 i++;
503 n = i; /* Ignore unused space in array caused by filters. */
504 qsort(rows, n, sizeof (*rows), rowcmp);
505 closedir(dp);
506 *rowsp = rows;
507 return n;
510 static void
511 free_rows(Row **rowsp, int nfiles)
513 int i;
515 for (i = 0; i < nfiles; i++)
516 free((*rowsp)[i].name);
517 free(*rowsp);
518 *rowsp = NULL;
521 /* Change working directory to the path in CWD. */
522 static void
523 cd(int reset)
525 int i, j;
527 message("Loading...", CYAN);
528 refresh();
529 if (reset) ESEL = SCROLL = 0;
530 chdir(CWD);
531 if (rover.nfiles)
532 free_rows(&rover.rows, rover.nfiles);
533 rover.nfiles = ls(&rover.rows, FLAGS);
534 if (!strcmp(CWD, rover.marks.dirpath)) {
535 for (i = 0; i < rover.nfiles; i++) {
536 for (j = 0; j < rover.marks.bulk; j++)
537 if (
538 rover.marks.entries[j] &&
539 !strcmp(rover.marks.entries[j], ENAME(i))
541 break;
542 MARKED(i) = j < rover.marks.bulk;
544 } else
545 for (i = 0; i < rover.nfiles; i++)
546 MARKED(i) = 0;
547 clear_message();
548 update_view();
551 /* Select a target entry, if it is present. */
552 static void
553 try_to_sel(const char *target)
555 ESEL = 0;
556 if (!ISDIR(target))
557 while ((ESEL+1) < rover.nfiles && S_ISDIR(EMODE(ESEL)))
558 ESEL++;
559 while ((ESEL+1) < rover.nfiles && strcoll(ENAME(ESEL), target) < 0)
560 ESEL++;
561 if (rover.nfiles > HEIGHT) {
562 SCROLL = ESEL - HEIGHT / 2;
563 SCROLL = MIN(MAX(SCROLL, 0), rover.nfiles - HEIGHT);
567 /* Reload CWD, but try to keep selection. */
568 static void
569 reload()
571 if (rover.nfiles) {
572 strcpy(INPUT, ENAME(ESEL));
573 cd(1);
574 try_to_sel(INPUT);
575 update_view();
576 } else
577 cd(1);
580 /* Recursively process a source directory using CWD as destination root.
581 For each node (i.e. directory), do the following:
582 1. call pre(destination);
583 2. call proc() on every child leaf (i.e. files);
584 3. recurse into every child node;
585 4. call pos(source).
586 E.g. to move directory /src/ (and all its contents) inside /dst/:
587 strcpy(CWD, "/dst/");
588 process_dir(adddir, movfile, deldir, "/src/"); */
589 static int
590 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
592 int ret;
593 DIR *dp;
594 struct dirent *ep;
595 struct stat statbuf;
596 char subpath[PATH_MAX];
598 ret = 0;
599 if (pre) {
600 char dstpath[PATH_MAX];
601 strcpy(dstpath, CWD);
602 strcat(dstpath, path + strlen(rover.marks.dirpath));
603 ret |= pre(dstpath);
605 if(!(dp = opendir(path))) return -1;
606 while ((ep = readdir(dp))) {
607 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
608 continue;
609 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
610 stat(subpath, &statbuf);
611 if (S_ISDIR(statbuf.st_mode)) {
612 strcat(subpath, "/");
613 ret |= process_dir(pre, proc, pos, subpath);
614 } else
615 ret |= proc(subpath);
617 closedir(dp);
618 if (pos) ret |= pos(path);
619 return ret;
622 /* Process all marked entries using CWD as destination root.
623 All marked entries that are directories will be recursively processed.
624 See process_dir() for details on the parameters. */
625 static void
626 process_marked(PROCESS pre, PROCESS proc, PROCESS pos)
628 int i, ret;
629 char path[PATH_MAX];
631 clear_message();
632 message("Processing...", CYAN);
633 refresh();
634 for (i = 0; i < rover.marks.bulk; i++)
635 if (rover.marks.entries[i]) {
636 ret = 0;
637 snprintf(path, PATH_MAX, "%s%s", rover.marks.dirpath, rover.marks.entries[i]);
638 if (ISDIR(rover.marks.entries[i])) {
639 if (!strncmp(path, CWD, strlen(path)))
640 ret = -1;
641 else
642 ret = process_dir(pre, proc, pos, path);
643 } else
644 ret = proc(path);
645 if (!ret) del_mark(&rover.marks, rover.marks.entries[i]);
647 reload();
648 if (!rover.marks.nentries)
649 message("Done.", GREEN);
650 else
651 message("Some errors occured.", RED);
654 /* Wrappers for file operations. */
655 static PROCESS delfile = unlink;
656 static PROCESS deldir = rmdir;
657 static int addfile(const char *path) {
658 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
659 int ret;
661 ret = creat(path, 0644);
662 if (ret < 0) return ret;
663 return close(ret);
665 static int cpyfile(const char *srcpath) {
666 int src, dst, ret;
667 size_t size;
668 struct stat st;
669 char buf[BUFSIZ];
670 char dstpath[PATH_MAX];
672 ret = src = open(srcpath, O_RDONLY);
673 if (ret < 0) return ret;
674 ret = fstat(src, &st);
675 if (ret < 0) return ret;
676 strcpy(dstpath, CWD);
677 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
678 ret = dst = creat(dstpath, st.st_mode);
679 if (ret < 0) return ret;
680 while ((size = read(src, buf, BUFSIZ)) > 0) {
681 write(dst, buf, size);
682 sync_signals();
684 close(src);
685 close(dst);
686 return 0;
688 static int adddir(const char *path) {
689 int ret;
690 struct stat st;
692 ret = stat(CWD, &st);
693 if (ret < 0) return ret;
694 return mkdir(path, st.st_mode);
696 static int movfile(const char *srcpath) {
697 int ret;
698 char dstpath[PATH_MAX];
700 strcpy(dstpath, CWD);
701 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
702 ret = rename(srcpath, dstpath);
703 if (ret < 0 && errno == EXDEV) {
704 ret = cpyfile(srcpath);
705 if (ret < 0) return ret;
706 ret = delfile(srcpath);
708 return ret;
711 static void
712 start_line_edit(const char *init_input)
714 curs_set(TRUE);
715 strncpy(INPUT, init_input, BUFLEN);
716 rover.edit.left = mbstowcs(rover.edit.buffer, init_input, BUFLEN);
717 rover.edit.right = BUFLEN - 1;
718 rover.edit.buffer[BUFLEN] = L'\0';
719 rover.edit_scroll = 0;
722 /* Read input and change editing state accordingly. */
723 static EditStat
724 get_line_edit()
726 wchar_t eraser, killer, wch;
727 int ret, length;
729 ret = rover_get_wch((wint_t *) &wch);
730 erasewchar(&eraser);
731 killwchar(&killer);
732 if (ret == KEY_CODE_YES) {
733 if (wch == KEY_ENTER) {
734 curs_set(FALSE);
735 return CONFIRM;
736 } else if (wch == KEY_LEFT) {
737 if (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
738 } else if (wch == KEY_RIGHT) {
739 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
740 } else if (wch == KEY_UP) {
741 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
742 } else if (wch == KEY_DOWN) {
743 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
744 } else if (wch == KEY_BACKSPACE) {
745 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
746 } else if (wch == KEY_DC) {
747 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
749 } else {
750 if (wch == L'\r' || wch == L'\n') {
751 curs_set(FALSE);
752 return CONFIRM;
753 } else if (wch == L'\t') {
754 curs_set(FALSE);
755 return CANCEL;
756 } else if (wch == eraser) {
757 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
758 } else if (wch == killer) {
759 EDIT_CLEAR(rover.edit);
760 clear_message();
761 } else if (iswprint(wch)) {
762 if (!EDIT_FULL(rover.edit)) EDIT_INSERT(rover.edit, wch);
765 /* Encode edit contents in INPUT. */
766 rover.edit.buffer[rover.edit.left] = L'\0';
767 length = wcstombs(INPUT, rover.edit.buffer, BUFLEN);
768 wcstombs(&INPUT[length], &rover.edit.buffer[rover.edit.right+1],
769 BUFLEN-length);
770 return CONTINUE;
773 /* Update line input on the screen. */
774 static void
775 update_input(char *prompt, Color color)
777 int plen, ilen, maxlen;
779 plen = strlen(prompt);
780 ilen = mbstowcs(NULL, INPUT, 0);
781 maxlen = STATUSPOS - plen - 2;
782 if (ilen - rover.edit_scroll < maxlen)
783 rover.edit_scroll = MAX(ilen - maxlen, 0);
784 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
785 rover.edit_scroll = rover.edit.left - maxlen;
786 else if (rover.edit.left < rover.edit_scroll)
787 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
788 color_set(RVC_PROMPT, NULL);
789 mvaddstr(LINES - 1, 0, prompt);
790 color_set(color, NULL);
791 mbstowcs(WBUF, INPUT, COLS);
792 mvaddnwstr(LINES - 1, plen, &WBUF[rover.edit_scroll], maxlen);
793 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
794 color_set(DEFAULT, NULL);
795 if (rover.edit_scroll)
796 mvaddch(LINES - 1, plen - 1, '<');
797 if (ilen > rover.edit_scroll + maxlen)
798 mvaddch(LINES - 1, plen + maxlen, '>');
799 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
803 main(int argc, char *argv[])
805 int i, ch;
806 char *program;
807 const char *key;
808 DIR *d;
809 EditStat edit_stat;
810 const char *save_cwd_file = NULL;
812 if (argc >= 2) {
813 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
814 printf("rover %s\n", RV_VERSION);
815 return 0;
816 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
817 printf(
818 "Usage: rover [DIRECTORY [DIRECTORY [DIRECTORY [...]]]]\n"
819 " or: rover [OPTION]\n"
820 "Browse current working directory or the ones specified.\n\n"
821 "Options:\n"
822 " -h, --help print this help message and exit\n"
823 " -v, --version print program version and exit\n\n"
824 "See rover(1) for more information.\n\n"
825 "Rover homepage: <https://github.com/lecram/rover>.\n"
827 return 0;
828 } else if (argc > 2 && !strcmp(argv[1], "--save-cwd")) {
829 save_cwd_file = argv[2];
830 argc -= 2; argv += 2;
833 init_term();
834 rover.nfiles = 0;
835 for (i = 0; i < 10; i++) {
836 rover.esel[i] = rover.scroll[i] = 0;
837 rover.flags[i] = SHOW_FILES | SHOW_DIRS;
839 strcpy(rover.cwd[0], getenv("HOME"));
840 for (i = 1; i < argc && i < 10; i++) {
841 if ((d = opendir(argv[i]))) {
842 realpath(argv[i], rover.cwd[i]);
843 closedir(d);
844 } else
845 strcpy(rover.cwd[i], rover.cwd[0]);
847 getcwd(rover.cwd[i], PATH_MAX);
848 for (i++; i < 10; i++)
849 strcpy(rover.cwd[i], rover.cwd[i-1]);
850 for (i = 0; i < 10; i++)
851 if (rover.cwd[i][strlen(rover.cwd[i]) - 1] != '/')
852 strcat(rover.cwd[i], "/");
853 rover.tab = 1;
854 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
855 init_marks(&rover.marks);
856 cd(1);
857 while (1) {
858 ch = rover_getch();
859 key = keyname(ch);
860 clear_message();
861 if (!strcmp(key, RVK_QUIT)) break;
862 else if (ch >= '0' && ch <= '9') {
863 rover.tab = ch - '0';
864 cd(0);
865 } else if (!strcmp(key, RVK_HELP)) {
866 ARGS[0] = "man";
867 ARGS[1] = "rover";
868 ARGS[2] = NULL;
869 spawn();
870 } else if (!strcmp(key, RVK_DOWN)) {
871 if (!rover.nfiles) continue;
872 ESEL = (ESEL + 1) % rover.nfiles;
873 update_view();
874 } else if (!strcmp(key, RVK_UP)) {
875 if (!rover.nfiles) continue;
876 ESEL = ESEL ? ESEL - 1 : rover.nfiles - 1;
877 update_view();
878 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
879 if (!rover.nfiles) continue;
880 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
881 if (rover.nfiles > HEIGHT)
882 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
883 update_view();
884 } else if (!strcmp(key, RVK_JUMP_UP)) {
885 if (!rover.nfiles) continue;
886 ESEL = MAX(ESEL - RV_JUMP, 0);
887 SCROLL = MAX(SCROLL - RV_JUMP, 0);
888 update_view();
889 } else if (!strcmp(key, RVK_JUMP_TOP)) {
890 if (!rover.nfiles) continue;
891 ESEL = 0;
892 SCROLL = 0;
893 update_view();
894 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
895 if (!rover.nfiles) continue;
896 ESEL = rover.nfiles - 1;
897 SCROLL = MAX(rover.nfiles - 1 - HEIGHT, 0);
898 update_view();
899 } else if (!strcmp(key, RVK_CD_DOWN)) {
900 if (!rover.nfiles || !S_ISDIR(EMODE(ESEL))) continue;
901 strcat(CWD, ENAME(ESEL));
902 cd(1);
903 } else if (!strcmp(key, RVK_CD_UP)) {
904 char *dirname, first;
905 if (!strcmp(CWD, "/")) continue;
906 CWD[strlen(CWD) - 1] = '\0';
907 dirname = strrchr(CWD, '/') + 1;
908 first = dirname[0];
909 dirname[0] = '\0';
910 cd(1);
911 dirname[0] = first;
912 dirname[strlen(dirname)] = '/';
913 try_to_sel(dirname);
914 dirname[0] = '\0';
915 update_view();
916 } else if (!strcmp(key, RVK_HOME)) {
917 strcpy(CWD, getenv("HOME"));
918 if (CWD[strlen(CWD) - 1] != '/')
919 strcat(CWD, "/");
920 cd(1);
921 } else if (!strcmp(key, RVK_REFRESH)) {
922 reload();
923 } else if (!strcmp(key, RVK_SHELL)) {
924 program = getenv("SHELL");
925 if (program) {
926 ARGS[0] = program;
927 ARGS[1] = NULL;
928 spawn();
929 reload();
931 } else if (!strcmp(key, RVK_VIEW)) {
932 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
933 program = getenv("PAGER");
934 if (program) {
935 ARGS[0] = program;
936 ARGS[1] = ENAME(ESEL);
937 ARGS[2] = NULL;
938 spawn();
940 } else if (!strcmp(key, RVK_EDIT)) {
941 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
942 program = getenv("EDITOR");
943 if (program) {
944 ARGS[0] = program;
945 ARGS[1] = ENAME(ESEL);
946 ARGS[2] = NULL;
947 spawn();
948 cd(0);
950 } else if (!strcmp(key, RVK_SEARCH)) {
951 int oldsel, oldscroll, length;
952 char *prompt = "search: ";
953 if (!rover.nfiles) continue;
954 oldsel = ESEL;
955 oldscroll = SCROLL;
956 start_line_edit("");
957 update_input(prompt, DEFAULT);
958 while ((edit_stat = get_line_edit()) == CONTINUE) {
959 int sel;
960 Color color = RED;
961 length = strlen(INPUT);
962 if (length) {
963 for (sel = 0; sel < rover.nfiles; sel++)
964 if (!strncmp(ENAME(sel), INPUT, length))
965 break;
966 if (sel < rover.nfiles) {
967 color = GREEN;
968 ESEL = sel;
969 if (rover.nfiles > HEIGHT) {
970 if (sel < 3)
971 SCROLL = 0;
972 else if (sel - 3 > rover.nfiles - HEIGHT)
973 SCROLL = rover.nfiles - HEIGHT;
974 else
975 SCROLL = sel - 3;
978 } else {
979 ESEL = oldsel;
980 SCROLL = oldscroll;
982 update_view();
983 update_input(prompt, color);
985 if (edit_stat == CANCEL) {
986 ESEL = oldsel;
987 SCROLL = oldscroll;
989 clear_message();
990 update_view();
991 } else if (!strcmp(key, RVK_TG_FILES)) {
992 FLAGS ^= SHOW_FILES;
993 reload();
994 } else if (!strcmp(key, RVK_TG_DIRS)) {
995 FLAGS ^= SHOW_DIRS;
996 reload();
997 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
998 FLAGS ^= SHOW_HIDDEN;
999 reload();
1000 } else if (!strcmp(key, RVK_NEW_FILE)) {
1001 int ok = 0;
1002 char *prompt = "new file: ";
1003 start_line_edit("");
1004 update_input(prompt, DEFAULT);
1005 while ((edit_stat = get_line_edit()) == CONTINUE) {
1006 int length = strlen(INPUT);
1007 ok = 1;
1008 for (i = 0; i < rover.nfiles; i++) {
1009 if (
1010 !strncmp(ENAME(i), INPUT, length) &&
1011 (!strcmp(ENAME(i) + length, "") ||
1012 !strcmp(ENAME(i) + length, "/"))
1014 ok = 0;
1015 break;
1018 update_input(prompt, ok ? GREEN : RED);
1020 clear_message();
1021 if (edit_stat == CONFIRM && strlen(INPUT)) {
1022 if (ok) {
1023 addfile(INPUT);
1024 cd(1);
1025 try_to_sel(INPUT);
1026 update_view();
1027 } else
1028 message("File already exists.", RED);
1030 } else if (!strcmp(key, RVK_NEW_DIR)) {
1031 int ok = 0;
1032 char *prompt = "new directory: ";
1033 start_line_edit("");
1034 update_input(prompt, DEFAULT);
1035 while ((edit_stat = get_line_edit()) == CONTINUE) {
1036 int length = strlen(INPUT);
1037 ok = 1;
1038 for (i = 0; i < rover.nfiles; i++) {
1039 if (
1040 !strncmp(ENAME(i), INPUT, length) &&
1041 (!strcmp(ENAME(i) + length, "") ||
1042 !strcmp(ENAME(i) + length, "/"))
1044 ok = 0;
1045 break;
1048 update_input(prompt, ok ? GREEN : RED);
1050 clear_message();
1051 if (edit_stat == CONFIRM && strlen(INPUT)) {
1052 if (ok) {
1053 adddir(INPUT);
1054 cd(1);
1055 try_to_sel(INPUT);
1056 update_view();
1057 } else
1058 message("File already exists.", RED);
1060 } else if (!strcmp(key, RVK_RENAME)) {
1061 int ok = 0;
1062 char *prompt = "rename: ";
1063 char *last;
1064 int isdir;
1065 strcpy(INPUT, ENAME(ESEL));
1066 last = INPUT + strlen(INPUT) - 1;
1067 if ((isdir = *last == '/'))
1068 *last = '\0';
1069 start_line_edit(INPUT);
1070 update_input(prompt, RED);
1071 while ((edit_stat = get_line_edit()) == CONTINUE) {
1072 int length = strlen(INPUT);
1073 ok = 1;
1074 for (i = 0; i < rover.nfiles; i++)
1075 if (
1076 !strncmp(ENAME(i), INPUT, length) &&
1077 (!strcmp(ENAME(i) + length, "") ||
1078 !strcmp(ENAME(i) + length, "/"))
1080 ok = 0;
1081 break;
1083 update_input(prompt, ok ? GREEN : RED);
1085 clear_message();
1086 if (edit_stat == CONFIRM && strlen(INPUT)) {
1087 if (isdir)
1088 strcat(INPUT, "/");
1089 if (ok) {
1090 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1091 del_mark(&rover.marks, ENAME(ESEL));
1092 add_mark(&rover.marks, CWD, INPUT);
1094 cd(1);
1095 try_to_sel(INPUT);
1096 update_view();
1097 } else
1098 message("File already exists.", RED);
1100 } else if (!strcmp(key, RVK_DELETE)) {
1101 if (rover.nfiles) {
1102 message("Delete selected entry? (Y to confirm)", YELLOW);
1103 if (rover_getch() == 'Y') {
1104 const char *name = ENAME(ESEL);
1105 int ret = S_ISDIR(EMODE(ESEL)) ? deldir(name) : delfile(name);
1106 reload();
1107 if (ret)
1108 message("Could not delete entry.", RED);
1109 } else
1110 clear_message();
1111 } else
1112 message("No entry selected for deletion.", RED);
1113 } else if (!strcmp(key, RVK_TG_MARK)) {
1114 if (MARKED(ESEL))
1115 del_mark(&rover.marks, ENAME(ESEL));
1116 else
1117 add_mark(&rover.marks, CWD, ENAME(ESEL));
1118 MARKED(ESEL) = !MARKED(ESEL);
1119 ESEL = (ESEL + 1) % rover.nfiles;
1120 update_view();
1121 } else if (!strcmp(key, RVK_INVMARK)) {
1122 for (i = 0; i < rover.nfiles; i++) {
1123 if (MARKED(i))
1124 del_mark(&rover.marks, ENAME(i));
1125 else
1126 add_mark(&rover.marks, CWD, ENAME(i));
1127 MARKED(i) = !MARKED(i);
1129 update_view();
1130 } else if (!strcmp(key, RVK_MARKALL)) {
1131 for (i = 0; i < rover.nfiles; i++)
1132 if (!MARKED(i)) {
1133 add_mark(&rover.marks, CWD, ENAME(i));
1134 MARKED(i) = 1;
1136 update_view();
1137 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1138 if (rover.marks.nentries) {
1139 message("Delete marked entries? (Y to confirm)", YELLOW);
1140 if (rover_getch() == 'Y')
1141 process_marked(NULL, delfile, deldir);
1142 else
1143 clear_message();
1144 } else
1145 message("No entries marked for deletion.", RED);
1146 } else if (!strcmp(key, RVK_MARK_COPY)) {
1147 if (rover.marks.nentries)
1148 process_marked(adddir, cpyfile, NULL);
1149 else
1150 message("No entries marked for copying.", RED);
1151 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1152 if (rover.marks.nentries)
1153 process_marked(adddir, movfile, deldir);
1154 else
1155 message("No entries marked for moving.", RED);
1158 if (rover.nfiles)
1159 free_rows(&rover.rows, rover.nfiles);
1160 free_marks(&rover.marks);
1161 delwin(rover.window);
1162 if (save_cwd_file != NULL) {
1163 FILE *fd = fopen(save_cwd_file, "w");
1164 fputs(CWD, fd);
1165 fclose(fd);
1167 return 0;