Blob


1 /* needed for some ncurses stuff */
2 #define _XOPEN_SOURCE_EXTENDED
3 #define _FILE_OFFSET_BITS 64
5 #include <sys/stat.h>
6 #include <sys/types.h>
7 #include <sys/wait.h>
9 #include <ctype.h>
10 #include <curses.h>
11 #include <dirent.h>
12 #include <err.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <getopt.h>
16 #include <libgen.h>
17 #include <limits.h>
18 #include <locale.h>
19 #include <signal.h>
20 #include <stdarg.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <wchar.h>
27 #include <wctype.h>
29 #include "config.h"
31 struct option opts[] = {
32 {"help", no_argument, NULL, 'h'},
33 {"version", no_argument, NULL, 'v'},
34 {NULL, 0, NULL, 0}
35 };
37 /* String buffers. */
38 #define BUFLEN PATH_MAX
39 static char BUF1[BUFLEN];
40 static char BUF2[BUFLEN];
41 static char INPUT[BUFLEN];
42 static char CLIPBOARD[BUFLEN];
43 static wchar_t WBUF[BUFLEN];
45 /* Paths to external programs. */
46 static char *user_shell;
47 static char *user_pager;
48 static char *user_editor;
49 static char *user_open;
51 /* Listing view parameters. */
52 #define HEIGHT (LINES-4)
53 #define STATUSPOS (COLS-16)
55 /* Listing view flags. */
56 #define SHOW_FILES 0x01u
57 #define SHOW_DIRS 0x02u
58 #define SHOW_HIDDEN 0x04u
60 /* Marks parameters. */
61 #define BULK_INIT 5
62 #define BULK_THRESH 256
64 /* Information associated to each entry in listing. */
65 struct row {
66 char *name;
67 off_t size;
68 mode_t mode;
69 int islink;
70 int marked;
71 };
73 /* Dynamic array of marked entries. */
74 struct marks {
75 char dirpath[PATH_MAX];
76 int bulk;
77 int nentries;
78 char **entries;
79 };
81 /* Line editing state. */
82 struct edit {
83 wchar_t buffer[BUFLEN + 1];
84 int left, right;
85 };
87 /* Each tab only stores the following information. */
88 struct tab {
89 int scroll;
90 int esel;
91 uint8_t flags;
92 char cwd[PATH_MAX];
93 };
95 struct prog {
96 off_t partial;
97 off_t total;
98 const char *msg;
99 };
101 /* Global state. */
102 static struct state {
103 int tab;
104 int nfiles;
105 struct row *rows;
106 WINDOW *window;
107 struct marks marks;
108 struct edit edit;
109 int edit_scroll;
110 volatile sig_atomic_t pending_usr1;
111 volatile sig_atomic_t pending_winch;
112 struct prog prog;
113 struct tab tabs[10];
114 } fm;
116 /* Macros for accessing global state. */
117 #define ENAME(I) fm.rows[I].name
118 #define ESIZE(I) fm.rows[I].size
119 #define EMODE(I) fm.rows[I].mode
120 #define ISLINK(I) fm.rows[I].islink
121 #define MARKED(I) fm.rows[I].marked
122 #define SCROLL fm.tabs[fm.tab].scroll
123 #define ESEL fm.tabs[fm.tab].esel
124 #define FLAGS fm.tabs[fm.tab].flags
125 #define CWD fm.tabs[fm.tab].cwd
127 /* Helpers. */
128 #define MIN(A, B) ((A) < (B) ? (A) : (B))
129 #define MAX(A, B) ((A) > (B) ? (A) : (B))
130 #define ISDIR(E) (strchr((E), '/') != NULL)
131 #define CTRL(x) ((x) & 0x1f)
132 #define nitems(a) (sizeof(a)/sizeof(a[0]))
134 /* Line Editing Macros. */
135 #define EDIT_FULL(E) ((E).left == (E).right)
136 #define EDIT_CAN_LEFT(E) ((E).left)
137 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
138 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
139 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
140 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
141 #define EDIT_BACKSPACE(E) (E).left--
142 #define EDIT_DELETE(E) (E).right++
143 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
145 enum editstate { CONTINUE, CONFIRM, CANCEL };
146 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
148 typedef int (*PROCESS)(const char *path);
150 #ifndef __dead
151 #define __dead __attribute__((noreturn))
152 #endif
154 static inline __dead void *
155 quit(const char *reason)
157 int saved_errno;
159 saved_errno = errno;
160 endwin();
161 nocbreak();
162 fflush(stderr);
163 errno = saved_errno;
164 err(1, "%s", reason);
167 static inline void *
168 xmalloc(size_t size)
170 void *d;
172 if ((d = malloc(size)) == NULL)
173 quit("malloc");
174 return d;
177 static inline void *
178 xcalloc(size_t nmemb, size_t size)
180 void *d;
182 if ((d = calloc(nmemb, size)) == NULL)
183 quit("calloc");
184 return d;
187 static inline void *
188 xrealloc(void *p, size_t size)
190 void *d;
192 if ((d = realloc(p, size)) == NULL)
193 quit("realloc");
194 return d;
197 static void
198 init_marks(struct marks *marks)
200 strcpy(marks->dirpath, "");
201 marks->bulk = BULK_INIT;
202 marks->nentries = 0;
203 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
206 /* Unmark all entries. */
207 static void
208 mark_none(struct marks *marks)
210 int i;
212 strcpy(marks->dirpath, "");
213 for (i = 0; i < marks->bulk && marks->nentries; i++)
214 if (marks->entries[i]) {
215 free(marks->entries[i]);
216 marks->entries[i] = NULL;
217 marks->nentries--;
219 if (marks->bulk > BULK_THRESH) {
220 /* Reset bulk to free some memory. */
221 free(marks->entries);
222 marks->bulk = BULK_INIT;
223 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
227 static void
228 add_mark(struct marks *marks, char *dirpath, char *entry)
230 int i;
232 if (!strcmp(marks->dirpath, dirpath)) {
233 /* Append mark to directory. */
234 if (marks->nentries == marks->bulk) {
235 /* Expand bulk to accomodate new entry. */
236 int extra = marks->bulk / 2;
237 marks->bulk += extra; /* bulk *= 1.5; */
238 marks->entries = xrealloc(marks->entries,
239 marks->bulk * sizeof(*marks->entries));
240 memset(&marks->entries[marks->nentries], 0,
241 extra * sizeof(*marks->entries));
242 i = marks->nentries;
243 } else {
244 /* Search for empty slot (there must be one). */
245 for (i = 0; i < marks->bulk; i++)
246 if (!marks->entries[i])
247 break;
249 } else {
250 /* Directory changed. Discard old marks. */
251 mark_none(marks);
252 strcpy(marks->dirpath, dirpath);
253 i = 0;
255 marks->entries[i] = xmalloc(strlen(entry) + 1);
256 strcpy(marks->entries[i], entry);
257 marks->nentries++;
260 static void
261 del_mark(struct marks *marks, char *entry)
263 int i;
265 if (marks->nentries > 1) {
266 for (i = 0; i < marks->bulk; i++)
267 if (marks->entries[i] &&
268 !strcmp(marks->entries[i], entry))
269 break;
270 free(marks->entries[i]);
271 marks->entries[i] = NULL;
272 marks->nentries--;
273 } else
274 mark_none(marks);
277 static void
278 free_marks(struct marks *marks)
280 int i;
282 for (i = 0; i < marks->bulk && marks->nentries; i++)
283 if (marks->entries[i]) {
284 free(marks->entries[i]);
285 marks->nentries--;
287 free(marks->entries);
290 static void
291 handle_usr1(int sig)
293 fm.pending_usr1 = 1;
296 static void
297 handle_winch(int sig)
299 fm.pending_winch = 1;
302 static void
303 enable_handlers(void)
305 struct sigaction sa;
307 memset(&sa, 0, sizeof(struct sigaction));
308 sa.sa_handler = handle_usr1;
309 sigaction(SIGUSR1, &sa, NULL);
310 sa.sa_handler = handle_winch;
311 sigaction(SIGWINCH, &sa, NULL);
314 static void
315 disable_handlers(void)
317 struct sigaction sa;
319 memset(&sa, 0, sizeof(struct sigaction));
320 sa.sa_handler = SIG_DFL;
321 sigaction(SIGUSR1, &sa, NULL);
322 sigaction(SIGWINCH, &sa, NULL);
325 static void reload(void);
326 static void update_view(void);
328 /* Handle any signals received since last call. */
329 static void
330 sync_signals(void)
332 if (fm.pending_usr1) {
333 /* SIGUSR1 received: refresh directory listing. */
334 reload();
335 fm.pending_usr1 = 0;
337 if (fm.pending_winch) {
338 /* SIGWINCH received: resize application accordingly. */
339 delwin(fm.window);
340 endwin();
341 refresh();
342 clear();
343 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
344 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
345 SCROLL = ESEL - HEIGHT;
346 update_view();
347 fm.pending_winch = 0;
351 /*
352 * This function must be used in place of getch(). It handles signals
353 * while waiting for user input.
354 */
355 static int
356 fm_getch()
358 int ch;
360 while ((ch = getch()) == ERR)
361 sync_signals();
362 return ch;
365 /*
366 * This function must be used in place of get_wch(). It handles
367 * signals while waiting for user input.
368 */
369 static int
370 fm_get_wch(wint_t *wch)
372 wint_t ret;
374 while ((ret = get_wch(wch)) == (wint_t)ERR)
375 sync_signals();
376 return ret;
379 /* Get user programs from the environment. */
381 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
382 dst = getenv(#src);
384 static void
385 get_user_programs()
387 FM_ENV(user_shell, SHELL);
388 FM_ENV(user_pager, PAGER);
389 FM_ENV(user_editor, VISUAL);
390 if (!user_editor)
391 FM_ENV(user_editor, EDITOR);
392 FM_ENV(user_open, OPEN);
395 /* Do a fork-exec to external program (e.g. $EDITOR). */
396 static void
397 spawn(const char *argv0, ...)
399 pid_t pid;
400 int status;
401 size_t i;
402 const char *argv[16], *last;
403 va_list ap;
405 memset(argv, 0, sizeof(argv));
407 va_start(ap, argv0);
408 argv[0] = argv0;
409 for (i = 1; i < nitems(argv); ++i) {
410 last = va_arg(ap, const char *);
411 if (last == NULL)
412 break;
413 argv[i] = last;
415 va_end(ap);
417 if (last != NULL)
418 abort();
420 disable_handlers();
421 endwin();
423 switch (pid = fork()) {
424 case -1:
425 quit("fork");
426 case 0: /* child */
427 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
428 execvp(argv[0], (char *const *)argv);
429 quit("execvp");
430 default:
431 waitpid(pid, &status, 0);
432 enable_handlers();
433 kill(getpid(), SIGWINCH);
437 static void
438 shell_escaped_cat(char *buf, char *str, size_t n)
440 char *p = buf + strlen(buf);
441 *p++ = '\'';
442 for (n--; n; n--, str++) {
443 switch (*str) {
444 case '\'':
445 if (n < 4)
446 goto done;
447 strcpy(p, "'\\''");
448 n -= 4;
449 p += 4;
450 break;
451 case '\0':
452 goto done;
453 default:
454 *p = *str;
455 p++;
458 done:
459 strncat(p, "'", n);
462 static int
463 open_with_env(char *program, char *path)
465 if (program) {
466 #ifdef RV_SHELL
467 strncpy(BUF1, program, BUFLEN - 1);
468 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
469 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
470 spawn(RV_SHELL, "-c", BUF1, NULL );
471 #else
472 spawn(program, path, NULL);
473 #endif
474 return 1;
476 return 0;
479 /* Curses setup. */
480 static void
481 init_term()
483 setlocale(LC_ALL, "");
484 initscr();
485 cbreak(); /* Get one character at a time. */
486 timeout(100); /* For getch(). */
487 noecho();
488 nonl(); /* No NL->CR/NL on output. */
489 intrflush(stdscr, FALSE);
490 keypad(stdscr, TRUE);
491 curs_set(FALSE); /* Hide blinking cursor. */
492 if (has_colors()) {
493 short bg;
494 start_color();
495 #ifdef NCURSES_EXT_FUNCS
496 use_default_colors();
497 bg = -1;
498 #else
499 bg = COLOR_BLACK;
500 #endif
501 init_pair(RED, COLOR_RED, bg);
502 init_pair(GREEN, COLOR_GREEN, bg);
503 init_pair(YELLOW, COLOR_YELLOW, bg);
504 init_pair(BLUE, COLOR_BLUE, bg);
505 init_pair(CYAN, COLOR_CYAN, bg);
506 init_pair(MAGENTA, COLOR_MAGENTA, bg);
507 init_pair(WHITE, COLOR_WHITE, bg);
508 init_pair(BLACK, COLOR_BLACK, bg);
510 atexit((void (*)(void))endwin);
511 enable_handlers();
514 /* Update the listing view. */
515 static void
516 update_view()
518 int i, j;
519 int numsize;
520 int ishidden;
521 int marking;
523 mvhline(0, 0, ' ', COLS);
524 attr_on(A_BOLD, NULL);
525 color_set(RVC_TABNUM, NULL);
526 mvaddch(0, COLS - 2, fm.tab + '0');
527 attr_off(A_BOLD, NULL);
528 if (fm.marks.nentries) {
529 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
530 color_set(RVC_MARKS, NULL);
531 mvaddstr(0, COLS - 3 - numsize, BUF1);
532 } else
533 numsize = -1;
534 color_set(RVC_CWD, NULL);
535 mbstowcs(WBUF, CWD, PATH_MAX);
536 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
537 wcolor_set(fm.window, RVC_BORDER, NULL);
538 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
539 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
541 /*
542 * Selection might not be visible, due to cursor wrapping or
543 * window shrinking. In that case, the scroll must be moved to
544 * make it visible.
545 */
546 if (fm.nfiles > HEIGHT) {
547 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
548 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
549 } else
550 SCROLL = 0;
551 marking = !strcmp(CWD, fm.marks.dirpath);
552 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
553 ishidden = ENAME(j)[0] == '.';
554 if (j == ESEL)
555 wattr_on(fm.window, A_REVERSE, NULL);
556 if (ISLINK(j))
557 wcolor_set(fm.window, RVC_LINK, NULL);
558 else if (ishidden)
559 wcolor_set(fm.window, RVC_HIDDEN, NULL);
560 else if (S_ISREG(EMODE(j))) {
561 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
562 wcolor_set(fm.window, RVC_EXEC, NULL);
563 else
564 wcolor_set(fm.window, RVC_REG, NULL);
565 } else if (S_ISDIR(EMODE(j)))
566 wcolor_set(fm.window, RVC_DIR, NULL);
567 else if (S_ISCHR(EMODE(j)))
568 wcolor_set(fm.window, RVC_CHR, NULL);
569 else if (S_ISBLK(EMODE(j)))
570 wcolor_set(fm.window, RVC_BLK, NULL);
571 else if (S_ISFIFO(EMODE(j)))
572 wcolor_set(fm.window, RVC_FIFO, NULL);
573 else if (S_ISSOCK(EMODE(j)))
574 wcolor_set(fm.window, RVC_SOCK, NULL);
575 if (S_ISDIR(EMODE(j))) {
576 mbstowcs(WBUF, ENAME(j), PATH_MAX);
577 if (ISLINK(j))
578 wcscat(WBUF, L"/");
579 } else {
580 const char *suffix, *suffixes = "BKMGTPEZY";
581 off_t human_size = ESIZE(j) * 10;
582 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
583 int namecols = wcswidth(WBUF, length);
584 for (suffix = suffixes; human_size >= 10240; suffix++)
585 human_size = (human_size + 512) / 1024;
586 if (*suffix == 'B')
587 swprintf(WBUF + length, PATH_MAX - length,
588 L"%*d %c",
589 (int)(COLS - namecols - 6),
590 (int)human_size / 10, *suffix);
591 else
592 swprintf(WBUF + length, PATH_MAX - length,
593 L"%*d.%d %c",
594 (int)(COLS - namecols - 8),
595 (int)human_size / 10,
596 (int)human_size % 10, *suffix);
598 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
599 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
600 if (marking && MARKED(j)) {
601 wcolor_set(fm.window, RVC_MARKS, NULL);
602 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
603 } else
604 mvwaddch(fm.window, i + 1, 1, ' ');
605 if (j == ESEL)
606 wattr_off(fm.window, A_REVERSE, NULL);
608 for (; i < HEIGHT; i++)
609 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
610 if (fm.nfiles > HEIGHT) {
611 int center, height;
612 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
613 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
614 if (!height)
615 height = 1;
616 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
617 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
618 RVS_SCROLLBAR, height);
620 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
621 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
622 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
623 if (!fm.nfiles)
624 strcpy(BUF2, "0/0");
625 else
626 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
627 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
628 color_set(RVC_STATUS, NULL);
629 mvaddstr(LINES - 1, STATUSPOS, BUF1);
630 wrefresh(fm.window);
633 /* Show a message on the status bar. */
634 static void __attribute__((format(printf, 2, 3)))
635 message(enum color c, const char *fmt, ...)
637 int len, pos;
638 va_list args;
640 va_start(args, fmt);
641 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
642 va_end(args);
643 len = strlen(BUF1);
644 pos = (STATUSPOS - len) / 2;
645 attr_on(A_BOLD, NULL);
646 color_set(c, NULL);
647 mvaddstr(LINES - 1, pos, BUF1);
648 color_set(DEFAULT, NULL);
649 attr_off(A_BOLD, NULL);
652 /* Clear message area, leaving only status info. */
653 static void
654 clear_message()
656 mvhline(LINES - 1, 0, ' ', STATUSPOS);
659 /* Comparison used to sort listing entries. */
660 static int
661 rowcmp(const void *a, const void *b)
663 int isdir1, isdir2, cmpdir;
664 const struct row *r1 = a;
665 const struct row *r2 = b;
666 isdir1 = S_ISDIR(r1->mode);
667 isdir2 = S_ISDIR(r2->mode);
668 cmpdir = isdir2 - isdir1;
669 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
672 /* Get all entries in current working directory. */
673 static int
674 ls(struct row **rowsp, uint8_t flags)
676 DIR *dp;
677 struct dirent *ep;
678 struct stat statbuf;
679 struct row *rows;
680 int i, n;
682 if (!(dp = opendir(".")))
683 return -1;
684 n = -2; /* We don't want the entries "." and "..". */
685 while (readdir(dp))
686 n++;
687 if (n == 0) {
688 closedir(dp);
689 return 0;
691 rewinddir(dp);
692 rows = xmalloc(n * sizeof(*rows));
693 i = 0;
694 while ((ep = readdir(dp))) {
695 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
696 continue;
697 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
698 continue;
699 lstat(ep->d_name, &statbuf);
700 rows[i].islink = S_ISLNK(statbuf.st_mode);
701 stat(ep->d_name, &statbuf);
702 if (S_ISDIR(statbuf.st_mode)) {
703 if (flags & SHOW_DIRS) {
704 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
705 strcpy(rows[i].name, ep->d_name);
706 if (!rows[i].islink)
707 strcat(rows[i].name, "/");
708 rows[i].mode = statbuf.st_mode;
709 i++;
711 } else if (flags & SHOW_FILES) {
712 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
713 strcpy(rows[i].name, ep->d_name);
714 rows[i].size = statbuf.st_size;
715 rows[i].mode = statbuf.st_mode;
716 i++;
719 n = i; /* Ignore unused space in array caused by filters. */
720 qsort(rows, n, sizeof(*rows), rowcmp);
721 closedir(dp);
722 *rowsp = rows;
723 return n;
726 static void
727 free_rows(struct row **rowsp, int nfiles)
729 int i;
731 for (i = 0; i < nfiles; i++)
732 free((*rowsp)[i].name);
733 free(*rowsp);
734 *rowsp = NULL;
737 /* Change working directory to the path in CWD. */
738 static void
739 cd(int reset)
741 int i, j;
743 message(CYAN, "Loading \"%s\"...", CWD);
744 refresh();
745 if (chdir(CWD) == -1) {
746 getcwd(CWD, PATH_MAX - 1);
747 if (CWD[strlen(CWD) - 1] != '/')
748 strcat(CWD, "/");
749 goto done;
751 if (reset)
752 ESEL = SCROLL = 0;
753 if (fm.nfiles)
754 free_rows(&fm.rows, fm.nfiles);
755 fm.nfiles = ls(&fm.rows, FLAGS);
756 if (!strcmp(CWD, fm.marks.dirpath)) {
757 for (i = 0; i < fm.nfiles; i++) {
758 for (j = 0; j < fm.marks.bulk; j++)
759 if (fm.marks.entries[j] &&
760 !strcmp(fm.marks.entries[j], ENAME(i)))
761 break;
762 MARKED(i) = j < fm.marks.bulk;
764 } else
765 for (i = 0; i < fm.nfiles; i++)
766 MARKED(i) = 0;
767 done:
768 clear_message();
769 update_view();
772 /* Select a target entry, if it is present. */
773 static void
774 try_to_sel(const char *target)
776 ESEL = 0;
777 if (!ISDIR(target))
778 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
779 ESEL++;
780 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
781 ESEL++;
784 /* Reload CWD, but try to keep selection. */
785 static void
786 reload()
788 if (fm.nfiles) {
789 strcpy(INPUT, ENAME(ESEL));
790 cd(0);
791 try_to_sel(INPUT);
792 update_view();
793 } else
794 cd(1);
797 static off_t
798 count_dir(const char *path)
800 DIR *dp;
801 struct dirent *ep;
802 struct stat statbuf;
803 char subpath[PATH_MAX];
804 off_t total;
806 if (!(dp = opendir(path)))
807 return 0;
808 total = 0;
809 while ((ep = readdir(dp))) {
810 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
811 continue;
812 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
813 lstat(subpath, &statbuf);
814 if (S_ISDIR(statbuf.st_mode)) {
815 strcat(subpath, "/");
816 total += count_dir(subpath);
817 } else
818 total += statbuf.st_size;
820 closedir(dp);
821 return total;
824 static off_t
825 count_marked()
827 int i;
828 char *entry;
829 off_t total;
830 struct stat statbuf;
832 total = 0;
833 chdir(fm.marks.dirpath);
834 for (i = 0; i < fm.marks.bulk; i++) {
835 entry = fm.marks.entries[i];
836 if (entry) {
837 if (ISDIR(entry)) {
838 total += count_dir(entry);
839 } else {
840 lstat(entry, &statbuf);
841 total += statbuf.st_size;
845 chdir(CWD);
846 return total;
849 /*
850 * Recursively process a source directory using CWD as destination
851 * root. For each node (i.e. directory), do the following:
853 * 1. call pre(destination);
854 * 2. call proc() on every child leaf (i.e. files);
855 * 3. recurse into every child node;
856 * 4. call pos(source).
858 * E.g. to move directory /src/ (and all its contents) inside /dst/:
859 * strcpy(CWD, "/dst/");
860 * process_dir(adddir, movfile, deldir, "/src/");
861 */
862 static int
863 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
865 int ret;
866 DIR *dp;
867 struct dirent *ep;
868 struct stat statbuf;
869 char subpath[PATH_MAX];
871 ret = 0;
872 if (pre) {
873 char dstpath[PATH_MAX];
874 strcpy(dstpath, CWD);
875 strcat(dstpath, path + strlen(fm . marks . dirpath));
876 ret |= pre(dstpath);
878 if (!(dp = opendir(path)))
879 return -1;
880 while ((ep = readdir(dp))) {
881 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
882 continue;
883 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
884 lstat(subpath, &statbuf);
885 if (S_ISDIR(statbuf.st_mode)) {
886 strcat(subpath, "/");
887 ret |= process_dir(pre, proc, pos, subpath);
888 } else
889 ret |= proc(subpath);
891 closedir(dp);
892 if (pos)
893 ret |= pos(path);
894 return ret;
897 /*
898 * Process all marked entries using CWD as destination root. All
899 * marked entries that are directories will be recursively processed.
900 * See process_dir() for details on the parameters.
901 */
902 static void
903 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
904 const char *msg_done)
906 int i, ret;
907 char *entry;
908 char path[PATH_MAX];
910 clear_message();
911 message(CYAN, "%s...", msg_doing);
912 refresh();
913 fm.prog = (struct prog){0, count_marked(), msg_doing};
914 for (i = 0; i < fm.marks.bulk; i++) {
915 entry = fm.marks.entries[i];
916 if (entry) {
917 ret = 0;
918 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
919 entry);
920 if (ISDIR(entry)) {
921 if (!strncmp(path, CWD, strlen(path)))
922 ret = -1;
923 else
924 ret = process_dir(pre, proc, pos, path);
925 } else
926 ret = proc(path);
927 if (!ret) {
928 del_mark(&fm.marks, entry);
929 reload();
933 fm.prog.total = 0;
934 reload();
935 if (!fm.marks.nentries)
936 message(GREEN, "%s all marked entries.", msg_done);
937 else
938 message(RED, "Some errors occured while %s.", msg_doing);
939 RV_ALERT();
942 static void
943 update_progress(off_t delta)
945 int percent;
947 if (!fm.prog.total)
948 return;
949 fm.prog.partial += delta;
950 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
951 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
952 refresh();
955 /* Wrappers for file operations. */
956 static int
957 delfile(const char *path)
959 int ret;
960 struct stat st;
962 ret = lstat(path, &st);
963 if (ret < 0)
964 return ret;
965 update_progress(st.st_size);
966 return unlink(path);
969 static PROCESS deldir = rmdir;
970 static int
971 addfile(const char *path)
973 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
974 int ret;
976 ret = creat(path, 0644);
977 if (ret < 0)
978 return ret;
979 return close(ret);
982 static int
983 cpyfile(const char *srcpath)
985 int src, dst, ret;
986 size_t size;
987 struct stat st;
988 char buf[BUFSIZ];
989 char dstpath[PATH_MAX];
991 strcpy(dstpath, CWD);
992 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
993 ret = lstat(srcpath, &st);
994 if (ret < 0)
995 return ret;
996 if (S_ISLNK(st.st_mode)) {
997 ret = readlink(srcpath, BUF1, BUFLEN - 1);
998 if (ret < 0)
999 return ret;
1000 BUF1[ret] = '\0';
1001 ret = symlink(BUF1, dstpath);
1002 } else {
1003 ret = src = open(srcpath, O_RDONLY);
1004 if (ret < 0)
1005 return ret;
1006 ret = dst = creat(dstpath, st.st_mode);
1007 if (ret < 0)
1008 return ret;
1009 while ((size = read(src, buf, BUFSIZ)) > 0) {
1010 write(dst, buf, size);
1011 update_progress(size);
1012 sync_signals();
1014 close(src);
1015 close(dst);
1016 ret = 0;
1018 return ret;
1021 static int
1022 adddir(const char *path)
1024 int ret;
1025 struct stat st;
1027 ret = stat(CWD, &st);
1028 if (ret < 0)
1029 return ret;
1030 return mkdir(path, st.st_mode);
1033 static int
1034 movfile(const char *srcpath)
1036 int ret;
1037 struct stat st;
1038 char dstpath[PATH_MAX];
1040 strcpy(dstpath, CWD);
1041 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1042 ret = rename(srcpath, dstpath);
1043 if (ret == 0) {
1044 ret = lstat(dstpath, &st);
1045 if (ret < 0)
1046 return ret;
1047 update_progress(st.st_size);
1048 } else if (errno == EXDEV) {
1049 ret = cpyfile(srcpath);
1050 if (ret < 0)
1051 return ret;
1052 ret = unlink(srcpath);
1054 return ret;
1057 static void
1058 start_line_edit(const char *init_input)
1060 curs_set(TRUE);
1061 strncpy(INPUT, init_input, BUFLEN);
1062 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1063 fm.edit.right = BUFLEN - 1;
1064 fm.edit.buffer[BUFLEN] = L'\0';
1065 fm.edit_scroll = 0;
1068 /* Read input and change editing state accordingly. */
1069 static enum editstate
1070 get_line_edit()
1072 wchar_t eraser, killer, wch;
1073 int ret, length;
1075 ret = fm_get_wch((wint_t *)&wch);
1076 erasewchar(&eraser);
1077 killwchar(&killer);
1078 if (ret == KEY_CODE_YES) {
1079 if (wch == KEY_ENTER) {
1080 curs_set(FALSE);
1081 return CONFIRM;
1082 } else if (wch == KEY_LEFT) {
1083 if (EDIT_CAN_LEFT(fm.edit))
1084 EDIT_LEFT(fm.edit);
1085 } else if (wch == KEY_RIGHT) {
1086 if (EDIT_CAN_RIGHT(fm.edit))
1087 EDIT_RIGHT(fm.edit);
1088 } else if (wch == KEY_UP) {
1089 while (EDIT_CAN_LEFT(fm.edit))
1090 EDIT_LEFT(fm.edit);
1091 } else if (wch == KEY_DOWN) {
1092 while (EDIT_CAN_RIGHT(fm.edit))
1093 EDIT_RIGHT(fm.edit);
1094 } else if (wch == KEY_BACKSPACE) {
1095 if (EDIT_CAN_LEFT(fm.edit))
1096 EDIT_BACKSPACE(fm.edit);
1097 } else if (wch == KEY_DC) {
1098 if (EDIT_CAN_RIGHT(fm.edit))
1099 EDIT_DELETE(fm.edit);
1101 } else {
1102 if (wch == L'\r' || wch == L'\n') {
1103 curs_set(FALSE);
1104 return CONFIRM;
1105 } else if (wch == L'\t') {
1106 curs_set(FALSE);
1107 return CANCEL;
1108 } else if (wch == eraser) {
1109 if (EDIT_CAN_LEFT(fm.edit))
1110 EDIT_BACKSPACE(fm.edit);
1111 } else if (wch == killer) {
1112 EDIT_CLEAR(fm.edit);
1113 clear_message();
1114 } else if (iswprint(wch)) {
1115 if (!EDIT_FULL(fm.edit))
1116 EDIT_INSERT(fm.edit, wch);
1119 /* Encode edit contents in INPUT. */
1120 fm.edit.buffer[fm.edit.left] = L'\0';
1121 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1122 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1123 BUFLEN - length);
1124 return CONTINUE;
1127 /* Update line input on the screen. */
1128 static void
1129 update_input(const char *prompt, enum color c)
1131 int plen, ilen, maxlen;
1133 plen = strlen(prompt);
1134 ilen = mbstowcs(NULL, INPUT, 0);
1135 maxlen = STATUSPOS - plen - 2;
1136 if (ilen - fm.edit_scroll < maxlen)
1137 fm.edit_scroll = MAX(ilen - maxlen, 0);
1138 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1139 fm.edit_scroll = fm.edit.left - maxlen;
1140 else if (fm.edit.left < fm.edit_scroll)
1141 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1142 color_set(RVC_PROMPT, NULL);
1143 mvaddstr(LINES - 1, 0, prompt);
1144 color_set(c, NULL);
1145 mbstowcs(WBUF, INPUT, COLS);
1146 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1147 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1148 ' ');
1149 color_set(DEFAULT, NULL);
1150 if (fm.edit_scroll)
1151 mvaddch(LINES - 1, plen - 1, '<');
1152 if (ilen > fm.edit_scroll + maxlen)
1153 mvaddch(LINES - 1, plen + maxlen, '>');
1154 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1157 static void
1158 cmd_down(void)
1160 if (fm.nfiles)
1161 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1164 static void
1165 cmd_up(void)
1167 if (fm.nfiles)
1168 ESEL = MAX(ESEL - 1, 0);
1171 static void
1172 cmd_scroll_down(void)
1174 if (!fm.nfiles)
1175 return;
1176 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1177 if (fm.nfiles > HEIGHT)
1178 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1181 static void
1182 cmd_scroll_up(void)
1184 if (!fm.nfiles)
1185 return;
1186 ESEL = MAX(ESEL - HEIGHT, 0);
1187 SCROLL = MAX(SCROLL - HEIGHT, 0);
1190 static void
1191 cmd_man(void)
1193 spawn("man", "fm", NULL);
1196 static void
1197 loop(void)
1199 int meta, ch, c;
1200 struct binding {
1201 int ch;
1202 #define K_META 1
1203 #define K_CTRL 2
1204 int chflags;
1205 void (*fn)(void);
1206 #define X_UPDV 1
1207 #define X_QUIT 2
1208 int flags;
1209 } bindings[] = {
1210 {'?', 0, cmd_man, 0},
1211 {'J', 0, cmd_scroll_down, X_UPDV},
1212 {'K', 0, cmd_scroll_up, X_UPDV},
1213 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1214 {'g', K_CTRL, NULL, X_UPDV},
1215 {'j', 0, cmd_down, X_UPDV},
1216 {'k', 0, cmd_up, X_UPDV},
1217 {'n', 0, cmd_down, X_UPDV},
1218 {'n', K_CTRL, cmd_down, X_UPDV},
1219 {'p', 0, cmd_up, X_UPDV},
1220 {'p', K_CTRL, cmd_up, X_UPDV},
1221 {'q', 0, NULL, X_QUIT},
1222 {'v', K_META, cmd_scroll_up, X_UPDV},
1223 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1224 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1225 {KEY_RESIZE, 0, NULL, X_UPDV},
1226 {KEY_RESIZE, K_META, NULL, X_UPDV},
1227 }, *b;
1228 size_t i;
1230 for (;;) {
1231 again:
1232 meta = 0;
1233 ch = fm_getch();
1234 if (ch == '\e') {
1235 meta = 1;
1236 if ((ch = fm_getch()) == '\e') {
1237 meta = 0;
1238 ch = '\e';
1242 clear_message();
1244 for (i = 0; i < nitems(bindings); ++i) {
1245 b = &bindings[i];
1246 c = b->ch;
1247 if (b->chflags & K_CTRL)
1248 c = CTRL(c);
1249 if ((!meta && b->chflags & K_META) || ch != c)
1250 continue;
1252 if (b->flags & X_QUIT)
1253 return;
1254 if (b->fn != NULL)
1255 b->fn();
1256 if (b->flags & X_UPDV)
1257 update_view();
1259 goto again;
1262 message(RED, "%s%s is undefined",
1263 meta ? "M-": "", keyname(ch));
1264 refresh();
1268 int
1269 main(int argc, char *argv[])
1271 int i, ch;
1272 char *program;
1273 char *entry;
1274 const char *key;
1275 const char *clip_path;
1276 DIR *d;
1277 enum editstate edit_stat;
1278 FILE *save_cwd_file = NULL;
1279 FILE *save_marks_file = NULL;
1280 FILE *clip_file;
1282 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1283 switch (ch) {
1284 case 'd':
1285 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1286 err(1, "open %s", optarg);
1287 break;
1288 case 'h':
1289 printf(""
1290 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1291 "Browse current directory or the ones specified.\n"
1292 "\n"
1293 "See fm(1) for more information.\n"
1294 "fm homepage <https://github.com/omar-polo/fm>\n");
1295 return 0;
1296 case 'm':
1297 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1298 err(1, "open %s", optarg);
1299 break;
1300 case 'v':
1301 printf("version: fm %s\n", RV_VERSION);
1302 return 0;
1306 get_user_programs();
1307 init_term();
1308 fm.nfiles = 0;
1309 for (i = 0; i < 10; i++) {
1310 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1311 fm.tabs[i].flags = RV_FLAGS;
1313 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1314 for (i = 1; i < argc && i < 10; i++) {
1315 if ((d = opendir(argv[i]))) {
1316 realpath(argv[i], fm.tabs[i].cwd);
1317 closedir(d);
1318 } else
1319 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1321 getcwd(fm.tabs[i].cwd, PATH_MAX);
1322 for (i++; i < 10; i++)
1323 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1324 for (i = 0; i < 10; i++)
1325 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1326 strcat(fm.tabs[i].cwd, "/");
1327 fm.tab = 1;
1328 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1329 init_marks(&fm.marks);
1330 cd(1);
1331 strcpy(CLIPBOARD, CWD);
1332 if (fm.nfiles > 0)
1333 strcat(CLIPBOARD, ENAME(ESEL));
1335 loop();
1337 if (fm.nfiles)
1338 free_rows(&fm.rows, fm.nfiles);
1339 delwin(fm.window);
1340 if (save_cwd_file != NULL) {
1341 fputs(CWD, save_cwd_file);
1342 fclose(save_cwd_file);
1344 if (save_marks_file != NULL) {
1345 for (i = 0; i < fm.marks.bulk; i++) {
1346 entry = fm.marks.entries[i];
1347 if (entry)
1348 fprintf(save_marks_file, "%s%s\n",
1349 fm.marks.dirpath, entry);
1351 fclose(save_marks_file);
1353 free_marks(&fm.marks);
1354 return 0;