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 #include "config.h"
36 struct option opts[] = {
37 {"help", no_argument, NULL, 'h'},
38 {"version", no_argument, NULL, 'v'},
39 {NULL, 0, NULL, 0}
40 };
42 static char clipboard[PATH_MAX];
44 /* String buffers. */
45 #define BUFLEN PATH_MAX
46 static char BUF1[BUFLEN];
47 static char BUF2[BUFLEN];
48 static char INPUT[BUFLEN];
49 static wchar_t WBUF[BUFLEN];
51 /* Paths to external programs. */
52 static char *user_shell;
53 static char *user_pager;
54 static char *user_editor;
55 static char *user_open;
57 /* Listing view parameters. */
58 #define HEIGHT (LINES-4)
59 #define STATUSPOS (COLS-16)
61 /* Listing view flags. */
62 #define SHOW_FILES 0x01u
63 #define SHOW_DIRS 0x02u
64 #define SHOW_HIDDEN 0x04u
66 /* Marks parameters. */
67 #define BULK_INIT 5
68 #define BULK_THRESH 256
70 /* Information associated to each entry in listing. */
71 struct row {
72 char *name;
73 off_t size;
74 mode_t mode;
75 int islink;
76 int marked;
77 };
79 /* Dynamic array of marked entries. */
80 struct marks {
81 char dirpath[PATH_MAX];
82 int bulk;
83 int nentries;
84 char **entries;
85 };
87 /* Line editing state. */
88 struct edit {
89 wchar_t buffer[BUFLEN + 1];
90 int left, right;
91 };
93 /* Each tab only stores the following information. */
94 struct tab {
95 int scroll;
96 int esel;
97 uint8_t flags;
98 char cwd[PATH_MAX];
99 };
101 struct prog {
102 off_t partial;
103 off_t total;
104 const char *msg;
105 };
107 /* Global state. */
108 static struct state {
109 int tab;
110 int nfiles;
111 struct row *rows;
112 WINDOW *window;
113 struct marks marks;
114 struct edit edit;
115 int edit_scroll;
116 volatile sig_atomic_t pending_usr1;
117 volatile sig_atomic_t pending_winch;
118 struct prog prog;
119 struct tab tabs[10];
120 } fm;
122 /* Macros for accessing global state. */
123 #define ENAME(I) fm.rows[I].name
124 #define ESIZE(I) fm.rows[I].size
125 #define EMODE(I) fm.rows[I].mode
126 #define ISLINK(I) fm.rows[I].islink
127 #define MARKED(I) fm.rows[I].marked
128 #define SCROLL fm.tabs[fm.tab].scroll
129 #define ESEL fm.tabs[fm.tab].esel
130 #define FLAGS fm.tabs[fm.tab].flags
131 #define CWD fm.tabs[fm.tab].cwd
133 /* Helpers. */
134 #define MIN(A, B) ((A) < (B) ? (A) : (B))
135 #define MAX(A, B) ((A) > (B) ? (A) : (B))
136 #define ISDIR(E) (strchr((E), '/') != NULL)
137 #define CTRL(x) ((x) & 0x1f)
138 #define nitems(a) (sizeof(a)/sizeof(a[0]))
140 /* Line Editing Macros. */
141 #define EDIT_FULL(E) ((E).left == (E).right)
142 #define EDIT_CAN_LEFT(E) ((E).left)
143 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
144 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
145 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
146 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
147 #define EDIT_BACKSPACE(E) (E).left--
148 #define EDIT_DELETE(E) (E).right++
149 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
151 enum editstate { CONTINUE, CONFIRM, CANCEL };
152 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
154 typedef int (*PROCESS)(const char *path);
156 #ifndef __dead
157 #define __dead __attribute__((noreturn))
158 #endif
160 static inline __dead void
161 quit(const char *reason)
163 int saved_errno;
165 saved_errno = errno;
166 endwin();
167 nocbreak();
168 fflush(stderr);
169 errno = saved_errno;
170 err(1, "%s", reason);
173 static inline void *
174 xmalloc(size_t size)
176 void *d;
178 if ((d = malloc(size)) == NULL)
179 quit("malloc");
180 return d;
183 static inline void *
184 xcalloc(size_t nmemb, size_t size)
186 void *d;
188 if ((d = calloc(nmemb, size)) == NULL)
189 quit("calloc");
190 return d;
193 static inline void *
194 xrealloc(void *p, size_t size)
196 void *d;
198 if ((d = realloc(p, size)) == NULL)
199 quit("realloc");
200 return d;
203 static void
204 init_marks(struct marks *marks)
206 strcpy(marks->dirpath, "");
207 marks->bulk = BULK_INIT;
208 marks->nentries = 0;
209 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
212 /* Unmark all entries. */
213 static void
214 mark_none(struct marks *marks)
216 int i;
218 strcpy(marks->dirpath, "");
219 for (i = 0; i < marks->bulk && marks->nentries; i++)
220 if (marks->entries[i]) {
221 free(marks->entries[i]);
222 marks->entries[i] = NULL;
223 marks->nentries--;
225 if (marks->bulk > BULK_THRESH) {
226 /* Reset bulk to free some memory. */
227 free(marks->entries);
228 marks->bulk = BULK_INIT;
229 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
233 static void
234 add_mark(struct marks *marks, char *dirpath, char *entry)
236 int i;
238 if (!strcmp(marks->dirpath, dirpath)) {
239 /* Append mark to directory. */
240 if (marks->nentries == marks->bulk) {
241 /* Expand bulk to accomodate new entry. */
242 int extra = marks->bulk / 2;
243 marks->bulk += extra; /* bulk *= 1.5; */
244 marks->entries = xrealloc(marks->entries,
245 marks->bulk * sizeof(*marks->entries));
246 memset(&marks->entries[marks->nentries], 0,
247 extra * sizeof(*marks->entries));
248 i = marks->nentries;
249 } else {
250 /* Search for empty slot (there must be one). */
251 for (i = 0; i < marks->bulk; i++)
252 if (!marks->entries[i])
253 break;
255 } else {
256 /* Directory changed. Discard old marks. */
257 mark_none(marks);
258 strcpy(marks->dirpath, dirpath);
259 i = 0;
261 marks->entries[i] = xmalloc(strlen(entry) + 1);
262 strcpy(marks->entries[i], entry);
263 marks->nentries++;
266 static void
267 del_mark(struct marks *marks, char *entry)
269 int i;
271 if (marks->nentries > 1) {
272 for (i = 0; i < marks->bulk; i++)
273 if (marks->entries[i] &&
274 !strcmp(marks->entries[i], entry))
275 break;
276 free(marks->entries[i]);
277 marks->entries[i] = NULL;
278 marks->nentries--;
279 } else
280 mark_none(marks);
283 static void
284 free_marks(struct marks *marks)
286 int i;
288 for (i = 0; i < marks->bulk && marks->nentries; i++)
289 if (marks->entries[i]) {
290 free(marks->entries[i]);
291 marks->nentries--;
293 free(marks->entries);
296 static void
297 handle_usr1(int sig)
299 fm.pending_usr1 = 1;
302 static void
303 handle_winch(int sig)
305 fm.pending_winch = 1;
308 static void
309 enable_handlers(void)
311 struct sigaction sa;
313 memset(&sa, 0, sizeof(struct sigaction));
314 sa.sa_handler = handle_usr1;
315 sigaction(SIGUSR1, &sa, NULL);
316 sa.sa_handler = handle_winch;
317 sigaction(SIGWINCH, &sa, NULL);
320 static void
321 disable_handlers(void)
323 struct sigaction sa;
325 memset(&sa, 0, sizeof(struct sigaction));
326 sa.sa_handler = SIG_DFL;
327 sigaction(SIGUSR1, &sa, NULL);
328 sigaction(SIGWINCH, &sa, NULL);
331 static void reload(void);
332 static void update_view(void);
334 /* Handle any signals received since last call. */
335 static void
336 sync_signals(void)
338 if (fm.pending_usr1) {
339 /* SIGUSR1 received: refresh directory listing. */
340 reload();
341 fm.pending_usr1 = 0;
343 if (fm.pending_winch) {
344 /* SIGWINCH received: resize application accordingly. */
345 delwin(fm.window);
346 endwin();
347 refresh();
348 clear();
349 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
350 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
351 SCROLL = ESEL - HEIGHT;
352 update_view();
353 fm.pending_winch = 0;
357 /*
358 * This function must be used in place of getch(). It handles signals
359 * while waiting for user input.
360 */
361 static int
362 fm_getch()
364 int ch;
366 while ((ch = getch()) == ERR)
367 sync_signals();
368 return ch;
371 /*
372 * This function must be used in place of get_wch(). It handles
373 * signals while waiting for user input.
374 */
375 static int
376 fm_get_wch(wint_t *wch)
378 wint_t ret;
380 while ((ret = get_wch(wch)) == (wint_t)ERR)
381 sync_signals();
382 return ret;
385 /* Get user programs from the environment. */
387 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
388 dst = getenv(#src);
390 static void
391 get_user_programs()
393 FM_ENV(user_shell, SHELL);
394 FM_ENV(user_pager, PAGER);
395 FM_ENV(user_editor, VISUAL);
396 if (!user_editor)
397 FM_ENV(user_editor, EDITOR);
398 FM_ENV(user_open, OPEN);
401 /* Do a fork-exec to external program (e.g. $EDITOR). */
402 static void
403 spawn(const char *argv0, ...)
405 pid_t pid;
406 int status;
407 size_t i;
408 const char *argv[16], *last;
409 va_list ap;
411 memset(argv, 0, sizeof(argv));
413 va_start(ap, argv0);
414 argv[0] = argv0;
415 for (i = 1; i < nitems(argv); ++i) {
416 last = va_arg(ap, const char *);
417 if (last == NULL)
418 break;
419 argv[i] = last;
421 va_end(ap);
423 if (last != NULL)
424 abort();
426 disable_handlers();
427 endwin();
429 switch (pid = fork()) {
430 case -1:
431 quit("fork");
432 case 0: /* child */
433 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
434 execvp(argv[0], (char *const *)argv);
435 quit("execvp");
436 default:
437 waitpid(pid, &status, 0);
438 enable_handlers();
439 kill(getpid(), SIGWINCH);
443 static void
444 shell_escaped_cat(char *buf, char *str, size_t n)
446 char *p = buf + strlen(buf);
447 *p++ = '\'';
448 for (n--; n; n--, str++) {
449 switch (*str) {
450 case '\'':
451 if (n < 4)
452 goto done;
453 strcpy(p, "'\\''");
454 n -= 4;
455 p += 4;
456 break;
457 case '\0':
458 goto done;
459 default:
460 *p = *str;
461 p++;
464 done:
465 strncat(p, "'", n);
468 static int
469 open_with_env(char *program, char *path)
471 if (program) {
472 #ifdef RV_SHELL
473 strncpy(BUF1, program, BUFLEN - 1);
474 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
475 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
476 spawn(RV_SHELL, "-c", BUF1, NULL );
477 #else
478 spawn(program, path, NULL);
479 #endif
480 return 1;
482 return 0;
485 /* Curses setup. */
486 static void
487 init_term()
489 setlocale(LC_ALL, "");
490 initscr();
491 raw();
492 timeout(100); /* For getch(). */
493 noecho();
494 nonl(); /* No NL->CR/NL on output. */
495 intrflush(stdscr, FALSE);
496 keypad(stdscr, TRUE);
497 curs_set(FALSE); /* Hide blinking cursor. */
498 if (has_colors()) {
499 short bg;
500 start_color();
501 #ifdef NCURSES_EXT_FUNCS
502 use_default_colors();
503 bg = -1;
504 #else
505 bg = COLOR_BLACK;
506 #endif
507 init_pair(RED, COLOR_RED, bg);
508 init_pair(GREEN, COLOR_GREEN, bg);
509 init_pair(YELLOW, COLOR_YELLOW, bg);
510 init_pair(BLUE, COLOR_BLUE, bg);
511 init_pair(CYAN, COLOR_CYAN, bg);
512 init_pair(MAGENTA, COLOR_MAGENTA, bg);
513 init_pair(WHITE, COLOR_WHITE, bg);
514 init_pair(BLACK, COLOR_BLACK, bg);
516 atexit((void (*)(void))endwin);
517 enable_handlers();
520 /* Update the listing view. */
521 static void
522 update_view()
524 int i, j;
525 int numsize;
526 int ishidden;
527 int marking;
529 mvhline(0, 0, ' ', COLS);
530 attr_on(A_BOLD, NULL);
531 color_set(RVC_TABNUM, NULL);
532 mvaddch(0, COLS - 2, fm.tab + '0');
533 attr_off(A_BOLD, NULL);
534 if (fm.marks.nentries) {
535 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
536 color_set(RVC_MARKS, NULL);
537 mvaddstr(0, COLS - 3 - numsize, BUF1);
538 } else
539 numsize = -1;
540 color_set(RVC_CWD, NULL);
541 mbstowcs(WBUF, CWD, PATH_MAX);
542 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
543 wcolor_set(fm.window, RVC_BORDER, NULL);
544 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
545 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
547 /*
548 * Selection might not be visible, due to cursor wrapping or
549 * window shrinking. In that case, the scroll must be moved to
550 * make it visible.
551 */
552 if (fm.nfiles > HEIGHT) {
553 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
554 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
555 } else
556 SCROLL = 0;
557 marking = !strcmp(CWD, fm.marks.dirpath);
558 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
559 ishidden = ENAME(j)[0] == '.';
560 if (j == ESEL)
561 wattr_on(fm.window, A_REVERSE, NULL);
562 if (ISLINK(j))
563 wcolor_set(fm.window, RVC_LINK, NULL);
564 else if (ishidden)
565 wcolor_set(fm.window, RVC_HIDDEN, NULL);
566 else if (S_ISREG(EMODE(j))) {
567 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
568 wcolor_set(fm.window, RVC_EXEC, NULL);
569 else
570 wcolor_set(fm.window, RVC_REG, NULL);
571 } else if (S_ISDIR(EMODE(j)))
572 wcolor_set(fm.window, RVC_DIR, NULL);
573 else if (S_ISCHR(EMODE(j)))
574 wcolor_set(fm.window, RVC_CHR, NULL);
575 else if (S_ISBLK(EMODE(j)))
576 wcolor_set(fm.window, RVC_BLK, NULL);
577 else if (S_ISFIFO(EMODE(j)))
578 wcolor_set(fm.window, RVC_FIFO, NULL);
579 else if (S_ISSOCK(EMODE(j)))
580 wcolor_set(fm.window, RVC_SOCK, NULL);
581 if (S_ISDIR(EMODE(j))) {
582 mbstowcs(WBUF, ENAME(j), PATH_MAX);
583 if (ISLINK(j))
584 wcscat(WBUF, L"/");
585 } else {
586 const char *suffix, *suffixes = "BKMGTPEZY";
587 off_t human_size = ESIZE(j) * 10;
588 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
589 int namecols = wcswidth(WBUF, length);
590 for (suffix = suffixes; human_size >= 10240; suffix++)
591 human_size = (human_size + 512) / 1024;
592 if (*suffix == 'B')
593 swprintf(WBUF + length, PATH_MAX - length,
594 L"%*d %c",
595 (int)(COLS - namecols - 6),
596 (int)human_size / 10, *suffix);
597 else
598 swprintf(WBUF + length, PATH_MAX - length,
599 L"%*d.%d %c",
600 (int)(COLS - namecols - 8),
601 (int)human_size / 10,
602 (int)human_size % 10, *suffix);
604 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
605 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
606 if (marking && MARKED(j)) {
607 wcolor_set(fm.window, RVC_MARKS, NULL);
608 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
609 } else
610 mvwaddch(fm.window, i + 1, 1, ' ');
611 if (j == ESEL)
612 wattr_off(fm.window, A_REVERSE, NULL);
614 for (; i < HEIGHT; i++)
615 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
616 if (fm.nfiles > HEIGHT) {
617 int center, height;
618 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
619 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
620 if (!height)
621 height = 1;
622 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
623 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
624 RVS_SCROLLBAR, height);
626 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
627 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
628 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
629 if (!fm.nfiles)
630 strcpy(BUF2, "0/0");
631 else
632 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
633 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
634 color_set(RVC_STATUS, NULL);
635 mvaddstr(LINES - 1, STATUSPOS, BUF1);
636 wrefresh(fm.window);
639 /* Show a message on the status bar. */
640 static void __attribute__((format(printf, 2, 3)))
641 message(enum color c, const char *fmt, ...)
643 int len, pos;
644 va_list args;
646 va_start(args, fmt);
647 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
648 va_end(args);
649 len = strlen(BUF1);
650 pos = (STATUSPOS - len) / 2;
651 attr_on(A_BOLD, NULL);
652 color_set(c, NULL);
653 mvaddstr(LINES - 1, pos, BUF1);
654 color_set(DEFAULT, NULL);
655 attr_off(A_BOLD, NULL);
658 /* Clear message area, leaving only status info. */
659 static void
660 clear_message()
662 mvhline(LINES - 1, 0, ' ', STATUSPOS);
665 /* Comparison used to sort listing entries. */
666 static int
667 rowcmp(const void *a, const void *b)
669 int isdir1, isdir2, cmpdir;
670 const struct row *r1 = a;
671 const struct row *r2 = b;
672 isdir1 = S_ISDIR(r1->mode);
673 isdir2 = S_ISDIR(r2->mode);
674 cmpdir = isdir2 - isdir1;
675 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
678 /* Get all entries in current working directory. */
679 static int
680 ls(struct row **rowsp, uint8_t flags)
682 DIR *dp;
683 struct dirent *ep;
684 struct stat statbuf;
685 struct row *rows;
686 int i, n;
688 if (!(dp = opendir(".")))
689 return -1;
690 n = -2; /* We don't want the entries "." and "..". */
691 while (readdir(dp))
692 n++;
693 if (n == 0) {
694 closedir(dp);
695 return 0;
697 rewinddir(dp);
698 rows = xmalloc(n * sizeof(*rows));
699 i = 0;
700 while ((ep = readdir(dp))) {
701 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
702 continue;
703 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
704 continue;
705 lstat(ep->d_name, &statbuf);
706 rows[i].islink = S_ISLNK(statbuf.st_mode);
707 stat(ep->d_name, &statbuf);
708 if (S_ISDIR(statbuf.st_mode)) {
709 if (flags & SHOW_DIRS) {
710 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
711 strcpy(rows[i].name, ep->d_name);
712 if (!rows[i].islink)
713 strcat(rows[i].name, "/");
714 rows[i].mode = statbuf.st_mode;
715 i++;
717 } else if (flags & SHOW_FILES) {
718 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
719 strcpy(rows[i].name, ep->d_name);
720 rows[i].size = statbuf.st_size;
721 rows[i].mode = statbuf.st_mode;
722 i++;
725 n = i; /* Ignore unused space in array caused by filters. */
726 qsort(rows, n, sizeof(*rows), rowcmp);
727 closedir(dp);
728 *rowsp = rows;
729 return n;
732 static void
733 free_rows(struct row **rowsp, int nfiles)
735 int i;
737 for (i = 0; i < nfiles; i++)
738 free((*rowsp)[i].name);
739 free(*rowsp);
740 *rowsp = NULL;
743 /* Change working directory to the path in CWD. */
744 static void
745 cd(int reset)
747 int i, j;
749 message(CYAN, "Loading \"%s\"...", CWD);
750 refresh();
751 if (chdir(CWD) == -1) {
752 getcwd(CWD, PATH_MAX - 1);
753 if (CWD[strlen(CWD) - 1] != '/')
754 strcat(CWD, "/");
755 goto done;
757 if (reset)
758 ESEL = SCROLL = 0;
759 if (fm.nfiles)
760 free_rows(&fm.rows, fm.nfiles);
761 fm.nfiles = ls(&fm.rows, FLAGS);
762 if (!strcmp(CWD, fm.marks.dirpath)) {
763 for (i = 0; i < fm.nfiles; i++) {
764 for (j = 0; j < fm.marks.bulk; j++)
765 if (fm.marks.entries[j] &&
766 !strcmp(fm.marks.entries[j], ENAME(i)))
767 break;
768 MARKED(i) = j < fm.marks.bulk;
770 } else
771 for (i = 0; i < fm.nfiles; i++)
772 MARKED(i) = 0;
773 done:
774 clear_message();
775 update_view();
778 /* Select a target entry, if it is present. */
779 static void
780 try_to_sel(const char *target)
782 ESEL = 0;
783 if (!ISDIR(target))
784 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
785 ESEL++;
786 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
787 ESEL++;
790 /* Reload CWD, but try to keep selection. */
791 static void
792 reload()
794 if (fm.nfiles) {
795 strcpy(INPUT, ENAME(ESEL));
796 cd(0);
797 try_to_sel(INPUT);
798 update_view();
799 } else
800 cd(1);
803 static off_t
804 count_dir(const char *path)
806 DIR *dp;
807 struct dirent *ep;
808 struct stat statbuf;
809 char subpath[PATH_MAX];
810 off_t total;
812 if (!(dp = opendir(path)))
813 return 0;
814 total = 0;
815 while ((ep = readdir(dp))) {
816 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
817 continue;
818 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
819 lstat(subpath, &statbuf);
820 if (S_ISDIR(statbuf.st_mode)) {
821 strcat(subpath, "/");
822 total += count_dir(subpath);
823 } else
824 total += statbuf.st_size;
826 closedir(dp);
827 return total;
830 static off_t
831 count_marked()
833 int i;
834 char *entry;
835 off_t total;
836 struct stat statbuf;
838 total = 0;
839 chdir(fm.marks.dirpath);
840 for (i = 0; i < fm.marks.bulk; i++) {
841 entry = fm.marks.entries[i];
842 if (entry) {
843 if (ISDIR(entry)) {
844 total += count_dir(entry);
845 } else {
846 lstat(entry, &statbuf);
847 total += statbuf.st_size;
851 chdir(CWD);
852 return total;
855 /*
856 * Recursively process a source directory using CWD as destination
857 * root. For each node (i.e. directory), do the following:
859 * 1. call pre(destination);
860 * 2. call proc() on every child leaf (i.e. files);
861 * 3. recurse into every child node;
862 * 4. call pos(source).
864 * E.g. to move directory /src/ (and all its contents) inside /dst/:
865 * strcpy(CWD, "/dst/");
866 * process_dir(adddir, movfile, deldir, "/src/");
867 */
868 static int
869 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
871 int ret;
872 DIR *dp;
873 struct dirent *ep;
874 struct stat statbuf;
875 char subpath[PATH_MAX];
877 ret = 0;
878 if (pre) {
879 char dstpath[PATH_MAX];
880 strcpy(dstpath, CWD);
881 strcat(dstpath, path + strlen(fm . marks . dirpath));
882 ret |= pre(dstpath);
884 if (!(dp = opendir(path)))
885 return -1;
886 while ((ep = readdir(dp))) {
887 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
888 continue;
889 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
890 lstat(subpath, &statbuf);
891 if (S_ISDIR(statbuf.st_mode)) {
892 strcat(subpath, "/");
893 ret |= process_dir(pre, proc, pos, subpath);
894 } else
895 ret |= proc(subpath);
897 closedir(dp);
898 if (pos)
899 ret |= pos(path);
900 return ret;
903 /*
904 * Process all marked entries using CWD as destination root. All
905 * marked entries that are directories will be recursively processed.
906 * See process_dir() for details on the parameters.
907 */
908 static void
909 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
910 const char *msg_done)
912 int i, ret;
913 char *entry;
914 char path[PATH_MAX];
916 clear_message();
917 message(CYAN, "%s...", msg_doing);
918 refresh();
919 fm.prog = (struct prog){0, count_marked(), msg_doing};
920 for (i = 0; i < fm.marks.bulk; i++) {
921 entry = fm.marks.entries[i];
922 if (entry) {
923 ret = 0;
924 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
925 entry);
926 if (ISDIR(entry)) {
927 if (!strncmp(path, CWD, strlen(path)))
928 ret = -1;
929 else
930 ret = process_dir(pre, proc, pos, path);
931 } else
932 ret = proc(path);
933 if (!ret) {
934 del_mark(&fm.marks, entry);
935 reload();
939 fm.prog.total = 0;
940 reload();
941 if (!fm.marks.nentries)
942 message(GREEN, "%s all marked entries.", msg_done);
943 else
944 message(RED, "Some errors occured while %s.", msg_doing);
945 RV_ALERT();
948 static void
949 update_progress(off_t delta)
951 int percent;
953 if (!fm.prog.total)
954 return;
955 fm.prog.partial += delta;
956 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
957 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
958 refresh();
961 /* Wrappers for file operations. */
962 static int
963 delfile(const char *path)
965 int ret;
966 struct stat st;
968 ret = lstat(path, &st);
969 if (ret < 0)
970 return ret;
971 update_progress(st.st_size);
972 return unlink(path);
975 static PROCESS deldir = rmdir;
976 static int
977 addfile(const char *path)
979 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
980 int ret;
982 ret = creat(path, 0644);
983 if (ret < 0)
984 return ret;
985 return close(ret);
988 static int
989 cpyfile(const char *srcpath)
991 int src, dst, ret;
992 size_t size;
993 struct stat st;
994 char buf[BUFSIZ];
995 char dstpath[PATH_MAX];
997 strcpy(dstpath, CWD);
998 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
999 ret = lstat(srcpath, &st);
1000 if (ret < 0)
1001 return ret;
1002 if (S_ISLNK(st.st_mode)) {
1003 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1004 if (ret < 0)
1005 return ret;
1006 BUF1[ret] = '\0';
1007 ret = symlink(BUF1, dstpath);
1008 } else {
1009 ret = src = open(srcpath, O_RDONLY);
1010 if (ret < 0)
1011 return ret;
1012 ret = dst = creat(dstpath, st.st_mode);
1013 if (ret < 0)
1014 return ret;
1015 while ((size = read(src, buf, BUFSIZ)) > 0) {
1016 write(dst, buf, size);
1017 update_progress(size);
1018 sync_signals();
1020 close(src);
1021 close(dst);
1022 ret = 0;
1024 return ret;
1027 static int
1028 adddir(const char *path)
1030 int ret;
1031 struct stat st;
1033 ret = stat(CWD, &st);
1034 if (ret < 0)
1035 return ret;
1036 return mkdir(path, st.st_mode);
1039 static int
1040 movfile(const char *srcpath)
1042 int ret;
1043 struct stat st;
1044 char dstpath[PATH_MAX];
1046 strcpy(dstpath, CWD);
1047 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1048 ret = rename(srcpath, dstpath);
1049 if (ret == 0) {
1050 ret = lstat(dstpath, &st);
1051 if (ret < 0)
1052 return ret;
1053 update_progress(st.st_size);
1054 } else if (errno == EXDEV) {
1055 ret = cpyfile(srcpath);
1056 if (ret < 0)
1057 return ret;
1058 ret = unlink(srcpath);
1060 return ret;
1063 static void
1064 start_line_edit(const char *init_input)
1066 curs_set(TRUE);
1067 strncpy(INPUT, init_input, BUFLEN);
1068 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1069 fm.edit.right = BUFLEN - 1;
1070 fm.edit.buffer[BUFLEN] = L'\0';
1071 fm.edit_scroll = 0;
1074 /* Read input and change editing state accordingly. */
1075 static enum editstate
1076 get_line_edit()
1078 wchar_t eraser, killer, wch;
1079 int ret, length;
1081 ret = fm_get_wch((wint_t *)&wch);
1082 erasewchar(&eraser);
1083 killwchar(&killer);
1084 if (ret == KEY_CODE_YES) {
1085 if (wch == KEY_ENTER) {
1086 curs_set(FALSE);
1087 return CONFIRM;
1088 } else if (wch == KEY_LEFT) {
1089 if (EDIT_CAN_LEFT(fm.edit))
1090 EDIT_LEFT(fm.edit);
1091 } else if (wch == KEY_RIGHT) {
1092 if (EDIT_CAN_RIGHT(fm.edit))
1093 EDIT_RIGHT(fm.edit);
1094 } else if (wch == KEY_UP) {
1095 while (EDIT_CAN_LEFT(fm.edit))
1096 EDIT_LEFT(fm.edit);
1097 } else if (wch == KEY_DOWN) {
1098 while (EDIT_CAN_RIGHT(fm.edit))
1099 EDIT_RIGHT(fm.edit);
1100 } else if (wch == KEY_BACKSPACE) {
1101 if (EDIT_CAN_LEFT(fm.edit))
1102 EDIT_BACKSPACE(fm.edit);
1103 } else if (wch == KEY_DC) {
1104 if (EDIT_CAN_RIGHT(fm.edit))
1105 EDIT_DELETE(fm.edit);
1107 } else {
1108 if (wch == L'\r' || wch == L'\n') {
1109 curs_set(FALSE);
1110 return CONFIRM;
1111 } else if (wch == L'\t') {
1112 curs_set(FALSE);
1113 return CANCEL;
1114 } else if (wch == eraser) {
1115 if (EDIT_CAN_LEFT(fm.edit))
1116 EDIT_BACKSPACE(fm.edit);
1117 } else if (wch == killer) {
1118 EDIT_CLEAR(fm.edit);
1119 clear_message();
1120 } else if (iswprint(wch)) {
1121 if (!EDIT_FULL(fm.edit))
1122 EDIT_INSERT(fm.edit, wch);
1125 /* Encode edit contents in INPUT. */
1126 fm.edit.buffer[fm.edit.left] = L'\0';
1127 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1128 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1129 BUFLEN - length);
1130 return CONTINUE;
1133 /* Update line input on the screen. */
1134 static void
1135 update_input(const char *prompt, enum color c)
1137 int plen, ilen, maxlen;
1139 plen = strlen(prompt);
1140 ilen = mbstowcs(NULL, INPUT, 0);
1141 maxlen = STATUSPOS - plen - 2;
1142 if (ilen - fm.edit_scroll < maxlen)
1143 fm.edit_scroll = MAX(ilen - maxlen, 0);
1144 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1145 fm.edit_scroll = fm.edit.left - maxlen;
1146 else if (fm.edit.left < fm.edit_scroll)
1147 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1148 color_set(RVC_PROMPT, NULL);
1149 mvaddstr(LINES - 1, 0, prompt);
1150 color_set(c, NULL);
1151 mbstowcs(WBUF, INPUT, COLS);
1152 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1153 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1154 ' ');
1155 color_set(DEFAULT, NULL);
1156 if (fm.edit_scroll)
1157 mvaddch(LINES - 1, plen - 1, '<');
1158 if (ilen > fm.edit_scroll + maxlen)
1159 mvaddch(LINES - 1, plen + maxlen, '>');
1160 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1163 static void
1164 cmd_down(void)
1166 if (fm.nfiles)
1167 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1170 static void
1171 cmd_up(void)
1173 if (fm.nfiles)
1174 ESEL = MAX(ESEL - 1, 0);
1177 static void
1178 cmd_scroll_down(void)
1180 if (!fm.nfiles)
1181 return;
1182 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1183 if (fm.nfiles > HEIGHT)
1184 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1187 static void
1188 cmd_scroll_up(void)
1190 if (!fm.nfiles)
1191 return;
1192 ESEL = MAX(ESEL - HEIGHT, 0);
1193 SCROLL = MAX(SCROLL - HEIGHT, 0);
1196 static void
1197 cmd_man(void)
1199 spawn("man", "fm", NULL);
1202 static void
1203 cmd_jump_top(void)
1205 if (fm.nfiles)
1206 ESEL = 0;
1209 static void
1210 cmd_jump_bottom(void)
1212 if (fm.nfiles)
1213 ESEL = fm.nfiles - 1;
1216 static void
1217 cmd_cd_down(void)
1219 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1220 return;
1221 if (chdir(ENAME(ESEL)) == -1) {
1222 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1223 return;
1225 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1226 cd(1);
1229 static void
1230 cmd_cd_up(void)
1232 char *dirname, first;
1234 if (!strcmp(CWD, "/"))
1235 return;
1237 /* dirname(3) basically */
1238 dirname = strrchr(CWD, '/');
1239 *dirname-- = '\0';
1240 dirname = strrchr(CWD, '/') + 1;
1242 first = dirname[0];
1243 dirname[0] = '\0';
1244 cd(1);
1245 dirname[0] = first;
1246 strlcat(dirname, "/", sizeof(dirname));
1247 try_to_sel(dirname);
1248 dirname[0] = '\0';
1249 if (fm.nfiles > HEIGHT)
1250 SCROLL = ESEL - HEIGHT / 2;
1253 static void
1254 cmd_home(void)
1256 const char *home;
1258 if ((home = getenv("HOME")) == NULL) {
1259 message(RED, "HOME is not defined!");
1260 return;
1263 strlcpy(CWD, home, sizeof(CWD));
1264 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1265 strlcat(CWD, "/", sizeof(CWD));
1266 cd(1);
1269 static void
1270 cmd_copy_path(void)
1272 const char *path;
1273 FILE *f;
1275 if ((path = getenv("CLIP")) == NULL ||
1276 (f = fopen(path, "w")) == NULL) {
1277 /* use internal clipboard */
1278 strlcpy(clipboard, CWD, sizeof(clipboard));
1279 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1280 return;
1283 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1284 fputc('\0', f);
1285 fclose(f);
1288 static void
1289 cmd_paste_path(void)
1291 ssize_t r;
1292 const char *path;
1293 char *nl;
1294 FILE *f;
1295 char p[PATH_MAX];
1297 if ((path = getenv("CLIP")) != NULL &&
1298 (f = fopen(path, "w")) != NULL) {
1299 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1300 fclose(f);
1301 if (r == -1 || r == 0)
1302 goto err;
1303 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1304 goto err;
1307 strlcpy(p, clipboard, sizeof(p));
1308 strlcpy(CWD, clipboard, sizeof(CWD));
1309 if ((nl = strrchr(CWD, '/')) != NULL) {
1310 *nl = '\0';
1311 nl = strrchr(p, '/');
1312 assert(nl != NULL);
1314 if (strcmp(CWD, "/") != 0)
1315 strlcat(CWD, "/", sizeof(CWD));
1316 cd(1);
1317 try_to_sel(nl+1);
1318 return;
1320 err:
1321 memset(clipboard, 0, sizeof(clipboard));
1324 static void
1325 cmd_reload(void)
1327 reload();
1330 static void
1331 cmd_shell(void)
1333 const char *shell;
1335 if ((shell = getenv("SHELL")) == NULL)
1336 shell = FM_SHELL;
1337 spawn(shell, NULL);
1340 static void
1341 loop(void)
1343 int meta, ch, c;
1344 struct binding {
1345 int ch;
1346 #define K_META 1
1347 #define K_CTRL 2
1348 int chflags;
1349 void (*fn)(void);
1350 #define X_UPDV 1
1351 #define X_QUIT 2
1352 int flags;
1353 } bindings[] = {
1354 {'<', K_META, cmd_jump_top, X_UPDV},
1355 {'>', K_META, cmd_jump_bottom, X_UPDV},
1356 {'?', 0, cmd_man, 0},
1357 {'G', 0, cmd_jump_bottom, X_UPDV},
1358 {'H', 0, cmd_home, X_UPDV},
1359 {'J', 0, cmd_scroll_down, X_UPDV},
1360 {'K', 0, cmd_scroll_up, X_UPDV},
1361 {'P', 0, cmd_paste_path, X_UPDV},
1362 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1363 {'Y', 0, cmd_copy_path, X_UPDV},
1364 {'^', 0, cmd_cd_up, X_UPDV},
1365 {'b', 0, cmd_cd_up, X_UPDV},
1366 {'f', 0, cmd_cd_down, X_UPDV},
1367 {'g', 0, cmd_jump_top, X_UPDV},
1368 {'g', K_CTRL, NULL, X_UPDV},
1369 {'h', 0, cmd_cd_up, X_UPDV},
1370 {'j', 0, cmd_down, X_UPDV},
1371 {'k', 0, cmd_up, X_UPDV},
1372 {'l', 0, cmd_cd_down, X_UPDV},
1373 {'l', K_CTRL, cmd_reload, X_UPDV},
1374 {'n', 0, cmd_down, X_UPDV},
1375 {'n', K_CTRL, cmd_down, X_UPDV},
1376 {'m', K_CTRL, cmd_shell, X_UPDV},
1377 {'p', 0, cmd_up, X_UPDV},
1378 {'p', K_CTRL, cmd_up, X_UPDV},
1379 {'q', 0, NULL, X_QUIT},
1380 {'v', K_META, cmd_scroll_up, X_UPDV},
1381 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1382 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1383 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1384 {KEY_RESIZE, 0, NULL, X_UPDV},
1385 {KEY_RESIZE, K_META, NULL, X_UPDV},
1386 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1387 }, *b;
1388 size_t i;
1390 for (;;) {
1391 again:
1392 meta = 0;
1393 ch = fm_getch();
1394 if (ch == '\e') {
1395 meta = 1;
1396 if ((ch = fm_getch()) == '\e') {
1397 meta = 0;
1398 ch = '\e';
1402 clear_message();
1404 for (i = 0; i < nitems(bindings); ++i) {
1405 b = &bindings[i];
1406 c = b->ch;
1407 if (b->chflags & K_CTRL)
1408 c = CTRL(c);
1409 if ((!meta && b->chflags & K_META) || ch != c)
1410 continue;
1412 if (b->flags & X_QUIT)
1413 return;
1414 if (b->fn != NULL)
1415 b->fn();
1416 if (b->flags & X_UPDV)
1417 update_view();
1419 goto again;
1422 message(RED, "%s%s is undefined",
1423 meta ? "M-": "", keyname(ch));
1424 refresh();
1428 int
1429 main(int argc, char *argv[])
1431 int i, ch;
1432 char *program;
1433 char *entry;
1434 const char *key;
1435 const char *clip_path;
1436 DIR *d;
1437 enum editstate edit_stat;
1438 FILE *save_cwd_file = NULL;
1439 FILE *save_marks_file = NULL;
1440 FILE *clip_file;
1442 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1443 switch (ch) {
1444 case 'd':
1445 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1446 err(1, "open %s", optarg);
1447 break;
1448 case 'h':
1449 printf(""
1450 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1451 "Browse current directory or the ones specified.\n"
1452 "\n"
1453 "See fm(1) for more information.\n"
1454 "fm homepage <https://github.com/omar-polo/fm>\n");
1455 return 0;
1456 case 'm':
1457 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1458 err(1, "open %s", optarg);
1459 break;
1460 case 'v':
1461 printf("version: fm %s\n", RV_VERSION);
1462 return 0;
1466 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1467 err(1, "pledge");
1469 get_user_programs();
1470 init_term();
1471 fm.nfiles = 0;
1472 for (i = 0; i < 10; i++) {
1473 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1474 fm.tabs[i].flags = RV_FLAGS;
1476 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1477 for (i = 1; i < argc && i < 10; i++) {
1478 if ((d = opendir(argv[i]))) {
1479 realpath(argv[i], fm.tabs[i].cwd);
1480 closedir(d);
1481 } else
1482 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1484 getcwd(fm.tabs[i].cwd, PATH_MAX);
1485 for (i++; i < 10; i++)
1486 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1487 for (i = 0; i < 10; i++)
1488 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1489 strcat(fm.tabs[i].cwd, "/");
1490 fm.tab = 1;
1491 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1492 init_marks(&fm.marks);
1493 cd(1);
1494 strlcpy(clipboard, CWD, sizeof(clipboard));
1495 if (fm.nfiles > 0)
1496 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1498 loop();
1500 if (fm.nfiles)
1501 free_rows(&fm.rows, fm.nfiles);
1502 delwin(fm.window);
1503 if (save_cwd_file != NULL) {
1504 fputs(CWD, save_cwd_file);
1505 fclose(save_cwd_file);
1507 if (save_marks_file != NULL) {
1508 for (i = 0; i < fm.marks.bulk; i++) {
1509 entry = fm.marks.entries[i];
1510 if (entry)
1511 fprintf(save_marks_file, "%s%s\n",
1512 fm.marks.dirpath, entry);
1514 fclose(save_marks_file);
1516 free_marks(&fm.marks);
1517 return 0;