Blob


1 #define _XOPEN_SOURCE 700
2 #define _XOPEN_SOURCE_EXTENDED
3 #define _FILE_OFFSET_BITS 64
5 #include <stdlib.h>
6 #include <stdint.h>
7 #include <ctype.h>
8 #include <wchar.h>
9 #include <wctype.h>
10 #include <string.h>
11 #include <sys/types.h> /* pid_t, ... */
12 #include <stdio.h>
13 #include <limits.h> /* PATH_MAX */
14 #include <locale.h> /* setlocale(), LC_ALL */
15 #include <unistd.h> /* chdir(), getcwd(), read(), close(), ... */
16 #include <dirent.h> /* DIR, struct dirent, opendir(), ... */
17 #include <sys/stat.h>
18 #include <fcntl.h> /* open() */
19 #include <sys/wait.h> /* waitpid() */
20 #include <signal.h> /* struct sigaction, sigaction() */
21 #include <errno.h>
22 #include <curses.h>
24 #include "config.h"
26 /* String buffers. */
27 #define BUFLEN PATH_MAX
28 static char BUF1[BUFLEN];
29 static char BUF2[BUFLEN];
30 static char INPUT[BUFLEN];
31 static wchar_t WBUF[BUFLEN];
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[BUFLEN+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 < BUFLEN-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 = BUFLEN-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 if (HEIGHT < rover.nfiles && SCROLL + HEIGHT > rover.nfiles)
252 SCROLL = ESEL - HEIGHT;
253 update_view();
254 rover.pending_winch = 0;
258 /* This function must be used in place of getch().
259 It handles signals while waiting for user input. */
260 static int
261 rover_getch()
263 int ch;
265 while ((ch = getch()) == ERR)
266 sync_signals();
267 return ch;
270 /* This function must be used in place of get_wch().
271 It handles signals while waiting for user input. */
272 static int
273 rover_get_wch(wint_t *wch)
275 wint_t ret;
277 while ((ret = get_wch(wch)) == (wint_t) ERR)
278 sync_signals();
279 return ret;
282 /* Do a fork-exec to external program (e.g. $EDITOR). */
283 static void
284 spawn()
286 pid_t pid;
287 int status;
289 setenv("RVSEL", rover.nfiles ? ENAME(ESEL) : "", 1);
290 pid = fork();
291 if (pid > 0) {
292 /* fork() succeeded. */
293 disable_handlers();
294 endwin();
295 waitpid(pid, &status, 0);
296 enable_handlers();
297 kill(getpid(), SIGWINCH);
298 } else if (pid == 0) {
299 /* Child process. */
300 execvp(ARGS[0], ARGS);
304 /* Curses setup. */
305 static void
306 init_term()
308 setlocale(LC_ALL, "");
309 initscr();
310 cbreak(); /* Get one character at a time. */
311 timeout(100); /* For getch(). */
312 noecho();
313 nonl(); /* No NL->CR/NL on output. */
314 intrflush(stdscr, FALSE);
315 keypad(stdscr, TRUE);
316 curs_set(FALSE); /* Hide blinking cursor. */
317 if (has_colors()) {
318 short bg;
319 start_color();
320 #ifdef NCURSES_EXT_FUNCS
321 use_default_colors();
322 bg = -1;
323 #else
324 bg = COLOR_BLACK;
325 #endif
326 init_pair(RED, COLOR_RED, bg);
327 init_pair(GREEN, COLOR_GREEN, bg);
328 init_pair(YELLOW, COLOR_YELLOW, bg);
329 init_pair(BLUE, COLOR_BLUE, bg);
330 init_pair(CYAN, COLOR_CYAN, bg);
331 init_pair(MAGENTA, COLOR_MAGENTA, bg);
332 init_pair(WHITE, COLOR_WHITE, bg);
333 init_pair(BLACK, COLOR_BLACK, bg);
335 atexit((void (*)(void)) endwin);
336 enable_handlers();
339 /* Update the listing view. */
340 static void
341 update_view()
343 int i, j;
344 int numsize;
345 int ishidden, isdir;
346 int marking;
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(BUF1, BUFLEN, "%d", rover.marks.nentries);
355 color_set(RVC_MARKS, NULL);
356 mvaddstr(0, COLS - 3 - numsize, BUF1);
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 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
418 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
419 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
420 if (!rover.nfiles)
421 strcpy(BUF2, "0/0");
422 else
423 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, rover.nfiles);
424 snprintf(BUF1+3, BUFLEN-3, "%12s", BUF2);
425 color_set(RVC_STATUS, NULL);
426 mvaddstr(LINES - 1, STATUSPOS, BUF1);
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, BUFLEN);
718 rover.edit.left = mbstowcs(rover.edit.buffer, init_input, BUFLEN);
719 rover.edit.right = BUFLEN - 1;
720 rover.edit.buffer[BUFLEN] = 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, BUFLEN);
770 wcstombs(&INPUT[length], &rover.edit.buffer[rover.edit.right+1],
771 BUFLEN-length);
772 return CONTINUE;
775 /* Update line input on the screen. */
776 static void
777 update_input(const char *prompt, Color color)
779 int plen, ilen, maxlen;
781 plen = strlen(prompt);
782 ilen = mbstowcs(NULL, INPUT, 0);
783 maxlen = STATUSPOS - plen - 2;
784 if (ilen - rover.edit_scroll < maxlen)
785 rover.edit_scroll = MAX(ilen - maxlen, 0);
786 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
787 rover.edit_scroll = rover.edit.left - maxlen;
788 else if (rover.edit.left < rover.edit_scroll)
789 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
790 color_set(RVC_PROMPT, NULL);
791 mvaddstr(LINES - 1, 0, prompt);
792 color_set(color, NULL);
793 mbstowcs(WBUF, INPUT, COLS);
794 mvaddnwstr(LINES - 1, plen, &WBUF[rover.edit_scroll], maxlen);
795 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
796 color_set(DEFAULT, NULL);
797 if (rover.edit_scroll)
798 mvaddch(LINES - 1, plen - 1, '<');
799 if (ilen > rover.edit_scroll + maxlen)
800 mvaddch(LINES - 1, plen + maxlen, '>');
801 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
804 int
805 main(int argc, char *argv[])
807 int i, ch;
808 char *program;
809 const char *key;
810 DIR *d;
811 EditStat edit_stat;
812 FILE *save_cwd_file = NULL;
814 if (argc >= 2) {
815 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
816 printf("rover %s\n", RV_VERSION);
817 return 0;
818 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
819 printf(
820 "Usage: rover [-s|--save-cwd FILE] [DIR [DIR [DIR [...]]]]\n"
821 " Browse current directory or the ones specified.\n"
822 " If FILE is given, write last visited path to it.\n\n"
823 " or: rover -h|--help\n"
824 " Print this help message and exit.\n\n"
825 " or: rover -v|--version\n"
826 " 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"
829 );
830 return 0;
831 } else if (!strcmp(argv[1], "-s") || !strcmp(argv[1], "--save-cwd")) {
832 if (argc > 2) {
833 save_cwd_file = fopen(argv[2], "w");
834 argc -= 2; argv += 2;
835 } else {
836 fprintf(stderr, "error: missing argument to %s\n", argv[1]);
837 return 1;
841 init_term();
842 rover.nfiles = 0;
843 for (i = 0; i < 10; i++) {
844 rover.esel[i] = rover.scroll[i] = 0;
845 rover.flags[i] = SHOW_FILES | SHOW_DIRS;
847 strcpy(rover.cwd[0], getenv("HOME"));
848 for (i = 1; i < argc && i < 10; i++) {
849 if ((d = opendir(argv[i]))) {
850 realpath(argv[i], rover.cwd[i]);
851 closedir(d);
852 } else
853 strcpy(rover.cwd[i], rover.cwd[0]);
855 getcwd(rover.cwd[i], PATH_MAX);
856 for (i++; i < 10; i++)
857 strcpy(rover.cwd[i], rover.cwd[i-1]);
858 for (i = 0; i < 10; i++)
859 if (rover.cwd[i][strlen(rover.cwd[i]) - 1] != '/')
860 strcat(rover.cwd[i], "/");
861 rover.tab = 1;
862 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
863 init_marks(&rover.marks);
864 cd(1);
865 while (1) {
866 ch = rover_getch();
867 key = keyname(ch);
868 clear_message();
869 if (!strcmp(key, RVK_QUIT)) break;
870 else if (ch >= '0' && ch <= '9') {
871 rover.tab = ch - '0';
872 cd(0);
873 } else if (!strcmp(key, RVK_HELP)) {
874 ARGS[0] = "man";
875 ARGS[1] = "rover";
876 ARGS[2] = NULL;
877 spawn();
878 } else if (!strcmp(key, RVK_DOWN)) {
879 if (!rover.nfiles) continue;
880 ESEL = MIN(ESEL + 1, rover.nfiles - 1);
881 update_view();
882 } else if (!strcmp(key, RVK_UP)) {
883 if (!rover.nfiles) continue;
884 ESEL = MAX(ESEL - 1, 0);
885 update_view();
886 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
887 if (!rover.nfiles) continue;
888 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
889 if (rover.nfiles > HEIGHT)
890 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
891 update_view();
892 } else if (!strcmp(key, RVK_JUMP_UP)) {
893 if (!rover.nfiles) continue;
894 ESEL = MAX(ESEL - RV_JUMP, 0);
895 SCROLL = MAX(SCROLL - RV_JUMP, 0);
896 update_view();
897 } else if (!strcmp(key, RVK_JUMP_TOP)) {
898 if (!rover.nfiles) continue;
899 ESEL = 0;
900 update_view();
901 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
902 if (!rover.nfiles) continue;
903 ESEL = rover.nfiles - 1;
904 update_view();
905 } else if (!strcmp(key, RVK_CD_DOWN)) {
906 if (!rover.nfiles || !S_ISDIR(EMODE(ESEL))) continue;
907 strcat(CWD, ENAME(ESEL));
908 cd(1);
909 } else if (!strcmp(key, RVK_CD_UP)) {
910 char *dirname, first;
911 if (!strcmp(CWD, "/")) continue;
912 CWD[strlen(CWD) - 1] = '\0';
913 dirname = strrchr(CWD, '/') + 1;
914 first = dirname[0];
915 dirname[0] = '\0';
916 cd(1);
917 dirname[0] = first;
918 dirname[strlen(dirname)] = '/';
919 try_to_sel(dirname);
920 dirname[0] = '\0';
921 update_view();
922 } else if (!strcmp(key, RVK_HOME)) {
923 strcpy(CWD, getenv("HOME"));
924 if (CWD[strlen(CWD) - 1] != '/')
925 strcat(CWD, "/");
926 cd(1);
927 } else if (!strcmp(key, RVK_REFRESH)) {
928 reload();
929 } else if (!strcmp(key, RVK_SHELL)) {
930 program = getenv("SHELL");
931 if (program) {
932 ARGS[0] = program;
933 ARGS[1] = NULL;
934 spawn();
935 reload();
937 } else if (!strcmp(key, RVK_VIEW)) {
938 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
939 program = getenv("PAGER");
940 if (program) {
941 ARGS[0] = program;
942 ARGS[1] = ENAME(ESEL);
943 ARGS[2] = NULL;
944 spawn();
946 } else if (!strcmp(key, RVK_EDIT)) {
947 if (!rover.nfiles || S_ISDIR(EMODE(ESEL))) continue;
948 program = getenv("EDITOR");
949 if (program) {
950 ARGS[0] = program;
951 ARGS[1] = ENAME(ESEL);
952 ARGS[2] = NULL;
953 spawn();
954 cd(0);
956 } else if (!strcmp(key, RVK_SEARCH)) {
957 int oldsel, oldscroll, length;
958 if (!rover.nfiles) continue;
959 oldsel = ESEL;
960 oldscroll = SCROLL;
961 start_line_edit("");
962 update_input(RVP_SEARCH, RED);
963 while ((edit_stat = get_line_edit()) == CONTINUE) {
964 int sel;
965 Color color = RED;
966 length = strlen(INPUT);
967 if (length) {
968 for (sel = 0; sel < rover.nfiles; sel++)
969 if (!strncmp(ENAME(sel), INPUT, length))
970 break;
971 if (sel < rover.nfiles) {
972 color = GREEN;
973 ESEL = sel;
974 if (rover.nfiles > HEIGHT) {
975 if (sel < 3)
976 SCROLL = 0;
977 else if (sel - 3 > rover.nfiles - HEIGHT)
978 SCROLL = rover.nfiles - HEIGHT;
979 else
980 SCROLL = sel - 3;
983 } else {
984 ESEL = oldsel;
985 SCROLL = oldscroll;
987 update_view();
988 update_input(RVP_SEARCH, color);
990 if (edit_stat == CANCEL) {
991 ESEL = oldsel;
992 SCROLL = oldscroll;
994 clear_message();
995 update_view();
996 } else if (!strcmp(key, RVK_TG_FILES)) {
997 FLAGS ^= SHOW_FILES;
998 reload();
999 } else if (!strcmp(key, RVK_TG_DIRS)) {
1000 FLAGS ^= SHOW_DIRS;
1001 reload();
1002 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
1003 FLAGS ^= SHOW_HIDDEN;
1004 reload();
1005 } else if (!strcmp(key, RVK_NEW_FILE)) {
1006 int ok = 0;
1007 start_line_edit("");
1008 update_input(RVP_NEW_FILE, RED);
1009 while ((edit_stat = get_line_edit()) == CONTINUE) {
1010 int length = strlen(INPUT);
1011 ok = length;
1012 for (i = 0; i < rover.nfiles; i++) {
1013 if (
1014 !strncmp(ENAME(i), INPUT, length) &&
1015 (!strcmp(ENAME(i) + length, "") ||
1016 !strcmp(ENAME(i) + length, "/"))
1017 ) {
1018 ok = 0;
1019 break;
1022 update_input(RVP_NEW_FILE, ok ? GREEN : RED);
1024 clear_message();
1025 if (edit_stat == CONFIRM) {
1026 if (ok) {
1027 addfile(INPUT);
1028 cd(1);
1029 try_to_sel(INPUT);
1030 update_view();
1031 } else
1032 message("File already exists.", RED);
1034 } else if (!strcmp(key, RVK_NEW_DIR)) {
1035 int ok = 0;
1036 start_line_edit("");
1037 update_input(RVP_NEW_DIR, RED);
1038 while ((edit_stat = get_line_edit()) == CONTINUE) {
1039 int length = strlen(INPUT);
1040 ok = length;
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, "/"))
1046 ) {
1047 ok = 0;
1048 break;
1051 update_input(RVP_NEW_DIR, ok ? GREEN : RED);
1053 clear_message();
1054 if (edit_stat == CONFIRM) {
1055 if (ok) {
1056 adddir(INPUT);
1057 cd(1);
1058 strcat(INPUT, "/");
1059 try_to_sel(INPUT);
1060 update_view();
1061 } else
1062 message("File already exists.", RED);
1064 } else if (!strcmp(key, RVK_RENAME)) {
1065 int ok = 0;
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(RVP_RENAME, RED);
1074 while ((edit_stat = get_line_edit()) == CONTINUE) {
1075 int length = strlen(INPUT);
1076 ok = length;
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, "/"))
1082 ) {
1083 ok = 0;
1084 break;
1086 update_input(RVP_RENAME, ok ? GREEN : RED);
1088 clear_message();
1089 if (edit_stat == CONFIRM) {
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 fputs(CWD, save_cwd_file);
1167 fclose(save_cwd_file);
1169 return 0;