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_MARKS, 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 mvwaddnstr(rover.window, i + 1, 2, ROW, COLS - 4);
365 if (marking && MARKED(j)) {
366 wcolor_set(rover.window, RVC_MARKS, NULL);
367 mvwaddch(rover.window, i + 1, 1, RVS_MARK);
368 } else
369 mvwaddch(rover.window, i + 1, 1, ' ');
370 wcolor_set(rover.window, DEFAULT, NULL);
371 if (j == ESEL)
372 wattr_off(rover.window, A_REVERSE, NULL);
374 for (; i < HEIGHT; i++)
375 mvwhline(rover.window, i + 1, 1, ' ', COLS - 2);
376 if (rover.nfiles > HEIGHT) {
377 int center, height;
378 center = (SCROLL + (HEIGHT / 2)) * HEIGHT / rover.nfiles;
379 height = (HEIGHT-1) * HEIGHT / rover.nfiles;
380 if (!height) height = 1;
381 wcolor_set(rover.window, RVC_BORDER, NULL);
382 wborder(rover.window, 0, 0, 0, 0, 0, 0, 0, 0);
383 wcolor_set(rover.window, RVC_SCROLLBAR, NULL);
384 mvwvline(rover.window, center-(height/2)+1, COLS-1, RVS_SCROLLBAR, height);
385 wcolor_set(rover.window, DEFAULT, NULL);
387 STATUS[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
388 STATUS[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
389 STATUS[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
390 if (!rover.nfiles)
391 strcpy(ROW, "0/0");
392 else
393 snprintf(ROW, ROWSZ, "%d/%d", ESEL + 1, rover.nfiles);
394 snprintf(STATUS+3, STATUSSZ-3, "%12s", ROW);
395 color_set(RVC_STATUS, NULL);
396 mvaddstr(LINES - 1, STATUSPOS, STATUS);
397 color_set(DEFAULT, NULL);
398 wrefresh(rover.window);
401 /* Show a message on the status bar. */
402 static void
403 message(const char *msg, Color color)
405 int len, pos;
407 len = strlen(msg);
408 pos = (STATUSPOS - len) / 2;
409 attr_on(A_BOLD, NULL);
410 color_set(color, NULL);
411 mvaddstr(LINES - 1, pos, msg);
412 color_set(DEFAULT, NULL);
413 attr_off(A_BOLD, NULL);
416 /* Clear message area, leaving only status info. */
417 static void
418 clear_message()
420 mvhline(LINES - 1, 0, ' ', STATUSPOS);
423 /* Comparison used to sort listing entries. */
424 static int
425 rowcmp(const void *a, const void *b)
427 int isdir1, isdir2, cmpdir;
428 const Row *r1 = a;
429 const Row *r2 = b;
430 isdir1 = ISDIR(r1->name);
431 isdir2 = ISDIR(r2->name);
432 cmpdir = isdir2 - isdir1;
433 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
436 /* Get all entries in current working directory. */
437 static int
438 ls(Row **rowsp, uint8_t flags)
440 DIR *dp;
441 struct dirent *ep;
442 struct stat statbuf;
443 Row *rows;
444 int i, n;
446 if(!(dp = opendir("."))) return -1;
447 n = -2; /* We don't want the entries "." and "..". */
448 while (readdir(dp)) n++;
449 rewinddir(dp);
450 rows = malloc(n * sizeof *rows);
451 i = 0;
452 while ((ep = readdir(dp))) {
453 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
454 continue;
455 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
456 continue;
457 lstat(ep->d_name, &statbuf);
458 if (S_ISDIR(statbuf.st_mode)) {
459 if (flags & SHOW_DIRS) {
460 rows[i].name = malloc(strlen(ep->d_name) + 2);
461 strcpy(rows[i].name, ep->d_name);
462 strcat(rows[i].name, "/");
463 i++;
465 } else if (flags & SHOW_FILES) {
466 rows[i].name = malloc(strlen(ep->d_name) + 1);
467 strcpy(rows[i].name, ep->d_name);
468 rows[i].size = statbuf.st_size;
469 i++;
472 n = i; /* Ignore unused space in array caused by filters. */
473 qsort(rows, n, sizeof (*rows), rowcmp);
474 closedir(dp);
475 *rowsp = rows;
476 return n;
479 static void
480 free_rows(Row **rowsp, int nfiles)
482 int i;
484 for (i = 0; i < nfiles; i++)
485 free((*rowsp)[i].name);
486 free(*rowsp);
487 *rowsp = NULL;
490 /* Change working directory to the path in CWD. */
491 static void
492 cd(int reset)
494 int i, j;
496 message("Loading...", CYAN);
497 refresh();
498 if (reset) ESEL = SCROLL = 0;
499 chdir(CWD);
500 if (rover.nfiles)
501 free_rows(&rover.rows, rover.nfiles);
502 rover.nfiles = ls(&rover.rows, FLAGS);
503 if (!strcmp(CWD, rover.marks.dirpath)) {
504 for (i = 0; i < rover.nfiles; i++) {
505 for (j = 0; j < rover.marks.bulk; j++)
506 if (
507 rover.marks.entries[j] &&
508 !strcmp(rover.marks.entries[j], ENAME(i))
510 break;
511 MARKED(i) = j < rover.marks.bulk;
513 } else
514 for (i = 0; i < rover.nfiles; i++)
515 MARKED(i) = 0;
516 clear_message();
517 update_view();
520 /* Select a target entry, if it is present. */
521 static void
522 try_to_sel(const char *target)
524 ESEL = 0;
525 if (!ISDIR(target))
526 while ((ESEL+1) < rover.nfiles && ISDIR(ENAME(ESEL)))
527 ESEL++;
528 while ((ESEL+1) < rover.nfiles && strcoll(ENAME(ESEL), target) < 0)
529 ESEL++;
530 if (rover.nfiles > HEIGHT) {
531 SCROLL = ESEL - (HEIGHT / 2);
532 SCROLL = MIN(MAX(SCROLL, 0), rover.nfiles - HEIGHT);
536 /* Reload CWD, but try to keep selection. */
537 static void
538 reload()
540 if (rover.nfiles) {
541 strcpy(INPUT, ENAME(ESEL));
542 cd(1);
543 try_to_sel(INPUT);
544 update_view();
545 } else
546 cd(1);
549 /* Recursively process a source directory using CWD as destination root.
550 For each node (i.e. directory), do the following:
551 1. call pre(destination);
552 2. call proc() on every child leaf (i.e. files);
553 3. recurse into every child node;
554 4. call pos(source).
555 E.g. to move directory /src/ (and all its contents) inside /dst/:
556 strcpy(CWD, "/dst/");
557 process_dir(adddir, movfile, deldir, "/src/"); */
558 static int
559 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
561 int ret;
562 DIR *dp;
563 struct dirent *ep;
564 struct stat statbuf;
565 char subpath[PATH_MAX];
567 ret = 0;
568 if (pre) {
569 char dstpath[PATH_MAX];
570 strcpy(dstpath, CWD);
571 strcat(dstpath, path + strlen(rover.marks.dirpath));
572 ret |= pre(dstpath);
574 if(!(dp = opendir(path))) return -1;
575 while ((ep = readdir(dp))) {
576 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
577 continue;
578 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
579 stat(subpath, &statbuf);
580 if (S_ISDIR(statbuf.st_mode)) {
581 strcat(subpath, "/");
582 ret |= process_dir(pre, proc, pos, subpath);
583 } else
584 ret |= proc(subpath);
586 closedir(dp);
587 if (pos) ret |= pos(path);
588 return ret;
591 /* Process all marked entries using CWD as destination root.
592 All marked entries that are directories will be recursively processed.
593 See process_dir() for details on the parameters. */
594 static void
595 process_marked(PROCESS pre, PROCESS proc, PROCESS pos)
597 int i, ret;
598 char path[PATH_MAX];
600 clear_message();
601 message("Processing...", CYAN);
602 refresh();
603 for (i = 0; i < rover.marks.bulk; i++)
604 if (rover.marks.entries[i]) {
605 ret = 0;
606 snprintf(path, PATH_MAX, "%s%s", rover.marks.dirpath, rover.marks.entries[i]);
607 if (ISDIR(rover.marks.entries[i])) {
608 if (!strncmp(path, CWD, strlen(path)))
609 ret = -1;
610 else
611 ret = process_dir(pre, proc, pos, path);
612 } else
613 ret = proc(path);
614 if (!ret) del_mark(&rover.marks, rover.marks.entries[i]);
616 reload();
617 if (!rover.marks.nentries)
618 message("Done.", GREEN);
619 else
620 message("Some errors occured.", RED);
623 /* Wrappers for file operations. */
624 static PROCESS delfile = unlink;
625 static PROCESS deldir = rmdir;
626 static int addfile(const char *path) {
627 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
628 int ret;
630 ret = creat(path, 0644);
631 if (ret < 0) return ret;
632 return close(ret);
634 static int cpyfile(const char *srcpath) {
635 int src, dst, ret;
636 size_t size;
637 struct stat st;
638 char buf[BUFSIZ];
639 char dstpath[PATH_MAX];
641 ret = src = open(srcpath, O_RDONLY);
642 if (ret < 0) return ret;
643 ret = fstat(src, &st);
644 if (ret < 0) return ret;
645 strcpy(dstpath, CWD);
646 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
647 ret = dst = creat(dstpath, st.st_mode);
648 if (ret < 0) return ret;
649 while ((size = read(src, buf, BUFSIZ)) > 0)
650 write(dst, buf, size);
651 close(src);
652 close(dst);
653 return 0;
655 static int adddir(const char *path) {
656 int ret;
657 struct stat st;
659 ret = stat(CWD, &st);
660 if (ret < 0) return ret;
661 return mkdir(path, st.st_mode);
663 static int movfile(const char *srcpath) {
664 int ret;
665 char dstpath[PATH_MAX];
667 strcpy(dstpath, CWD);
668 strcat(dstpath, srcpath + strlen(rover.marks.dirpath));
669 ret = rename(srcpath, dstpath);
670 if (ret < 0 && errno == EXDEV) {
671 ret = cpyfile(srcpath);
672 if (ret < 0) return ret;
673 ret = delfile(srcpath);
675 return ret;
678 static void
679 start_line_edit(const char *init_input)
681 curs_set(TRUE);
682 strncpy(INPUT, init_input, INPUTSZ);
683 strncpy(rover.edit.buffer, init_input, INPUTSZ);
684 rover.edit.left = strlen(init_input);
685 rover.edit.right = INPUTSZ - 1;
686 rover.edit_scroll = 0;
689 /* Read input and change editing state accordingly. */
690 static EditStat
691 get_line_edit()
693 int ch = getch();
694 if (ch == '\r' || ch == '\n' || ch == KEY_ENTER) {
695 curs_set(FALSE);
696 return CONFIRM;
697 } else if (ch == '\t') {
698 curs_set(FALSE);
699 return CANCEL;
700 } else if (EDIT_CAN_LEFT(rover.edit) && ch == KEY_LEFT) {
701 EDIT_LEFT(rover.edit);
702 } else if (EDIT_CAN_RIGHT(rover.edit) && ch == KEY_RIGHT) {
703 EDIT_RIGHT(rover.edit);
704 } else if (ch == KEY_UP) {
705 while (EDIT_CAN_LEFT(rover.edit)) EDIT_LEFT(rover.edit);
706 } else if (ch == KEY_DOWN) {
707 while (EDIT_CAN_RIGHT(rover.edit)) EDIT_RIGHT(rover.edit);
708 } else if (ch == erasechar() || ch == KEY_BACKSPACE) {
709 if (EDIT_CAN_LEFT(rover.edit)) EDIT_BACKSPACE(rover.edit);
710 } else if (ch == KEY_DC) {
711 if (EDIT_CAN_RIGHT(rover.edit)) EDIT_DELETE(rover.edit);
712 } else if (ch == killchar()) {
713 EDIT_CLEAR(rover.edit);
714 clear_message();
715 } else if (!EDIT_FULL(rover.edit) && isprint(ch)) {
716 EDIT_INSERT(rover.edit, ch);
718 /* Copy edit contents to INPUT and append null character. */
719 strncpy(INPUT, rover.edit.buffer, rover.edit.left);
720 strncpy(&INPUT[rover.edit.left], &rover.edit.buffer[rover.edit.right+1],
721 INPUTSZ-rover.edit.left-1);
722 INPUT[rover.edit.left+INPUTSZ-rover.edit.right-1] = '\0';
723 return CONTINUE;
726 /* Update line input on the screen. */
727 static void
728 update_input(char *prompt, Color color)
730 int plen, ilen, maxlen;
732 plen = strlen(prompt);
733 ilen = strlen(INPUT);
734 maxlen = STATUSPOS - plen - 2;
735 if (ilen - rover.edit_scroll < maxlen)
736 rover.edit_scroll = MAX(ilen - maxlen, 0);
737 else if (rover.edit.left > rover.edit_scroll + maxlen - 1)
738 rover.edit_scroll = rover.edit.left - maxlen;
739 else if (rover.edit.left < rover.edit_scroll)
740 rover.edit_scroll = MAX(rover.edit.left - maxlen, 0);
741 color_set(RVC_PROMPT, NULL);
742 mvaddstr(LINES - 1, 0, prompt);
743 color_set(color, NULL);
744 mvaddnstr(LINES - 1, plen, &INPUT[rover.edit_scroll], maxlen);
745 mvaddch(LINES - 1, plen + MIN(ilen - rover.edit_scroll, maxlen + 1), ' ');
746 color_set(DEFAULT, NULL);
747 if (rover.edit_scroll)
748 mvaddch(LINES - 1, plen - 1, '<');
749 if (ilen > rover.edit_scroll + maxlen)
750 mvaddch(LINES - 1, plen + maxlen, '>');
751 move(LINES - 1, plen + rover.edit.left - rover.edit_scroll);
754 int
755 main(int argc, char *argv[])
757 int i, ch;
758 char *program;
759 const char *key;
760 DIR *d;
761 EditStat edit_stat;
763 if (argc == 2) {
764 if (!strcmp(argv[1], "-v") || !strcmp(argv[1], "--version")) {
765 printf("rover %s\n", RV_VERSION);
766 return 0;
767 } else if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) {
768 printf(
769 "Usage: rover [DIRECTORY [DIRECTORY [DIRECTORY [...]]]]\n"
770 " or: rover [OPTION]\n"
771 "Browse current working directory or the ones specified.\n\n"
772 "Options:\n"
773 " -h, --help print this help message and exit\n"
774 " -v, --version print program version and exit\n\n"
775 "See rover(1) for more information.\n\n"
776 "Rover homepage: <https://github.com/lecram/rover>.\n"
777 );
778 return 0;
781 init_term();
782 rover.nfiles = 0;
783 for (i = 0; i < 10; i++) {
784 rover.esel[i] = rover.scroll[i] = 0;
785 rover.flags[i] = SHOW_FILES | SHOW_DIRS;
787 strcpy(rover.cwd[0], getenv("HOME"));
788 for (i = 1; i < argc && i < 10; i++) {
789 if ((d = opendir(argv[i]))) {
790 realpath(argv[i], rover.cwd[i]);
791 closedir(d);
792 } else
793 strcpy(rover.cwd[i], rover.cwd[0]);
795 getcwd(rover.cwd[i], PATH_MAX);
796 for (i++; i < 10; i++)
797 strcpy(rover.cwd[i], rover.cwd[i-1]);
798 for (i = 0; i < 10; i++)
799 if (rover.cwd[i][strlen(rover.cwd[i]) - 1] != '/')
800 strcat(rover.cwd[i], "/");
801 rover.tab = 1;
802 rover.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
803 init_marks(&rover.marks);
804 cd(1);
805 while (1) {
806 ch = getch();
807 key = keyname(ch);
808 clear_message();
809 if (!strcmp(key, RVK_QUIT)) break;
810 else if (ch >= '0' && ch <= '9') {
811 rover.tab = ch - '0';
812 cd(0);
813 } else if (!strcmp(key, RVK_HELP)) {
814 ARGS[0] = "man";
815 ARGS[1] = "rover";
816 ARGS[2] = NULL;
817 spawn();
818 } else if (!strcmp(key, RVK_DOWN)) {
819 if (!rover.nfiles) continue;
820 ESEL = (ESEL + 1) % rover.nfiles;
821 update_view();
822 } else if (!strcmp(key, RVK_UP)) {
823 if (!rover.nfiles) continue;
824 ESEL = ESEL ? ESEL - 1 : rover.nfiles - 1;
825 update_view();
826 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
827 if (!rover.nfiles) continue;
828 ESEL = MIN(ESEL + RV_JUMP, rover.nfiles - 1);
829 if (rover.nfiles > HEIGHT)
830 SCROLL = MIN(SCROLL + RV_JUMP, rover.nfiles - HEIGHT);
831 update_view();
832 } else if (!strcmp(key, RVK_JUMP_UP)) {
833 if (!rover.nfiles) continue;
834 ESEL = MAX(ESEL - RV_JUMP, 0);
835 SCROLL = MAX(SCROLL - RV_JUMP, 0);
836 update_view();
837 } else if (!strcmp(key, RVK_CD_DOWN)) {
838 if (!rover.nfiles || !ISDIR(ENAME(ESEL))) continue;
839 strcat(CWD, ENAME(ESEL));
840 cd(1);
841 } else if (!strcmp(key, RVK_CD_UP)) {
842 char *dirname, first;
843 if (!strcmp(CWD, "/")) continue;
844 CWD[strlen(CWD) - 1] = '\0';
845 dirname = strrchr(CWD, '/') + 1;
846 first = dirname[0];
847 dirname[0] = '\0';
848 cd(1);
849 dirname[0] = first;
850 dirname[strlen(dirname)] = '/';
851 try_to_sel(dirname);
852 dirname[0] = '\0';
853 update_view();
854 } else if (!strcmp(key, RVK_HOME)) {
855 strcpy(CWD, getenv("HOME"));
856 if (CWD[strlen(CWD) - 1] != '/')
857 strcat(CWD, "/");
858 cd(1);
859 } else if (!strcmp(key, RVK_REFRESH)) {
860 reload();
861 } else if (!strcmp(key, RVK_SHELL)) {
862 program = getenv("SHELL");
863 if (program) {
864 ARGS[0] = program;
865 ARGS[1] = NULL;
866 spawn();
867 reload();
869 } else if (!strcmp(key, RVK_VIEW)) {
870 if (!rover.nfiles || ISDIR(ENAME(ESEL))) continue;
871 program = getenv("PAGER");
872 if (program) {
873 ARGS[0] = program;
874 ARGS[1] = ENAME(ESEL);
875 ARGS[2] = NULL;
876 spawn();
878 } else if (!strcmp(key, RVK_EDIT)) {
879 if (!rover.nfiles || ISDIR(ENAME(ESEL))) continue;
880 program = getenv("EDITOR");
881 if (program) {
882 ARGS[0] = program;
883 ARGS[1] = ENAME(ESEL);
884 ARGS[2] = NULL;
885 spawn();
886 cd(0);
888 } else if (!strcmp(key, RVK_SEARCH)) {
889 int oldsel, oldscroll, length;
890 char *prompt = "search: ";
891 if (!rover.nfiles) continue;
892 oldsel = ESEL;
893 oldscroll = SCROLL;
894 start_line_edit("");
895 update_input(prompt, DEFAULT);
896 while ((edit_stat = get_line_edit()) == CONTINUE) {
897 int sel;
898 Color color = RED;
899 length = strlen(INPUT);
900 if (length) {
901 for (sel = 0; sel < rover.nfiles; sel++)
902 if (!strncmp(ENAME(sel), INPUT, length))
903 break;
904 if (sel < rover.nfiles) {
905 color = GREEN;
906 ESEL = sel;
907 if (rover.nfiles > HEIGHT) {
908 if (sel < 3)
909 SCROLL = 0;
910 else if (sel - 3 > rover.nfiles - HEIGHT)
911 SCROLL = rover.nfiles - HEIGHT;
912 else
913 SCROLL = sel - 3;
916 } else {
917 ESEL = oldsel;
918 SCROLL = oldscroll;
920 update_view();
921 update_input(prompt, color);
923 if (edit_stat == CANCEL) {
924 ESEL = oldsel;
925 SCROLL = oldscroll;
927 clear_message();
928 update_view();
929 } else if (!strcmp(key, RVK_TG_FILES)) {
930 FLAGS ^= SHOW_FILES;
931 reload();
932 } else if (!strcmp(key, RVK_TG_DIRS)) {
933 FLAGS ^= SHOW_DIRS;
934 reload();
935 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
936 FLAGS ^= SHOW_HIDDEN;
937 reload();
938 } else if (!strcmp(key, RVK_NEW_FILE)) {
939 int ok = 0;
940 char *prompt = "new file: ";
941 start_line_edit("");
942 update_input(prompt, DEFAULT);
943 while ((edit_stat = get_line_edit()) == CONTINUE) {
944 int length = strlen(INPUT);
945 ok = 1;
946 for (i = 0; i < rover.nfiles; i++) {
947 if (
948 !strncmp(ENAME(i), INPUT, length) &&
949 (!strcmp(ENAME(i) + length, "") ||
950 !strcmp(ENAME(i) + length, "/"))
951 ) {
952 ok = 0;
953 break;
956 update_input(prompt, ok ? GREEN : RED);
958 clear_message();
959 if (edit_stat == CONFIRM && strlen(INPUT)) {
960 if (ok) {
961 addfile(INPUT);
962 cd(1);
963 try_to_sel(INPUT);
964 update_view();
965 } else
966 message("File already exists.", RED);
968 } else if (!strcmp(key, RVK_NEW_DIR)) {
969 int ok = 0;
970 char *prompt = "new directory: ";
971 start_line_edit("");
972 update_input(prompt, DEFAULT);
973 while ((edit_stat = get_line_edit()) == CONTINUE) {
974 int length = strlen(INPUT);
975 ok = 1;
976 for (i = 0; i < rover.nfiles; i++) {
977 if (
978 !strncmp(ENAME(i), INPUT, length) &&
979 (!strcmp(ENAME(i) + length, "") ||
980 !strcmp(ENAME(i) + length, "/"))
981 ) {
982 ok = 0;
983 break;
986 update_input(prompt, ok ? GREEN : RED);
988 clear_message();
989 if (edit_stat == CONFIRM && strlen(INPUT)) {
990 if (ok) {
991 adddir(INPUT);
992 cd(1);
993 try_to_sel(INPUT);
994 update_view();
995 } else
996 message("File already exists.", RED);
998 } else if (!strcmp(key, RVK_RENAME)) {
999 int ok = 0;
1000 char *prompt = "rename: ";
1001 char *last;
1002 int isdir;
1003 strcpy(INPUT, ENAME(ESEL));
1004 last = INPUT + strlen(INPUT) - 1;
1005 if ((isdir = *last == '/'))
1006 *last = '\0';
1007 start_line_edit(INPUT);
1008 update_input(prompt, RED);
1009 while ((edit_stat = get_line_edit()) == CONTINUE) {
1010 int length = strlen(INPUT);
1011 ok = 1;
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;
1021 update_input(prompt, ok ? GREEN : RED);
1023 clear_message();
1024 if (edit_stat == CONFIRM && strlen(INPUT)) {
1025 if (isdir)
1026 strcat(INPUT, "/");
1027 if (ok) {
1028 if (!rename(ENAME(ESEL), INPUT) && MARKED(ESEL)) {
1029 del_mark(&rover.marks, ENAME(ESEL));
1030 add_mark(&rover.marks, CWD, INPUT);
1032 cd(1);
1033 try_to_sel(INPUT);
1034 update_view();
1035 } else
1036 message("File already exists.", RED);
1038 } else if (!strcmp(key, RVK_DELETE)) {
1039 if (rover.nfiles) {
1040 message("Delete selected entry? (Y to confirm)", YELLOW);
1041 if (getch() == 'Y') {
1042 const char *name = ENAME(ESEL);
1043 int ret = ISDIR(name) ? deldir(name) : delfile(name);
1044 reload();
1045 if (ret)
1046 message("Could not delete entry.", RED);
1047 } else
1048 clear_message();
1049 } else
1050 message("No entry selected for deletion.", RED);
1051 } else if (!strcmp(key, RVK_TG_MARK)) {
1052 if (MARKED(ESEL))
1053 del_mark(&rover.marks, ENAME(ESEL));
1054 else
1055 add_mark(&rover.marks, CWD, ENAME(ESEL));
1056 MARKED(ESEL) = !MARKED(ESEL);
1057 ESEL = (ESEL + 1) % rover.nfiles;
1058 update_view();
1059 } else if (!strcmp(key, RVK_INVMARK)) {
1060 for (i = 0; i < rover.nfiles; i++) {
1061 if (MARKED(i))
1062 del_mark(&rover.marks, ENAME(i));
1063 else
1064 add_mark(&rover.marks, CWD, ENAME(i));
1065 MARKED(i) = !MARKED(i);
1067 update_view();
1068 } else if (!strcmp(key, RVK_MARKALL)) {
1069 for (i = 0; i < rover.nfiles; i++)
1070 if (!MARKED(i)) {
1071 add_mark(&rover.marks, CWD, ENAME(i));
1072 MARKED(i) = 1;
1074 update_view();
1075 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1076 if (rover.marks.nentries) {
1077 message("Delete marked entries? (Y to confirm)", YELLOW);
1078 if (getch() == 'Y')
1079 process_marked(NULL, delfile, deldir);
1080 else
1081 clear_message();
1082 } else
1083 message("No entries marked for deletion.", RED);
1084 } else if (!strcmp(key, RVK_MARK_COPY)) {
1085 if (rover.marks.nentries)
1086 process_marked(adddir, cpyfile, NULL);
1087 else
1088 message("No entries marked for copying.", RED);
1089 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1090 if (rover.marks.nentries)
1091 process_marked(adddir, movfile, deldir);
1092 else
1093 message("No entries marked for moving.", RED);
1096 if (rover.nfiles)
1097 free_rows(&rover.rows, rover.nfiles);
1098 free_marks(&rover.marks);
1099 delwin(rover.window);
1100 return 0;