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 <assert.h>
10 #include <ctype.h>
11 #include <curses.h>
12 #include <dirent.h>
13 #include <err.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <getopt.h>
17 #include <libgen.h>
18 #include <limits.h>
19 #include <locale.h>
20 #include <signal.h>
21 #include <stdarg.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <wchar.h>
28 #include <wctype.h>
30 #ifndef FM_SHELL
31 #define FM_SHELL "/bin/sh"
32 #endif
34 #ifndef FM_PAGER
35 #define FM_PAGER "/usr/bin/less"
36 #endif
38 #ifndef FM_ED
39 #define FM_ED "/bin/ed"
40 #endif
42 #include "config.h"
44 struct option opts[] = {
45 {"help", no_argument, NULL, 'h'},
46 {"version", no_argument, NULL, 'v'},
47 {NULL, 0, NULL, 0}
48 };
50 static char clipboard[PATH_MAX];
52 /* String buffers. */
53 #define BUFLEN PATH_MAX
54 static char BUF1[BUFLEN];
55 static char BUF2[BUFLEN];
56 static char INPUT[BUFLEN];
57 static wchar_t WBUF[BUFLEN];
59 /* Paths to external programs. */
60 static char *user_shell;
61 static char *user_pager;
62 static char *user_editor;
63 static char *user_open;
65 /* Listing view parameters. */
66 #define HEIGHT (LINES-4)
67 #define STATUSPOS (COLS-16)
69 /* Listing view flags. */
70 #define SHOW_FILES 0x01u
71 #define SHOW_DIRS 0x02u
72 #define SHOW_HIDDEN 0x04u
74 /* Marks parameters. */
75 #define BULK_INIT 5
76 #define BULK_THRESH 256
78 /* Information associated to each entry in listing. */
79 struct row {
80 char *name;
81 off_t size;
82 mode_t mode;
83 int islink;
84 int marked;
85 };
87 /* Dynamic array of marked entries. */
88 struct marks {
89 char dirpath[PATH_MAX];
90 int bulk;
91 int nentries;
92 char **entries;
93 };
95 /* Line editing state. */
96 struct edit {
97 wchar_t buffer[BUFLEN + 1];
98 int left, right;
99 };
101 /* Each tab only stores the following information. */
102 struct tab {
103 int scroll;
104 int esel;
105 uint8_t flags;
106 char cwd[PATH_MAX];
107 };
109 struct prog {
110 off_t partial;
111 off_t total;
112 const char *msg;
113 };
115 /* Global state. */
116 static struct state {
117 int tab;
118 int nfiles;
119 struct row *rows;
120 WINDOW *window;
121 struct marks marks;
122 struct edit edit;
123 int edit_scroll;
124 volatile sig_atomic_t pending_usr1;
125 volatile sig_atomic_t pending_winch;
126 struct prog prog;
127 struct tab tabs[10];
128 } fm;
130 /* Macros for accessing global state. */
131 #define ENAME(I) fm.rows[I].name
132 #define ESIZE(I) fm.rows[I].size
133 #define EMODE(I) fm.rows[I].mode
134 #define ISLINK(I) fm.rows[I].islink
135 #define MARKED(I) fm.rows[I].marked
136 #define SCROLL fm.tabs[fm.tab].scroll
137 #define ESEL fm.tabs[fm.tab].esel
138 #define FLAGS fm.tabs[fm.tab].flags
139 #define CWD fm.tabs[fm.tab].cwd
141 /* Helpers. */
142 #define MIN(A, B) ((A) < (B) ? (A) : (B))
143 #define MAX(A, B) ((A) > (B) ? (A) : (B))
144 #define ISDIR(E) (strchr((E), '/') != NULL)
145 #define CTRL(x) ((x) & 0x1f)
146 #define nitems(a) (sizeof(a)/sizeof(a[0]))
148 /* Line Editing Macros. */
149 #define EDIT_FULL(E) ((E).left == (E).right)
150 #define EDIT_CAN_LEFT(E) ((E).left)
151 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
152 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
153 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
154 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
155 #define EDIT_BACKSPACE(E) (E).left--
156 #define EDIT_DELETE(E) (E).right++
157 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
159 enum editstate { CONTINUE, CONFIRM, CANCEL };
160 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
162 typedef int (*PROCESS)(const char *path);
164 #ifndef __dead
165 #define __dead __attribute__((noreturn))
166 #endif
168 static inline __dead void
169 quit(const char *reason)
171 int saved_errno;
173 saved_errno = errno;
174 endwin();
175 nocbreak();
176 fflush(stderr);
177 errno = saved_errno;
178 err(1, "%s", reason);
181 static inline void *
182 xmalloc(size_t size)
184 void *d;
186 if ((d = malloc(size)) == NULL)
187 quit("malloc");
188 return d;
191 static inline void *
192 xcalloc(size_t nmemb, size_t size)
194 void *d;
196 if ((d = calloc(nmemb, size)) == NULL)
197 quit("calloc");
198 return d;
201 static inline void *
202 xrealloc(void *p, size_t size)
204 void *d;
206 if ((d = realloc(p, size)) == NULL)
207 quit("realloc");
208 return d;
211 static void
212 init_marks(struct marks *marks)
214 strcpy(marks->dirpath, "");
215 marks->bulk = BULK_INIT;
216 marks->nentries = 0;
217 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
220 /* Unmark all entries. */
221 static void
222 mark_none(struct marks *marks)
224 int i;
226 strcpy(marks->dirpath, "");
227 for (i = 0; i < marks->bulk && marks->nentries; i++)
228 if (marks->entries[i]) {
229 free(marks->entries[i]);
230 marks->entries[i] = NULL;
231 marks->nentries--;
233 if (marks->bulk > BULK_THRESH) {
234 /* Reset bulk to free some memory. */
235 free(marks->entries);
236 marks->bulk = BULK_INIT;
237 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
241 static void
242 add_mark(struct marks *marks, char *dirpath, char *entry)
244 int i;
246 if (!strcmp(marks->dirpath, dirpath)) {
247 /* Append mark to directory. */
248 if (marks->nentries == marks->bulk) {
249 /* Expand bulk to accomodate new entry. */
250 int extra = marks->bulk / 2;
251 marks->bulk += extra; /* bulk *= 1.5; */
252 marks->entries = xrealloc(marks->entries,
253 marks->bulk * sizeof(*marks->entries));
254 memset(&marks->entries[marks->nentries], 0,
255 extra * sizeof(*marks->entries));
256 i = marks->nentries;
257 } else {
258 /* Search for empty slot (there must be one). */
259 for (i = 0; i < marks->bulk; i++)
260 if (!marks->entries[i])
261 break;
263 } else {
264 /* Directory changed. Discard old marks. */
265 mark_none(marks);
266 strcpy(marks->dirpath, dirpath);
267 i = 0;
269 marks->entries[i] = xmalloc(strlen(entry) + 1);
270 strcpy(marks->entries[i], entry);
271 marks->nentries++;
274 static void
275 del_mark(struct marks *marks, char *entry)
277 int i;
279 if (marks->nentries > 1) {
280 for (i = 0; i < marks->bulk; i++)
281 if (marks->entries[i] &&
282 !strcmp(marks->entries[i], entry))
283 break;
284 free(marks->entries[i]);
285 marks->entries[i] = NULL;
286 marks->nentries--;
287 } else
288 mark_none(marks);
291 static void
292 free_marks(struct marks *marks)
294 int i;
296 for (i = 0; i < marks->bulk && marks->nentries; i++)
297 if (marks->entries[i]) {
298 free(marks->entries[i]);
299 marks->nentries--;
301 free(marks->entries);
304 static void
305 handle_usr1(int sig)
307 fm.pending_usr1 = 1;
310 static void
311 handle_winch(int sig)
313 fm.pending_winch = 1;
316 static void
317 enable_handlers(void)
319 struct sigaction sa;
321 memset(&sa, 0, sizeof(struct sigaction));
322 sa.sa_handler = handle_usr1;
323 sigaction(SIGUSR1, &sa, NULL);
324 sa.sa_handler = handle_winch;
325 sigaction(SIGWINCH, &sa, NULL);
328 static void
329 disable_handlers(void)
331 struct sigaction sa;
333 memset(&sa, 0, sizeof(struct sigaction));
334 sa.sa_handler = SIG_DFL;
335 sigaction(SIGUSR1, &sa, NULL);
336 sigaction(SIGWINCH, &sa, NULL);
339 static void reload(void);
340 static void update_view(void);
342 /* Handle any signals received since last call. */
343 static void
344 sync_signals(void)
346 if (fm.pending_usr1) {
347 /* SIGUSR1 received: refresh directory listing. */
348 reload();
349 fm.pending_usr1 = 0;
351 if (fm.pending_winch) {
352 /* SIGWINCH received: resize application accordingly. */
353 delwin(fm.window);
354 endwin();
355 refresh();
356 clear();
357 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
358 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
359 SCROLL = ESEL - HEIGHT;
360 update_view();
361 fm.pending_winch = 0;
365 /*
366 * This function must be used in place of getch(). It handles signals
367 * while waiting for user input.
368 */
369 static int
370 fm_getch()
372 int ch;
374 while ((ch = getch()) == ERR)
375 sync_signals();
376 return ch;
379 /*
380 * This function must be used in place of get_wch(). It handles
381 * signals while waiting for user input.
382 */
383 static int
384 fm_get_wch(wint_t *wch)
386 wint_t ret;
388 while ((ret = get_wch(wch)) == (wint_t)ERR)
389 sync_signals();
390 return ret;
393 /* Get user programs from the environment. */
395 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
396 dst = getenv(#src);
398 static void
399 get_user_programs()
401 FM_ENV(user_shell, SHELL);
402 FM_ENV(user_pager, PAGER);
403 FM_ENV(user_editor, VISUAL);
404 if (!user_editor)
405 FM_ENV(user_editor, EDITOR);
406 FM_ENV(user_open, OPEN);
409 /* Do a fork-exec to external program (e.g. $EDITOR). */
410 static void
411 spawn(const char *argv0, ...)
413 pid_t pid;
414 int status;
415 size_t i;
416 const char *argv[16], *last;
417 va_list ap;
419 memset(argv, 0, sizeof(argv));
421 va_start(ap, argv0);
422 argv[0] = argv0;
423 for (i = 1; i < nitems(argv); ++i) {
424 last = va_arg(ap, const char *);
425 if (last == NULL)
426 break;
427 argv[i] = last;
429 va_end(ap);
431 if (last != NULL)
432 abort();
434 disable_handlers();
435 endwin();
437 switch (pid = fork()) {
438 case -1:
439 quit("fork");
440 case 0: /* child */
441 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
442 execvp(argv[0], (char *const *)argv);
443 quit("execvp");
444 default:
445 waitpid(pid, &status, 0);
446 enable_handlers();
447 kill(getpid(), SIGWINCH);
451 static void
452 shell_escaped_cat(char *buf, char *str, size_t n)
454 char *p = buf + strlen(buf);
455 *p++ = '\'';
456 for (n--; n; n--, str++) {
457 switch (*str) {
458 case '\'':
459 if (n < 4)
460 goto done;
461 strcpy(p, "'\\''");
462 n -= 4;
463 p += 4;
464 break;
465 case '\0':
466 goto done;
467 default:
468 *p = *str;
469 p++;
472 done:
473 strncat(p, "'", n);
476 static int
477 open_with_env(char *program, char *path)
479 if (program) {
480 #ifdef RV_SHELL
481 strncpy(BUF1, program, BUFLEN - 1);
482 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
483 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
484 spawn(RV_SHELL, "-c", BUF1, NULL );
485 #else
486 spawn(program, path, NULL);
487 #endif
488 return 1;
490 return 0;
493 /* Curses setup. */
494 static void
495 init_term()
497 setlocale(LC_ALL, "");
498 initscr();
499 raw();
500 timeout(100); /* For getch(). */
501 noecho();
502 nonl(); /* No NL->CR/NL on output. */
503 intrflush(stdscr, FALSE);
504 keypad(stdscr, TRUE);
505 curs_set(FALSE); /* Hide blinking cursor. */
506 if (has_colors()) {
507 short bg;
508 start_color();
509 #ifdef NCURSES_EXT_FUNCS
510 use_default_colors();
511 bg = -1;
512 #else
513 bg = COLOR_BLACK;
514 #endif
515 init_pair(RED, COLOR_RED, bg);
516 init_pair(GREEN, COLOR_GREEN, bg);
517 init_pair(YELLOW, COLOR_YELLOW, bg);
518 init_pair(BLUE, COLOR_BLUE, bg);
519 init_pair(CYAN, COLOR_CYAN, bg);
520 init_pair(MAGENTA, COLOR_MAGENTA, bg);
521 init_pair(WHITE, COLOR_WHITE, bg);
522 init_pair(BLACK, COLOR_BLACK, bg);
524 atexit((void (*)(void))endwin);
525 enable_handlers();
528 /* Update the listing view. */
529 static void
530 update_view()
532 int i, j;
533 int numsize;
534 int ishidden;
535 int marking;
537 mvhline(0, 0, ' ', COLS);
538 attr_on(A_BOLD, NULL);
539 color_set(RVC_TABNUM, NULL);
540 mvaddch(0, COLS - 2, fm.tab + '0');
541 attr_off(A_BOLD, NULL);
542 if (fm.marks.nentries) {
543 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
544 color_set(RVC_MARKS, NULL);
545 mvaddstr(0, COLS - 3 - numsize, BUF1);
546 } else
547 numsize = -1;
548 color_set(RVC_CWD, NULL);
549 mbstowcs(WBUF, CWD, PATH_MAX);
550 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
551 wcolor_set(fm.window, RVC_BORDER, NULL);
552 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
553 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
555 /*
556 * Selection might not be visible, due to cursor wrapping or
557 * window shrinking. In that case, the scroll must be moved to
558 * make it visible.
559 */
560 if (fm.nfiles > HEIGHT) {
561 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
562 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
563 } else
564 SCROLL = 0;
565 marking = !strcmp(CWD, fm.marks.dirpath);
566 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
567 ishidden = ENAME(j)[0] == '.';
568 if (j == ESEL)
569 wattr_on(fm.window, A_REVERSE, NULL);
570 if (ISLINK(j))
571 wcolor_set(fm.window, RVC_LINK, NULL);
572 else if (ishidden)
573 wcolor_set(fm.window, RVC_HIDDEN, NULL);
574 else if (S_ISREG(EMODE(j))) {
575 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
576 wcolor_set(fm.window, RVC_EXEC, NULL);
577 else
578 wcolor_set(fm.window, RVC_REG, NULL);
579 } else if (S_ISDIR(EMODE(j)))
580 wcolor_set(fm.window, RVC_DIR, NULL);
581 else if (S_ISCHR(EMODE(j)))
582 wcolor_set(fm.window, RVC_CHR, NULL);
583 else if (S_ISBLK(EMODE(j)))
584 wcolor_set(fm.window, RVC_BLK, NULL);
585 else if (S_ISFIFO(EMODE(j)))
586 wcolor_set(fm.window, RVC_FIFO, NULL);
587 else if (S_ISSOCK(EMODE(j)))
588 wcolor_set(fm.window, RVC_SOCK, NULL);
589 if (S_ISDIR(EMODE(j))) {
590 mbstowcs(WBUF, ENAME(j), PATH_MAX);
591 if (ISLINK(j))
592 wcscat(WBUF, L"/");
593 } else {
594 const char *suffix, *suffixes = "BKMGTPEZY";
595 off_t human_size = ESIZE(j) * 10;
596 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
597 int namecols = wcswidth(WBUF, length);
598 for (suffix = suffixes; human_size >= 10240; suffix++)
599 human_size = (human_size + 512) / 1024;
600 if (*suffix == 'B')
601 swprintf(WBUF + length, PATH_MAX - length,
602 L"%*d %c",
603 (int)(COLS - namecols - 6),
604 (int)human_size / 10, *suffix);
605 else
606 swprintf(WBUF + length, PATH_MAX - length,
607 L"%*d.%d %c",
608 (int)(COLS - namecols - 8),
609 (int)human_size / 10,
610 (int)human_size % 10, *suffix);
612 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
613 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
614 if (marking && MARKED(j)) {
615 wcolor_set(fm.window, RVC_MARKS, NULL);
616 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
617 } else
618 mvwaddch(fm.window, i + 1, 1, ' ');
619 if (j == ESEL)
620 wattr_off(fm.window, A_REVERSE, NULL);
622 for (; i < HEIGHT; i++)
623 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
624 if (fm.nfiles > HEIGHT) {
625 int center, height;
626 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
627 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
628 if (!height)
629 height = 1;
630 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
631 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
632 RVS_SCROLLBAR, height);
634 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
635 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
636 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
637 if (!fm.nfiles)
638 strcpy(BUF2, "0/0");
639 else
640 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
641 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
642 color_set(RVC_STATUS, NULL);
643 mvaddstr(LINES - 1, STATUSPOS, BUF1);
644 wrefresh(fm.window);
647 /* Show a message on the status bar. */
648 static void __attribute__((format(printf, 2, 3)))
649 message(enum color c, const char *fmt, ...)
651 int len, pos;
652 va_list args;
654 va_start(args, fmt);
655 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
656 va_end(args);
657 len = strlen(BUF1);
658 pos = (STATUSPOS - len) / 2;
659 attr_on(A_BOLD, NULL);
660 color_set(c, NULL);
661 mvaddstr(LINES - 1, pos, BUF1);
662 color_set(DEFAULT, NULL);
663 attr_off(A_BOLD, NULL);
666 /* Clear message area, leaving only status info. */
667 static void
668 clear_message()
670 mvhline(LINES - 1, 0, ' ', STATUSPOS);
673 /* Comparison used to sort listing entries. */
674 static int
675 rowcmp(const void *a, const void *b)
677 int isdir1, isdir2, cmpdir;
678 const struct row *r1 = a;
679 const struct row *r2 = b;
680 isdir1 = S_ISDIR(r1->mode);
681 isdir2 = S_ISDIR(r2->mode);
682 cmpdir = isdir2 - isdir1;
683 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
686 /* Get all entries in current working directory. */
687 static int
688 ls(struct row **rowsp, uint8_t flags)
690 DIR *dp;
691 struct dirent *ep;
692 struct stat statbuf;
693 struct row *rows;
694 int i, n;
696 if (!(dp = opendir(".")))
697 return -1;
698 n = -2; /* We don't want the entries "." and "..". */
699 while (readdir(dp))
700 n++;
701 if (n == 0) {
702 closedir(dp);
703 return 0;
705 rewinddir(dp);
706 rows = xmalloc(n * sizeof(*rows));
707 i = 0;
708 while ((ep = readdir(dp))) {
709 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
710 continue;
711 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
712 continue;
713 lstat(ep->d_name, &statbuf);
714 rows[i].islink = S_ISLNK(statbuf.st_mode);
715 stat(ep->d_name, &statbuf);
716 if (S_ISDIR(statbuf.st_mode)) {
717 if (flags & SHOW_DIRS) {
718 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
719 strcpy(rows[i].name, ep->d_name);
720 if (!rows[i].islink)
721 strcat(rows[i].name, "/");
722 rows[i].mode = statbuf.st_mode;
723 i++;
725 } else if (flags & SHOW_FILES) {
726 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
727 strcpy(rows[i].name, ep->d_name);
728 rows[i].size = statbuf.st_size;
729 rows[i].mode = statbuf.st_mode;
730 i++;
733 n = i; /* Ignore unused space in array caused by filters. */
734 qsort(rows, n, sizeof(*rows), rowcmp);
735 closedir(dp);
736 *rowsp = rows;
737 return n;
740 static void
741 free_rows(struct row **rowsp, int nfiles)
743 int i;
745 for (i = 0; i < nfiles; i++)
746 free((*rowsp)[i].name);
747 free(*rowsp);
748 *rowsp = NULL;
751 /* Change working directory to the path in CWD. */
752 static void
753 cd(int reset)
755 int i, j;
757 message(CYAN, "Loading \"%s\"...", CWD);
758 refresh();
759 if (chdir(CWD) == -1) {
760 getcwd(CWD, PATH_MAX - 1);
761 if (CWD[strlen(CWD) - 1] != '/')
762 strcat(CWD, "/");
763 goto done;
765 if (reset)
766 ESEL = SCROLL = 0;
767 if (fm.nfiles)
768 free_rows(&fm.rows, fm.nfiles);
769 fm.nfiles = ls(&fm.rows, FLAGS);
770 if (!strcmp(CWD, fm.marks.dirpath)) {
771 for (i = 0; i < fm.nfiles; i++) {
772 for (j = 0; j < fm.marks.bulk; j++)
773 if (fm.marks.entries[j] &&
774 !strcmp(fm.marks.entries[j], ENAME(i)))
775 break;
776 MARKED(i) = j < fm.marks.bulk;
778 } else
779 for (i = 0; i < fm.nfiles; i++)
780 MARKED(i) = 0;
781 done:
782 clear_message();
783 update_view();
786 /* Select a target entry, if it is present. */
787 static void
788 try_to_sel(const char *target)
790 ESEL = 0;
791 if (!ISDIR(target))
792 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
793 ESEL++;
794 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
795 ESEL++;
798 /* Reload CWD, but try to keep selection. */
799 static void
800 reload()
802 if (fm.nfiles) {
803 strcpy(INPUT, ENAME(ESEL));
804 cd(0);
805 try_to_sel(INPUT);
806 update_view();
807 } else
808 cd(1);
811 static off_t
812 count_dir(const char *path)
814 DIR *dp;
815 struct dirent *ep;
816 struct stat statbuf;
817 char subpath[PATH_MAX];
818 off_t total;
820 if (!(dp = opendir(path)))
821 return 0;
822 total = 0;
823 while ((ep = readdir(dp))) {
824 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
825 continue;
826 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
827 lstat(subpath, &statbuf);
828 if (S_ISDIR(statbuf.st_mode)) {
829 strcat(subpath, "/");
830 total += count_dir(subpath);
831 } else
832 total += statbuf.st_size;
834 closedir(dp);
835 return total;
838 static off_t
839 count_marked()
841 int i;
842 char *entry;
843 off_t total;
844 struct stat statbuf;
846 total = 0;
847 chdir(fm.marks.dirpath);
848 for (i = 0; i < fm.marks.bulk; i++) {
849 entry = fm.marks.entries[i];
850 if (entry) {
851 if (ISDIR(entry)) {
852 total += count_dir(entry);
853 } else {
854 lstat(entry, &statbuf);
855 total += statbuf.st_size;
859 chdir(CWD);
860 return total;
863 /*
864 * Recursively process a source directory using CWD as destination
865 * root. For each node (i.e. directory), do the following:
867 * 1. call pre(destination);
868 * 2. call proc() on every child leaf (i.e. files);
869 * 3. recurse into every child node;
870 * 4. call pos(source).
872 * E.g. to move directory /src/ (and all its contents) inside /dst/:
873 * strcpy(CWD, "/dst/");
874 * process_dir(adddir, movfile, deldir, "/src/");
875 */
876 static int
877 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
879 int ret;
880 DIR *dp;
881 struct dirent *ep;
882 struct stat statbuf;
883 char subpath[PATH_MAX];
885 ret = 0;
886 if (pre) {
887 char dstpath[PATH_MAX];
888 strcpy(dstpath, CWD);
889 strcat(dstpath, path + strlen(fm . marks . dirpath));
890 ret |= pre(dstpath);
892 if (!(dp = opendir(path)))
893 return -1;
894 while ((ep = readdir(dp))) {
895 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
896 continue;
897 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
898 lstat(subpath, &statbuf);
899 if (S_ISDIR(statbuf.st_mode)) {
900 strcat(subpath, "/");
901 ret |= process_dir(pre, proc, pos, subpath);
902 } else
903 ret |= proc(subpath);
905 closedir(dp);
906 if (pos)
907 ret |= pos(path);
908 return ret;
911 /*
912 * Process all marked entries using CWD as destination root. All
913 * marked entries that are directories will be recursively processed.
914 * See process_dir() for details on the parameters.
915 */
916 static void
917 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
918 const char *msg_done)
920 int i, ret;
921 char *entry;
922 char path[PATH_MAX];
924 clear_message();
925 message(CYAN, "%s...", msg_doing);
926 refresh();
927 fm.prog = (struct prog){0, count_marked(), msg_doing};
928 for (i = 0; i < fm.marks.bulk; i++) {
929 entry = fm.marks.entries[i];
930 if (entry) {
931 ret = 0;
932 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
933 entry);
934 if (ISDIR(entry)) {
935 if (!strncmp(path, CWD, strlen(path)))
936 ret = -1;
937 else
938 ret = process_dir(pre, proc, pos, path);
939 } else
940 ret = proc(path);
941 if (!ret) {
942 del_mark(&fm.marks, entry);
943 reload();
947 fm.prog.total = 0;
948 reload();
949 if (!fm.marks.nentries)
950 message(GREEN, "%s all marked entries.", msg_done);
951 else
952 message(RED, "Some errors occured while %s.", msg_doing);
953 RV_ALERT();
956 static void
957 update_progress(off_t delta)
959 int percent;
961 if (!fm.prog.total)
962 return;
963 fm.prog.partial += delta;
964 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
965 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
966 refresh();
969 /* Wrappers for file operations. */
970 static int
971 delfile(const char *path)
973 int ret;
974 struct stat st;
976 ret = lstat(path, &st);
977 if (ret < 0)
978 return ret;
979 update_progress(st.st_size);
980 return unlink(path);
983 static PROCESS deldir = rmdir;
984 static int
985 addfile(const char *path)
987 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
988 int ret;
990 ret = creat(path, 0644);
991 if (ret < 0)
992 return ret;
993 return close(ret);
996 static int
997 cpyfile(const char *srcpath)
999 int src, dst, ret;
1000 size_t size;
1001 struct stat st;
1002 char buf[BUFSIZ];
1003 char dstpath[PATH_MAX];
1005 strcpy(dstpath, CWD);
1006 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1007 ret = lstat(srcpath, &st);
1008 if (ret < 0)
1009 return ret;
1010 if (S_ISLNK(st.st_mode)) {
1011 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1012 if (ret < 0)
1013 return ret;
1014 BUF1[ret] = '\0';
1015 ret = symlink(BUF1, dstpath);
1016 } else {
1017 ret = src = open(srcpath, O_RDONLY);
1018 if (ret < 0)
1019 return ret;
1020 ret = dst = creat(dstpath, st.st_mode);
1021 if (ret < 0)
1022 return ret;
1023 while ((size = read(src, buf, BUFSIZ)) > 0) {
1024 write(dst, buf, size);
1025 update_progress(size);
1026 sync_signals();
1028 close(src);
1029 close(dst);
1030 ret = 0;
1032 return ret;
1035 static int
1036 adddir(const char *path)
1038 int ret;
1039 struct stat st;
1041 ret = stat(CWD, &st);
1042 if (ret < 0)
1043 return ret;
1044 return mkdir(path, st.st_mode);
1047 static int
1048 movfile(const char *srcpath)
1050 int ret;
1051 struct stat st;
1052 char dstpath[PATH_MAX];
1054 strcpy(dstpath, CWD);
1055 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1056 ret = rename(srcpath, dstpath);
1057 if (ret == 0) {
1058 ret = lstat(dstpath, &st);
1059 if (ret < 0)
1060 return ret;
1061 update_progress(st.st_size);
1062 } else if (errno == EXDEV) {
1063 ret = cpyfile(srcpath);
1064 if (ret < 0)
1065 return ret;
1066 ret = unlink(srcpath);
1068 return ret;
1071 static void
1072 start_line_edit(const char *init_input)
1074 curs_set(TRUE);
1075 strncpy(INPUT, init_input, BUFLEN);
1076 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1077 fm.edit.right = BUFLEN - 1;
1078 fm.edit.buffer[BUFLEN] = L'\0';
1079 fm.edit_scroll = 0;
1082 /* Read input and change editing state accordingly. */
1083 static enum editstate
1084 get_line_edit()
1086 wchar_t eraser, killer, wch;
1087 int ret, length;
1089 ret = fm_get_wch((wint_t *)&wch);
1090 erasewchar(&eraser);
1091 killwchar(&killer);
1092 if (ret == KEY_CODE_YES) {
1093 if (wch == KEY_ENTER) {
1094 curs_set(FALSE);
1095 return CONFIRM;
1096 } else if (wch == KEY_LEFT) {
1097 if (EDIT_CAN_LEFT(fm.edit))
1098 EDIT_LEFT(fm.edit);
1099 } else if (wch == KEY_RIGHT) {
1100 if (EDIT_CAN_RIGHT(fm.edit))
1101 EDIT_RIGHT(fm.edit);
1102 } else if (wch == KEY_UP) {
1103 while (EDIT_CAN_LEFT(fm.edit))
1104 EDIT_LEFT(fm.edit);
1105 } else if (wch == KEY_DOWN) {
1106 while (EDIT_CAN_RIGHT(fm.edit))
1107 EDIT_RIGHT(fm.edit);
1108 } else if (wch == KEY_BACKSPACE) {
1109 if (EDIT_CAN_LEFT(fm.edit))
1110 EDIT_BACKSPACE(fm.edit);
1111 } else if (wch == KEY_DC) {
1112 if (EDIT_CAN_RIGHT(fm.edit))
1113 EDIT_DELETE(fm.edit);
1115 } else {
1116 if (wch == L'\r' || wch == L'\n') {
1117 curs_set(FALSE);
1118 return CONFIRM;
1119 } else if (wch == L'\t') {
1120 curs_set(FALSE);
1121 return CANCEL;
1122 } else if (wch == eraser) {
1123 if (EDIT_CAN_LEFT(fm.edit))
1124 EDIT_BACKSPACE(fm.edit);
1125 } else if (wch == killer) {
1126 EDIT_CLEAR(fm.edit);
1127 clear_message();
1128 } else if (iswprint(wch)) {
1129 if (!EDIT_FULL(fm.edit))
1130 EDIT_INSERT(fm.edit, wch);
1133 /* Encode edit contents in INPUT. */
1134 fm.edit.buffer[fm.edit.left] = L'\0';
1135 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1136 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1137 BUFLEN - length);
1138 return CONTINUE;
1141 /* Update line input on the screen. */
1142 static void
1143 update_input(const char *prompt, enum color c)
1145 int plen, ilen, maxlen;
1147 plen = strlen(prompt);
1148 ilen = mbstowcs(NULL, INPUT, 0);
1149 maxlen = STATUSPOS - plen - 2;
1150 if (ilen - fm.edit_scroll < maxlen)
1151 fm.edit_scroll = MAX(ilen - maxlen, 0);
1152 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1153 fm.edit_scroll = fm.edit.left - maxlen;
1154 else if (fm.edit.left < fm.edit_scroll)
1155 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1156 color_set(RVC_PROMPT, NULL);
1157 mvaddstr(LINES - 1, 0, prompt);
1158 color_set(c, NULL);
1159 mbstowcs(WBUF, INPUT, COLS);
1160 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1161 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1162 ' ');
1163 color_set(DEFAULT, NULL);
1164 if (fm.edit_scroll)
1165 mvaddch(LINES - 1, plen - 1, '<');
1166 if (ilen > fm.edit_scroll + maxlen)
1167 mvaddch(LINES - 1, plen + maxlen, '>');
1168 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1171 static void
1172 cmd_down(void)
1174 if (fm.nfiles)
1175 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1178 static void
1179 cmd_up(void)
1181 if (fm.nfiles)
1182 ESEL = MAX(ESEL - 1, 0);
1185 static void
1186 cmd_scroll_down(void)
1188 if (!fm.nfiles)
1189 return;
1190 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1191 if (fm.nfiles > HEIGHT)
1192 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1195 static void
1196 cmd_scroll_up(void)
1198 if (!fm.nfiles)
1199 return;
1200 ESEL = MAX(ESEL - HEIGHT, 0);
1201 SCROLL = MAX(SCROLL - HEIGHT, 0);
1204 static void
1205 cmd_man(void)
1207 spawn("man", "fm", NULL);
1210 static void
1211 cmd_jump_top(void)
1213 if (fm.nfiles)
1214 ESEL = 0;
1217 static void
1218 cmd_jump_bottom(void)
1220 if (fm.nfiles)
1221 ESEL = fm.nfiles - 1;
1224 static void
1225 cmd_cd_down(void)
1227 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1228 return;
1229 if (chdir(ENAME(ESEL)) == -1) {
1230 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1231 return;
1233 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1234 cd(1);
1237 static void
1238 cmd_cd_up(void)
1240 char *dirname, first;
1242 if (!strcmp(CWD, "/"))
1243 return;
1245 /* dirname(3) basically */
1246 dirname = strrchr(CWD, '/');
1247 *dirname-- = '\0';
1248 dirname = strrchr(CWD, '/') + 1;
1250 first = dirname[0];
1251 dirname[0] = '\0';
1252 cd(1);
1253 dirname[0] = first;
1254 strlcat(dirname, "/", sizeof(dirname));
1255 try_to_sel(dirname);
1256 dirname[0] = '\0';
1257 if (fm.nfiles > HEIGHT)
1258 SCROLL = ESEL - HEIGHT / 2;
1261 static void
1262 cmd_home(void)
1264 const char *home;
1266 if ((home = getenv("HOME")) == NULL) {
1267 message(RED, "HOME is not defined!");
1268 return;
1271 strlcpy(CWD, home, sizeof(CWD));
1272 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1273 strlcat(CWD, "/", sizeof(CWD));
1274 cd(1);
1277 static void
1278 cmd_copy_path(void)
1280 const char *path;
1281 FILE *f;
1283 if ((path = getenv("CLIP")) == NULL ||
1284 (f = fopen(path, "w")) == NULL) {
1285 /* use internal clipboard */
1286 strlcpy(clipboard, CWD, sizeof(clipboard));
1287 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1288 return;
1291 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1292 fputc('\0', f);
1293 fclose(f);
1296 static void
1297 cmd_paste_path(void)
1299 ssize_t r;
1300 const char *path;
1301 char *nl;
1302 FILE *f;
1303 char p[PATH_MAX];
1305 if ((path = getenv("CLIP")) != NULL &&
1306 (f = fopen(path, "w")) != NULL) {
1307 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1308 fclose(f);
1309 if (r == -1 || r == 0)
1310 goto err;
1311 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1312 goto err;
1315 strlcpy(p, clipboard, sizeof(p));
1316 strlcpy(CWD, clipboard, sizeof(CWD));
1317 if ((nl = strrchr(CWD, '/')) != NULL) {
1318 *nl = '\0';
1319 nl = strrchr(p, '/');
1320 assert(nl != NULL);
1322 if (strcmp(CWD, "/") != 0)
1323 strlcat(CWD, "/", sizeof(CWD));
1324 cd(1);
1325 try_to_sel(nl+1);
1326 return;
1328 err:
1329 memset(clipboard, 0, sizeof(clipboard));
1332 static void
1333 cmd_reload(void)
1335 reload();
1338 static void
1339 cmd_shell(void)
1341 const char *shell;
1343 if ((shell = getenv("SHELL")) == NULL)
1344 shell = FM_SHELL;
1345 spawn(shell, NULL);
1348 static void
1349 cmd_view(void)
1351 const char *pager;
1353 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1354 return;
1356 if ((pager = getenv("PAGER")) == NULL)
1357 pager = FM_PAGER;
1358 spawn(pager, ENAME(ESEL), NULL);
1361 static void
1362 cmd_edit(void)
1364 const char *editor;
1366 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1367 return;
1369 if ((editor = getenv("VISUAL")) == NULL ||
1370 (editor = getenv("EDITOR")) == NULL)
1371 editor = FM_ED;
1373 spawn(editor, ENAME(ESEL), NULL);
1376 static void
1377 loop(void)
1379 int meta, ch, c;
1380 struct binding {
1381 int ch;
1382 #define K_META 1
1383 #define K_CTRL 2
1384 int chflags;
1385 void (*fn)(void);
1386 #define X_UPDV 1
1387 #define X_QUIT 2
1388 int flags;
1389 } bindings[] = {
1390 {'<', K_META, cmd_jump_top, X_UPDV},
1391 {'>', K_META, cmd_jump_bottom, X_UPDV},
1392 {'?', 0, cmd_man, 0},
1393 {'G', 0, cmd_jump_bottom, X_UPDV},
1394 {'H', 0, cmd_home, X_UPDV},
1395 {'J', 0, cmd_scroll_down, X_UPDV},
1396 {'K', 0, cmd_scroll_up, X_UPDV},
1397 {'P', 0, cmd_paste_path, X_UPDV},
1398 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1399 {'Y', 0, cmd_copy_path, X_UPDV},
1400 {'^', 0, cmd_cd_up, X_UPDV},
1401 {'b', 0, cmd_cd_up, X_UPDV},
1402 {'e', 0, cmd_edit, X_UPDV},
1403 {'f', 0, cmd_cd_down, X_UPDV},
1404 {'g', 0, cmd_jump_top, X_UPDV},
1405 {'g', K_CTRL, NULL, X_UPDV},
1406 {'h', 0, cmd_cd_up, X_UPDV},
1407 {'j', 0, cmd_down, X_UPDV},
1408 {'k', 0, cmd_up, X_UPDV},
1409 {'l', 0, cmd_cd_down, X_UPDV},
1410 {'l', K_CTRL, cmd_reload, X_UPDV},
1411 {'n', 0, cmd_down, X_UPDV},
1412 {'n', K_CTRL, cmd_down, X_UPDV},
1413 {'m', K_CTRL, cmd_shell, X_UPDV},
1414 {'p', 0, cmd_up, X_UPDV},
1415 {'p', K_CTRL, cmd_up, X_UPDV},
1416 {'q', 0, NULL, X_QUIT},
1417 {'v', 0, cmd_view, X_UPDV},
1418 {'v', K_META, cmd_scroll_up, X_UPDV},
1419 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1420 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1421 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1422 {KEY_RESIZE, 0, NULL, X_UPDV},
1423 {KEY_RESIZE, K_META, NULL, X_UPDV},
1424 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1425 }, *b;
1426 size_t i;
1428 for (;;) {
1429 again:
1430 meta = 0;
1431 ch = fm_getch();
1432 if (ch == '\e') {
1433 meta = 1;
1434 if ((ch = fm_getch()) == '\e') {
1435 meta = 0;
1436 ch = '\e';
1440 clear_message();
1442 for (i = 0; i < nitems(bindings); ++i) {
1443 b = &bindings[i];
1444 c = b->ch;
1445 if (b->chflags & K_CTRL)
1446 c = CTRL(c);
1447 if ((!meta && b->chflags & K_META) || ch != c)
1448 continue;
1450 if (b->flags & X_QUIT)
1451 return;
1452 if (b->fn != NULL)
1453 b->fn();
1454 if (b->flags & X_UPDV)
1455 update_view();
1457 goto again;
1460 message(RED, "%s%s is undefined",
1461 meta ? "M-": "", keyname(ch));
1462 refresh();
1466 int
1467 main(int argc, char *argv[])
1469 int i, ch;
1470 char *program;
1471 char *entry;
1472 const char *key;
1473 const char *clip_path;
1474 DIR *d;
1475 enum editstate edit_stat;
1476 FILE *save_cwd_file = NULL;
1477 FILE *save_marks_file = NULL;
1478 FILE *clip_file;
1480 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1481 switch (ch) {
1482 case 'd':
1483 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1484 err(1, "open %s", optarg);
1485 break;
1486 case 'h':
1487 printf(""
1488 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1489 "Browse current directory or the ones specified.\n"
1490 "\n"
1491 "See fm(1) for more information.\n"
1492 "fm homepage <https://github.com/omar-polo/fm>\n");
1493 return 0;
1494 case 'm':
1495 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1496 err(1, "open %s", optarg);
1497 break;
1498 case 'v':
1499 printf("version: fm %s\n", RV_VERSION);
1500 return 0;
1504 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1505 err(1, "pledge");
1507 get_user_programs();
1508 init_term();
1509 fm.nfiles = 0;
1510 for (i = 0; i < 10; i++) {
1511 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1512 fm.tabs[i].flags = RV_FLAGS;
1514 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1515 for (i = 1; i < argc && i < 10; i++) {
1516 if ((d = opendir(argv[i]))) {
1517 realpath(argv[i], fm.tabs[i].cwd);
1518 closedir(d);
1519 } else
1520 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1522 getcwd(fm.tabs[i].cwd, PATH_MAX);
1523 for (i++; i < 10; i++)
1524 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1525 for (i = 0; i < 10; i++)
1526 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1527 strcat(fm.tabs[i].cwd, "/");
1528 fm.tab = 1;
1529 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1530 init_marks(&fm.marks);
1531 cd(1);
1532 strlcpy(clipboard, CWD, sizeof(clipboard));
1533 if (fm.nfiles > 0)
1534 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1536 loop();
1538 if (fm.nfiles)
1539 free_rows(&fm.rows, fm.nfiles);
1540 delwin(fm.window);
1541 if (save_cwd_file != NULL) {
1542 fputs(CWD, save_cwd_file);
1543 fclose(save_cwd_file);
1545 if (save_marks_file != NULL) {
1546 for (i = 0; i < fm.marks.bulk; i++) {
1547 entry = fm.marks.entries[i];
1548 if (entry)
1549 fprintf(save_marks_file, "%s%s\n",
1550 fm.marks.dirpath, entry);
1552 fclose(save_marks_file);
1554 free_marks(&fm.marks);
1555 return 0;