Blob


1 #include <stdlib.h>
2 #include <stdint.h>
3 #include <ctype.h>
4 #include <string.h>
5 #include <sys/types.h> /* pid_t, ... */
6 #include <stdio.h>
7 #include <limits.h> /* PATH_MAX */
8 #include <locale.h> /* setlocale(), LC_ALL */
9 #include <unistd.h> /* chdir(), getcwd(), read(), close(), ... */
10 #include <dirent.h> /* DIR, struct dirent, opendir(), ... */
11 #include <sys/stat.h>
12 #include <fcntl.h> /* open() */
13 #include <sys/wait.h> /* waitpid() */
14 #include <signal.h> /* struct sigaction, sigaction() */
15 #include <errno.h>
16 #include <curses.h>
18 #include "config.h"
20 /* String buffers. */
21 #define ROWSZ 256
22 static char ROW[ROWSZ];
23 #define STATUSSZ 256
24 static char STATUS[STATUSSZ];
25 #define INPUTSZ 256
26 static char INPUT[INPUTSZ];
28 /* Argument buffers for execvp(). */
29 #define MAXARGS 256
30 static char *ARGS[MAXARGS];
32 /* Listing view parameters. */
33 #define HEIGHT (LINES-4)
34 #define STATUSPOS (COLS-16)
36 /* Listing view flags. */
37 #define SHOW_FILES 0x01u
38 #define SHOW_DIRS 0x02u
39 #define SHOW_HIDDEN 0x04u
41 /* Marks parameters. */
42 #define BULK_INIT 5
43 #define BULK_THRESH 256
45 /* Information associated to each entry in listing. */
46 typedef struct Row {
47 char *name;
48 off_t size;
49 int marked;
50 } Row;
52 /* Dynamic array of marked entries. */
53 typedef struct Marks {
54 char dirpath[PATH_MAX];
55 int bulk;
56 int nentries;
57 char **entries;
58 } Marks;
60 /* Line editing state. */
61 typedef struct Edit {
62 char buffer[INPUTSZ-1];
63 int left, right;
64 } Edit;
66 /* Global state. Some basic info is allocated for ten tabs. */
67 static struct Rover {
68 int tab;
69 int nfiles;
70 int scroll[10];
71 int esel[10];
72 uint8_t flags[10];
73 Row *rows;
74 WINDOW *window;
75 char cwd[10][PATH_MAX];
76 Marks marks;
77 Edit edit;
78 int edit_scroll;
79 } rover;
81 /* Macros for accessing global state. */
82 #define ENAME(I) rover.rows[I].name
83 #define ESIZE(I) rover.rows[I].size
84 #define MARKED(I) rover.rows[I].marked
85 #define SCROLL rover.scroll[rover.tab]
86 #define ESEL rover.esel[rover.tab]
87 #define FLAGS rover.flags[rover.tab]
88 #define CWD rover.cwd[rover.tab]
90 /* Helpers. */
91 #define MIN(A, B) ((A) < (B) ? (A) : (B))
92 #define MAX(A, B) ((A) > (B) ? (A) : (B))
93 #define ISDIR(E) (strchr((E), '/') != NULL)
95 /* Line Editing Macros. */
96 #define EDIT_FULL(E) ((E).left == (E).right)
97 #define EDIT_CAN_LEFT(E) ((E).left)
98 #define EDIT_CAN_RIGHT(E) ((E).right < INPUTSZ-1)
99 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
100 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
101 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
102 #define EDIT_BACKSPACE(E) (E).left--
103 #define EDIT_DELETE(E) (E).right++
104 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = INPUTSZ-1; } while(0)
106 typedef enum EditStat {CONTINUE, CONFIRM, CANCEL} EditStat;
107 typedef enum Color {DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE} Color;
108 typedef int (*PROCESS)(const char *path);
110 static void
111 init_marks(Marks *marks)
113 strcpy(marks->dirpath, "");
114 marks->bulk = BULK_INIT;
115 marks->nentries = 0;
116 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
119 /* Unmark all entries. */
120 static void
121 mark_none(Marks *marks)
123 int i;
125 strcpy(marks->dirpath, "");
126 for (i = 0; i < marks->bulk && marks->nentries; i++)
127 if (marks->entries[i]) {
128 free(marks->entries[i]);
129 marks->entries[i] = NULL;
130 marks->nentries--;
132 if (marks->bulk > BULK_THRESH) {
133 /* Reset bulk to free some memory. */
134 free(marks->entries);
135 marks->bulk = BULK_INIT;
136 marks->entries = calloc(marks->bulk, sizeof *marks->entries);
140 static void
141 add_mark(Marks *marks, char *dirpath, char *entry)
143 int i;
145 if (!strcmp(marks->dirpath, dirpath)) {
146 /* Append mark to directory. */
147 if (marks->nentries == marks->bulk) {
148 /* Expand bulk to accomodate new entry. */
149 int extra = marks->bulk / 2;
150 marks->bulk += extra; /* bulk *= 1.5; */
151 marks->entries = realloc(marks->entries,
152 marks->bulk * sizeof *marks->entries);
153 memset(&marks->entries[marks->nentries], 0,
154 extra * sizeof *marks->entries);
155 i = marks->nentries;
156 } else {
157 /* Search for empty slot (there must be one). */
158 for (i = 0; i < marks->bulk; i++)
159 if (!marks->entries[i])
160 break;
162 } else {
163 /* Directory changed. Discard old marks. */
164 mark_none(marks);
165 strcpy(marks->dirpath, dirpath);
166 i = 0;
168 marks->entries[i] = malloc(strlen(entry) + 1);
169 strcpy(marks->entries[i], entry);
170 marks->nentries++;
173 static void
174 del_mark(Marks *marks, char *entry)
176 int i;
178 if (marks->nentries > 1) {
179 for (i = 0; i < marks->bulk; i++)
180 if (marks->entries[i] && !strcmp(marks->entries[i], entry))
181 break;
182 free(marks->entries[i]);
183 marks->entries[i] = NULL;
184 marks->nentries--;
185 } else
186 mark_none(marks);
189 static void
190 free_marks(Marks *marks)
192 int i;
194 for (i = 0; i < marks->bulk && marks->nentries; i++)
195 if (marks->entries[i]) {
196 free(marks->entries[i]);
197 marks->nentries--;
199 free(marks->entries);
202 static void update_view();
204 /* SIGSEGV handler: clean up curses before exiting. */
205 static void
206 handle_segv(int sig)
208 (void) sig;
209 endwin();
210 fprintf(stderr, "Received SIGSEGV (segmentation fault).\n");
211 exit(1);
214 /* SIGWINCH handler: resize application according to new terminal settings. */
215 static void
216 handle_winch(int sig)
218 (void) sig;
219 delwin(rover.window);
220 endwin();
221 refresh();
222 clear();
223 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
224 update_view();
227 static void
228 enable_handlers()
230 struct sigaction sa;
232 memset(&sa, 0, sizeof (struct sigaction));
233 sa.sa_handler = handle_segv;
234 sigaction(SIGSEGV, &sa, NULL);
235 sa.sa_handler = handle_winch;
236 sigaction(SIGWINCH, &sa, NULL);
239 static void
240 disable_handlers()
242 struct sigaction sa;
244 memset(&sa, 0, sizeof (struct sigaction));
245 sa.sa_handler = SIG_DFL;
246 sigaction(SIGSEGV, &sa, NULL);
247 sigaction(SIGWINCH, &sa, NULL);
250 /* Do a fork-exec to external program (e.g. $EDITOR). */
251 static void
252 spawn()
254 pid_t pid;
255 int status;
257 setenv("RVSEL", rover.nfiles ? ENAME(ESEL) : "", 1);
258 pid = fork();
259 if (pid > 0) {
260 /* fork() succeeded. */
261 disable_handlers();
262 endwin();
263 waitpid(pid, &status, 0);
264 enable_handlers();
265 kill(getpid(), SIGWINCH);
266 } else if (pid == 0) {
267 /* Child process. */
268 execvp(ARGS[0], ARGS);
272 /* Curses setup. */
273 static void
274 init_term()
276 setlocale(LC_ALL, "");
277 initscr();
278 cbreak(); /* Get one character at a time. */
279 noecho();
280 nonl(); /* No NL->CR/NL on output. */
281 intrflush(stdscr, FALSE);
282 keypad(stdscr, TRUE);
283 curs_set(FALSE); /* Hide blinking cursor. */
284 if (has_colors()) {
285 short bg;
286 start_color();
287 #ifdef NCURSES_EXT_FUNCS
288 use_default_colors();
289 bg = -1;
290 #else
291 bg = COLOR_BLACK;
292 #endif
293 init_pair(RED, COLOR_RED, bg);
294 init_pair(GREEN, COLOR_GREEN, bg);
295 init_pair(YELLOW, COLOR_YELLOW, bg);
296 init_pair(BLUE, COLOR_BLUE, bg);
297 init_pair(CYAN, COLOR_CYAN, bg);
298 init_pair(MAGENTA, COLOR_MAGENTA, bg);
299 init_pair(WHITE, COLOR_WHITE, bg);
301 atexit((void (*)(void)) endwin);
302 enable_handlers();
305 /* Update the listing view. */
306 static void
307 update_view()
309 int i, j;
310 int numsize;
311 int ishidden, isdir;
312 int marking;
314 mvhline(0, 0, ' ', COLS);
315 attr_on(A_BOLD, NULL);
316 color_set(RVC_TABNUM, NULL);
317 mvaddch(0, COLS - 2, rover.tab + '0');
318 color_set(DEFAULT, NULL);
319 attr_off(A_BOLD, NULL);
320 if (rover.marks.nentries) {
321 numsize = snprintf(STATUS, STATUSSZ, "%d", rover.marks.nentries);
322 color_set(RVC_NMARKS, NULL);
323 mvaddstr(0, COLS - 3 - numsize, STATUS);
324 color_set(DEFAULT, NULL);
325 } else
326 numsize = -1;
327 color_set(RVC_CWD, NULL);
328 mvaddnstr(0, 0, CWD, COLS - 4 - numsize);
329 color_set(DEFAULT, NULL);
330 wcolor_set(rover.window, RVC_BORDER, NULL);
331 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
332 wcolor_set(rover.window, DEFAULT, NULL);
333 /* Selection might not be visible, due to cursor wrapping or window
334 shrinking. In that case, the scroll must be moved to make it visible. */
335 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
336 marking = !strcmp(CWD, rover.marks.dirpath);
337 for (i = 0, j = SCROLL; i < HEIGHT && j < rover.nfiles; i++, j++) {
338 ishidden = ENAME(j)[0] == '.';
339 isdir = ISDIR(ENAME(j));
340 if (j == ESEL)
341 wattr_on(rover.window, A_REVERSE, NULL);
342 if (ishidden)
343 wcolor_set(rover.window, RVC_HIDDEN, NULL);
344 else if (isdir)
345 wcolor_set(rover.window, RVC_DIR, NULL);
346 else
347 wcolor_set(rover.window, RVC_FILE, NULL);
348 if (!isdir) {
349 char *suffix, *suffixes = "BKMGTPEZY";
350 off_t human_size = ESIZE(j) * 10;
351 for (suffix = suffixes; human_size >= 10240; suffix++)
352 human_size = (human_size + 512) / 1024;
353 if (*suffix == 'B')
354 snprintf(ROW, ROWSZ, "%s%*d %c", ENAME(j),
355 (int) (COLS - strlen(ENAME(j)) - 6),
356 (int) human_size / 10, *suffix);
357 else
358 snprintf(ROW, ROWSZ, "%s%*d.%d %c", ENAME(j),
359 (int) (COLS - strlen(ENAME(j)) - 8),
360 (int) human_size / 10, (int) human_size % 10, *suffix);
361 } else
362 strcpy(ROW, ENAME(j));
363 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
364 if (marking && MARKED(j))
365 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
366 else
367 mvwaddch(rover.window, i + 1, 1, ' ');
368 mvwaddnstr(rover.window, i + 1, 2, ROW, COLS - 4);
369 wcolor_set(rover.window, DEFAULT, NULL);
370 if (j == ESEL)
371 wattr_off(rover.window, A_REVERSE, NULL);
373 for (;i < HEIGHT; i++)
374 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
375 if (rover.nfiles > HEIGHT) {
376 int center, height;
377 center = (SCROLL + (HEIGHT / 2)) * HEIGHT / rover.nfiles;
378 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
379 if (!height) height = 1;
380 wcolor_set(rover.window, RVC_BORDER, NULL);
381 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
382 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
383 mvwvline(rover.window, center-(height/2)+1, COLS-1, RVS_SCROLLBAR, height);
384 wcolor_set(rover.window, DEFAULT, NULL);
386 STATUS[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
387 STATUS[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
388 STATUS[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
389 if (!rover.nfiles)
390 strcpy(ROW, "0/0");
391 else
392 snprintf(ROW, ROWSZ, "%d/%d", ESEL + 1, rover.nfiles);
393 snprintf(STATUS+3, STATUSSZ-3, "%12s", ROW);
394 color_set(RVC_STATUS, NULL);
395 mvaddstr(LINES - 1, STATUSPOS, STATUS);
396 color_set(DEFAULT, NULL);
397 wrefresh(rover.window);
400 /* Show a message on the status bar. */
401 static void
402 message(const char *msg, Color color)
404 int len, pos;
406 len = strlen(msg);
407 pos = (STATUSPOS - len) / 2;
408 attr_on(A_BOLD, NULL);
409 color_set(color, NULL);
410 mvaddstr(LINES - 1, pos, msg);
411 color_set(DEFAULT, NULL);
412 attr_off(A_BOLD, NULL);
415 /* Clear message area, leaving only status info. */
416 static void
417 clear_message()
419 mvhline(LINES - 1, 0, ' ', STATUSPOS);
422 /* Comparison used to sort listing entries. */
423 static int
424 rowcmp(const void *a, const void *b)
426 int isdir1, isdir2, cmpdir;
427 const Row *r1 = a;
428 const Row *r2 = b;
429 isdir1 = ISDIR(r1->name);
430 isdir2 = ISDIR(r2->name);
431 cmpdir = isdir2 - isdir1;
432 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
435 /* Get all entries in current working directory. */
436 static int
437 ls(Row **rowsp, uint8_t flags)
439 DIR *dp;
440 struct dirent *ep;
441 struct stat statbuf;
442 Row *rows;
443 int i, n;
445 if(!(dp = opendir("."))) return -1;
446 n = -2; /* We don't want the entries "." and "..". */
447 while (readdir(dp)) n++;
448 rewinddir(dp);
449 rows = malloc(n * sizeof *rows);
450 i = 0;
451 while ((ep = readdir(dp))) {
452 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
453 continue;
454 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
455 continue;
456 lstat(ep->d_name, &statbuf);
457 if (S_ISDIR(statbuf.st_mode)) {
458 if (flags & SHOW_DIRS) {
459 rows[i].name = malloc(strlen(ep->d_name) + 2);
460 strcpy(rows[i].name, ep->d_name);
461 strcat(rows[i].name, "/");
462 i++;
464 } else if (flags & SHOW_FILES) {
465 rows[i].name = malloc(strlen(ep->d_name) + 1);
466 strcpy(rows[i].name, ep->d_name);
467 rows[i].size = statbuf.st_size;
468 i++;
471 n = i; /* Ignore unused space in array caused by filters. */
472 qsort(rows, n, sizeof (*rows), rowcmp);
473 closedir(dp);
474 *rowsp = rows;
475 return n;
478 static void
479 free_rows(Row **rowsp, int nfiles)
481 int i;
483 for (i = 0; i < nfiles; i++)
484 free((*rowsp)[i].name);
485 free(*rowsp);
486 *rowsp = NULL;
489 /* Change working directory to the path in CWD. */
490 static void
491 cd(int reset)
493 int i, j;
495 message("Loading...", CYAN);
496 refresh();
497 if (reset) ESEL = SCROLL = 0;
498 chdir(CWD);
499 if (rover.nfiles)
500 free_rows(&rover.rows, rover.nfiles);
501 rover.nfiles = ls(&rover.rows, FLAGS);
502 if (!strcmp(CWD, rover.marks.dirpath)) {
503 for (i = 0; i < rover.nfiles; i++) {
504 for (j = 0; j < rover.marks.bulk; j++)
505 if (
506 rover.marks.entries[j] &&
507 !strcmp(rover.marks.entries[j], ENAME(i))
509 break;
510 MARKED(i) = j < rover.marks.bulk;
512 } else
513 for (i = 0; i < rover.nfiles; i++)
514 MARKED(i) = 0;
515 clear_message();
516 update_view();
519 /* Select a target entry, if it is present. */
520 static void
521 try_to_sel(const char *target)
523 ESEL = 0;
524 if (!ISDIR(target))
525 while ((ESEL+1) < rover.nfiles && ISDIR(ENAME(ESEL)))
526 ESEL++;
527 while ((ESEL+1) < rover.nfiles && strcoll(ENAME(ESEL), target) < 0)
528 ESEL++;
529 if (rover.nfiles > HEIGHT) {
530 SCROLL = ESEL - (HEIGHT / 2);
531 SCROLL = MIN(MAX(SCROLL, 0), rover.nfiles - HEIGHT);
535 /* Reload CWD, but try to keep selection. */
536 static void
537 reload()
539 if (rover.nfiles) {
540 strcpy(INPUT, ENAME(ESEL));
541 cd(1);
542 try_to_sel(INPUT);
543 update_view();
544 } else
545 cd(1);
548 /* Recursively process a source directory using CWD as destination root.
549 For each node (i.e. directory), do the following:
550 1. call pre(destination);
551 2. call proc() on every child leaf (i.e. files);
552 3. recurse into every child node;
553 4. call pos(source).
554 E.g. to move directory /src/ (and all its contents) inside /dst/:
555 strcpy(CWD, "/dst/");
556 process_dir(adddir, movfile, deldir, "/src/"); */
557 static int
558 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
560 int ret;
561 DIR *dp;
562 struct dirent *ep;
563 struct stat statbuf;
564 char subpath[PATH_MAX];
566 ret = 0;
567 if (pre) {
568 char dstpath[PATH_MAX];
569 strcpy(dstpath, CWD);
570 strcat(dstpath, path + strlen(rover.marks.dirpath));
571 ret |= pre(dstpath);
573 if(!(dp = opendir(path))) return -1;
574 while ((ep = readdir(dp))) {
575 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
576 continue;
577 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
578 stat(subpath, &statbuf);
579 if (S_ISDIR(statbuf.st_mode)) {
580 strcat(subpath, "/");
581 ret |= process_dir(pre, proc, pos, subpath);
582 } else
583 ret |= proc(subpath);
585 closedir(dp);
586 if (pos) ret |= pos(path);
587 return ret;
590 /* Process all marked entries using CWD as destination root.
591 All marked entries that are directories will be recursively processed.
592 See process_dir() for details on the parameters. */
593 static void
594 process_marked(PROCESS pre, PROCESS proc, PROCESS pos)
596 int i, ret;
597 char path[PATH_MAX];
599 clear_message();
600 message("Processing...", CYAN);
601 refresh();
602 for (i = 0; i < rover.marks.bulk; i++)
603 if (rover.marks.entries[i]) {
604 ret = 0;
605 snprintf(path, PATH_MAX, "%s%s", rover.marks.dirpath, rover.marks.entries[i]);
606 if (ISDIR(rover.marks.entries[i])) {
607 if (!strncmp(path, CWD, strlen(path)))
608 ret = -1;
609 else
610 ret = process_dir(pre, proc, pos, path);
611 } else
612 ret = proc(path);
613 if (!ret) del_mark(&rover.marks, rover.marks.entries[i]);
615 reload();
616 if (!rover.marks.nentries)
617 message("Done.", GREEN);
618 else
619 message("Some errors occured.", RED);
622 /* Wrappers for file operations. */
623 static PROCESS delfile = unlink;
624 static PROCESS deldir = rmdir;
625 static int addfile(const char *path) {
626 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
627 int ret;
629 ret = creat(path, 0644);
630 if (ret < 0) return ret;
631 return close(ret);
633 static int cpyfile(const char *srcpath) {
634 int src, dst, ret;
635 size_t size;
636 struct stat st;
637 char buf[BUFSIZ];
638 char dstpath[PATH_MAX];
640 ret = src = open(srcpath, O_RDONLY);
641 if (ret < 0) return ret;
642 ret = fstat(src, &st);
643 if (ret < 0) return ret;
644 strcpy(dstpath, CWD);
645 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
646 ret = dst = creat(dstpath, st.st_mode);
647 if (ret < 0) return ret;
648 while ((size = read(src, buf, BUFSIZ)) > 0)
649 write(dst, buf, size);
650 close(src);
651 close(dst);
652 return 0;
654 static int adddir(const char *path) {
655 int ret;
656 struct stat st;
658 ret = stat(CWD, &st);
659 if (ret < 0) return ret;
660 return mkdir(path, st.st_mode);
662 static int movfile(const char *srcpath) {
663 int ret;
664 char dstpath[PATH_MAX];
666 strcpy(dstpath, CWD);
667 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
668 ret = rename(srcpath, dstpath);
669 if (ret < 0 && errno == EXDEV) {
670 ret = cpyfile(srcpath);
671 if (ret < 0) return ret;
672 ret = delfile(srcpath);
674 return ret;
677 static void
678 start_line_edit(const char *init_input)
680 curs_set(TRUE);
681 strncpy(INPUT, init_input, INPUTSZ);
682 strncpy(rover.edit.buffer, init_input, INPUTSZ);
683 rover.edit.left = strlen(init_input);
684 rover.edit.right = INPUTSZ - 1;
685 rover.edit_scroll = 0;
688 /* Read input and change editing state accordingly. */
689 static EditStat
690 get_line_edit()
692 int ch = getch();
693 if (ch == '\r' || ch == '\n' || ch == KEY_ENTER) {
694 curs_set(FALSE);
695 return CONFIRM;
696 } else if (ch == '\t') {
697 curs_set(FALSE);
698 return CANCEL;
699 } else if (EDIT_CAN_LEFT(rover.edit) && ch == KEY_LEFT) {
700 EDIT_LEFT(rover.edit);
701 } else if (EDIT_CAN_RIGHT(rover.edit) && ch == KEY_RIGHT) {
702 EDIT_RIGHT(rover.edit);
703 } else if (ch == KEY_UP) {
704 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
705 } else if (ch == KEY_DOWN) {
706 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
707 } else if (ch == erasechar() || ch == KEY_BACKSPACE) {
708 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
709 } else if (ch == KEY_DC) {
710 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
711 } else if (ch == killchar()) {
712 EDIT_CLEAR(rover.edit);
713 clear_message();
714 } else if (!EDIT_FULL(rover.edit) && isprint(ch)) {
715 EDIT_INSERT(rover.edit, ch);
717 /* Copy edit contents to INPUT and append null character. */
718 strncpy(INPUT, rover.edit.buffer, rover.edit.left);
719 strncpy(&INPUT[rover.edit.left], &rover.edit.buffer[rover.edit.right+1],
720 INPUTSZ-rover.edit.left-1);
721 INPUT[rover.edit.left+INPUTSZ-rover.edit.right-1] = '\0';
722 return CONTINUE;
725 /* Update line input on the screen. */
726 static void
727 update_input(char *prompt, Color color)
729 int plen, ilen, maxlen;
731 plen = strlen(prompt);
732 ilen = strlen(INPUT);
733 maxlen = STATUSPOS - plen - 2;
734 if (ilen - rover.edit_scroll < maxlen)
735 rover.edit_scroll = MAX(ilen - maxlen, 0);
736 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
737 rover.edit_scroll = rover.edit.left - maxlen;
738 else if (rover.edit.left < rover.edit_scroll)
739 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
740 color_set(RVC_PROMPT, NULL);
741 mvaddstr(LINES - 1, 0, prompt);
742 color_set(color, NULL);
743 mvaddnstr(LINES - 1, plen, &INPUT[rover.edit_scroll], maxlen);
744 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
745 color_set(DEFAULT, NULL);
746 if (rover.edit_scroll)
747 mvaddch(LINES - 1, plen - 1, '<');
748 if (ilen > rover.edit_scroll + maxlen)
749 mvaddch(LINES - 1, plen + maxlen, '>');
750 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
753 int
754 main(int argc, char *argv[])
756 int i, ch;
757 char *program;
758 const char *key;
759 DIR *d;
760 EditStat edit_stat;
762 if (argc == 2) {
763 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
764 printf("rover %s\n", RV_VERSION);
765 return 0;
766 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
767 printf(
768 "Usage: rover [DIRECTORY [DIRECTORY [DIRECTORY [...]]]]\n"
769 " or: rover [OPTION]\n"
770 "Browse current working directory or the ones specified.\n\n"
771 "Options:\n"
772 " -h, --help print this help message and exit\n"
773 " -v, --version print program version and exit\n\n"
774 "See rover(1) for more information.\n\n"
775 "Rover homepage: <https://github.com/lecram/rover>.\n"
776 );
777 return 0;
780 init_term();
781 rover.nfiles = 0;
782 for (i = 0; i < 10; i++) {
783 rover.esel[i] = rover.scroll[i] = 0;
784 rover.flags[i] = SHOW_FILES | SHOW_DIRS;
786 strcpy(rover.cwd[0], getenv("HOME"));
787 for (i = 1; i < argc && i < 10; i++) {
788 if ((d = opendir(argv[i]))) {
789 realpath(argv[i], rover.cwd[i]);
790 closedir(d);
791 } else
792 strcpy(rover.cwd[i], rover.cwd[0]);
794 getcwd(rover.cwd[i], PATH_MAX);
795 for (i++; i < 10; i++)
796 strcpy(rover.cwd[i], rover.cwd[i-1]);
797 for (i = 0; i < 10; i++)
798 if (rover.cwd[i][strlen(rover.cwd[i]) - 1] != '/')
799 strcat(rover.cwd[i], "/");
800 rover.tab = 1;
801 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
802 init_marks(&rover.marks);
803 cd(1);
804 while (1) {
805 ch = getch();
806 key = keyname(ch);
807 clear_message();
808 if (!strcmp(key, RVK_QUIT)) break;
809 else if (ch >= '0' && ch <= '9') {
810 rover.tab = ch - '0';
811 cd(0);
812 } else if (!strcmp(key, RVK_HELP)) {
813 ARGS[0] = "man";
814 ARGS[1] = "rover";
815 ARGS[2] = NULL;
816 spawn();
817 } else if (!strcmp(key, RVK_DOWN)) {
818 if (!rover.nfiles) continue;
819 ESEL = (ESEL + 1) % rover.nfiles;
820 update_view();
821 } else if (!strcmp(key, RVK_UP)) {
822 if (!rover.nfiles) continue;
823 ESEL = ESEL ? ESEL - 1 : rover.nfiles - 1;
824 update_view();
825 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
826 if (!rover.nfiles) continue;
827 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
828 if (rover.nfiles > HEIGHT)
829 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
830 update_view();
831 } else if (!strcmp(key, RVK_JUMP_UP)) {
832 if (!rover.nfiles) continue;
833 ESEL = MAX(ESEL - RV_JUMP, 0);
834 SCROLL = MAX(SCROLL - RV_JUMP, 0);
835 update_view();
836 } else if (!strcmp(key, RVK_CD_DOWN)) {
837 if (!rover.nfiles || !ISDIR(ENAME(ESEL))) continue;
838 strcat(CWD, ENAME(ESEL));
839 cd(1);
840 } else if (!strcmp(key, RVK_CD_UP)) {
841 char *dirname, first;
842 if (!strcmp(CWD, "/")) continue;
843 CWD[strlen(CWD) - 1] = '\0';
844 dirname = strrchr(CWD, '/') + 1;
845 first = dirname[0];
846 dirname[0] = '\0';
847 cd(1);
848 dirname[0] = first;
849 dirname[strlen(dirname)] = '/';
850 try_to_sel(dirname);
851 dirname[0] = '\0';
852 update_view();
853 } else if (!strcmp(key, RVK_HOME)) {
854 strcpy(CWD, getenv("HOME"));
855 if (CWD[strlen(CWD) - 1] != '/')
856 strcat(CWD, "/");
857 cd(1);
858 } else if (!strcmp(key, RVK_REFRESH)) {
859 reload();
860 } else if (!strcmp(key, RVK_SHELL)) {
861 program = getenv("SHELL");
862 if (program) {
863 ARGS[0] = program;
864 ARGS[1] = NULL;
865 spawn();
866 reload();
868 } else if (!strcmp(key, RVK_VIEW)) {
869 if (!rover.nfiles || ISDIR(ENAME(ESEL))) continue;
870 program = getenv("PAGER");
871 if (program) {
872 ARGS[0] = program;
873 ARGS[1] = ENAME(ESEL);
874 ARGS[2] = NULL;
875 spawn();
877 } else if (!strcmp(key, RVK_EDIT)) {
878 if (!rover.nfiles || ISDIR(ENAME(ESEL))) continue;
879 program = getenv("EDITOR");
880 if (program) {
881 ARGS[0] = program;
882 ARGS[1] = ENAME(ESEL);
883 ARGS[2] = NULL;
884 spawn();
885 cd(0);
887 } else if (!strcmp(key, RVK_SEARCH)) {
888 int oldsel, oldscroll, length;
889 char *prompt = "search: ";
890 if (!rover.nfiles) continue;
891 oldsel = ESEL;
892 oldscroll = SCROLL;
893 start_line_edit("");
894 update_input(prompt, DEFAULT);
895 while ((edit_stat = get_line_edit()) == CONTINUE) {
896 int sel;
897 Color color = RED;
898 length = strlen(INPUT);
899 if (length) {
900 for (sel = 0; sel < rover.nfiles; sel++)
901 if (!strncmp(ENAME(sel), INPUT, length))
902 break;
903 if (sel < rover.nfiles) {
904 color = GREEN;
905 ESEL = sel;
906 if (rover.nfiles > HEIGHT) {
907 if (sel < 3)
908 SCROLL = 0;
909 else if (sel - 3 > rover.nfiles - HEIGHT)
910 SCROLL = rover.nfiles - HEIGHT;
911 else
912 SCROLL = sel - 3;
915 } else {
916 ESEL = oldsel;
917 SCROLL = oldscroll;
919 update_view();
920 update_input(prompt, color);
922 if (edit_stat == CANCEL) {
923 ESEL = oldsel;
924 SCROLL = oldscroll;
926 clear_message();
927 update_view();
928 } else if (!strcmp(key, RVK_TG_FILES)) {
929 FLAGS ^= SHOW_FILES;
930 reload();
931 } else if (!strcmp(key, RVK_TG_DIRS)) {
932 FLAGS ^= SHOW_DIRS;
933 reload();
934 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
935 FLAGS ^= SHOW_HIDDEN;
936 reload();
937 } else if (!strcmp(key, RVK_NEW_FILE)) {
938 int ok = 0;
939 char *prompt = "new file: ";
940 start_line_edit("");
941 update_input(prompt, DEFAULT);
942 while ((edit_stat = get_line_edit()) == CONTINUE) {
943 int length = strlen(INPUT);
944 ok = 1;
945 for (i = 0; i < rover.nfiles; i++) {
946 if (
947 !strncmp(ENAME(i), INPUT, length) &&
948 (!strcmp(ENAME(i) + length, "") ||
949 !strcmp(ENAME(i) + length, "/"))
950 ) {
951 ok = 0;
952 break;
955 update_input(prompt, ok ? GREEN : RED);
957 clear_message();
958 if (edit_stat == CONFIRM && strlen(INPUT)) {
959 if (ok) {
960 addfile(INPUT);
961 cd(1);
962 try_to_sel(INPUT);
963 update_view();
964 } else
965 message("File already exists.", RED);
967 } else if (!strcmp(key, RVK_NEW_DIR)) {
968 int ok = 0;
969 char *prompt = "new directory: ";
970 start_line_edit("");
971 update_input(prompt, DEFAULT);
972 while ((edit_stat = get_line_edit()) == CONTINUE) {
973 int length = strlen(INPUT);
974 ok = 1;
975 for (i = 0; i < rover.nfiles; i++) {
976 if (
977 !strncmp(ENAME(i), INPUT, length) &&
978 (!strcmp(ENAME(i) + length, "") ||
979 !strcmp(ENAME(i) + length, "/"))
980 ) {
981 ok = 0;
982 break;
985 update_input(prompt, ok ? GREEN : RED);
987 clear_message();
988 if (edit_stat == CONFIRM && strlen(INPUT)) {
989 if (ok) {
990 adddir(INPUT);
991 cd(1);
992 try_to_sel(INPUT);
993 update_view();
994 } else
995 message("File already exists.", RED);
997 } else if (!strcmp(key, RVK_RENAME)) {
998 int ok = 0;
999 char *prompt = "rename: ";
1000 char *last;
1001 int isdir;
1002 strcpy(INPUT, ENAME(ESEL));
1003 last = INPUT + strlen(INPUT) - 1;
1004 if ((isdir = *last == '/'))
1005 *last = '\0';
1006 start_line_edit(INPUT);
1007 update_input(prompt, RED);
1008 while ((edit_stat = get_line_edit()) == CONTINUE) {
1009 int length = strlen(INPUT);
1010 ok = 1;
1011 for (i = 0; i < rover.nfiles; i++)
1012 if (
1013 !strncmp(ENAME(i), INPUT, length) &&
1014 (!strcmp(ENAME(i) + length, "") ||
1015 !strcmp(ENAME(i) + length, "/"))
1016 ) {
1017 ok = 0;
1018 break;
1020 update_input(prompt, ok ? GREEN : RED);
1022 clear_message();
1023 if (edit_stat == CONFIRM && strlen(INPUT)) {
1024 if (isdir)
1025 strcat(INPUT, "/");
1026 if (ok) {
1027 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1028 del_mark(&rover.marks, ENAME(ESEL));
1029 add_mark(&rover.marks, CWD, INPUT);
1031 cd(1);
1032 try_to_sel(INPUT);
1033 update_view();
1034 } else
1035 message("File already exists.", RED);
1037 } else if (!strcmp(key, RVK_DELETE)) {
1038 if (rover.nfiles) {
1039 message("Delete selected entry? (Y to confirm)", YELLOW);
1040 if (getch() == 'Y') {
1041 const char *name = ENAME(ESEL);
1042 int ret = ISDIR(name) ? deldir(name) : delfile(name);
1043 reload();
1044 if (ret)
1045 message("Could not delete entry.", RED);
1046 } else
1047 clear_message();
1048 } else
1049 message("No entry selected for deletion.", RED);
1050 } else if (!strcmp(key, RVK_TG_MARK)) {
1051 if (MARKED(ESEL))
1052 del_mark(&rover.marks, ENAME(ESEL));
1053 else
1054 add_mark(&rover.marks, CWD, ENAME(ESEL));
1055 MARKED(ESEL) = !MARKED(ESEL);
1056 ESEL = (ESEL + 1) % rover.nfiles;
1057 update_view();
1058 } else if (!strcmp(key, RVK_INVMARK)) {
1059 for (i = 0; i < rover.nfiles; i++) {
1060 if (MARKED(i))
1061 del_mark(&rover.marks, ENAME(i));
1062 else
1063 add_mark(&rover.marks, CWD, ENAME(i));
1064 MARKED(i) = !MARKED(i);
1066 update_view();
1067 } else if (!strcmp(key, RVK_MARKALL)) {
1068 for (i = 0; i < rover.nfiles; i++)
1069 if (!MARKED(i)) {
1070 add_mark(&rover.marks, CWD, ENAME(i));
1071 MARKED(i) = 1;
1073 update_view();
1074 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1075 if (rover.marks.nentries) {
1076 message("Delete marked entries? (Y to confirm)", YELLOW);
1077 if (getch() == 'Y')
1078 process_marked(NULL, delfile, deldir);
1079 else
1080 clear_message();
1081 } else
1082 message("No entries marked for deletion.", RED);
1083 } else if (!strcmp(key, RVK_MARK_COPY)) {
1084 if (rover.marks.nentries)
1085 process_marked(adddir, cpyfile, NULL);
1086 else
1087 message("No entries marked for copying.", RED);
1088 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1089 if (rover.marks.nentries)
1090 process_marked(adddir, movfile, deldir);
1091 else
1092 message("No entries marked for moving.", RED);
1095 if (rover.nfiles)
1096 free_rows(&rover.rows, rover.nfiles);
1097 free_marks(&rover.marks);
1098 delwin(rover.window);
1099 return 0;