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 #include "config.h"
40 struct option opts[] = {
41 {"help", no_argument, NULL, 'h'},
42 {"version", no_argument, NULL, 'v'},
43 {NULL, 0, NULL, 0}
44 };
46 static char clipboard[PATH_MAX];
48 /* String buffers. */
49 #define BUFLEN PATH_MAX
50 static char BUF1[BUFLEN];
51 static char BUF2[BUFLEN];
52 static char INPUT[BUFLEN];
53 static wchar_t WBUF[BUFLEN];
55 /* Paths to external programs. */
56 static char *user_shell;
57 static char *user_pager;
58 static char *user_editor;
59 static char *user_open;
61 /* Listing view parameters. */
62 #define HEIGHT (LINES-4)
63 #define STATUSPOS (COLS-16)
65 /* Listing view flags. */
66 #define SHOW_FILES 0x01u
67 #define SHOW_DIRS 0x02u
68 #define SHOW_HIDDEN 0x04u
70 /* Marks parameters. */
71 #define BULK_INIT 5
72 #define BULK_THRESH 256
74 /* Information associated to each entry in listing. */
75 struct row {
76 char *name;
77 off_t size;
78 mode_t mode;
79 int islink;
80 int marked;
81 };
83 /* Dynamic array of marked entries. */
84 struct marks {
85 char dirpath[PATH_MAX];
86 int bulk;
87 int nentries;
88 char **entries;
89 };
91 /* Line editing state. */
92 struct edit {
93 wchar_t buffer[BUFLEN + 1];
94 int left, right;
95 };
97 /* Each tab only stores the following information. */
98 struct tab {
99 int scroll;
100 int esel;
101 uint8_t flags;
102 char cwd[PATH_MAX];
103 };
105 struct prog {
106 off_t partial;
107 off_t total;
108 const char *msg;
109 };
111 /* Global state. */
112 static struct state {
113 int tab;
114 int nfiles;
115 struct row *rows;
116 WINDOW *window;
117 struct marks marks;
118 struct edit edit;
119 int edit_scroll;
120 volatile sig_atomic_t pending_usr1;
121 volatile sig_atomic_t pending_winch;
122 struct prog prog;
123 struct tab tabs[10];
124 } fm;
126 /* Macros for accessing global state. */
127 #define ENAME(I) fm.rows[I].name
128 #define ESIZE(I) fm.rows[I].size
129 #define EMODE(I) fm.rows[I].mode
130 #define ISLINK(I) fm.rows[I].islink
131 #define MARKED(I) fm.rows[I].marked
132 #define SCROLL fm.tabs[fm.tab].scroll
133 #define ESEL fm.tabs[fm.tab].esel
134 #define FLAGS fm.tabs[fm.tab].flags
135 #define CWD fm.tabs[fm.tab].cwd
137 /* Helpers. */
138 #define MIN(A, B) ((A) < (B) ? (A) : (B))
139 #define MAX(A, B) ((A) > (B) ? (A) : (B))
140 #define ISDIR(E) (strchr((E), '/') != NULL)
141 #define CTRL(x) ((x) & 0x1f)
142 #define nitems(a) (sizeof(a)/sizeof(a[0]))
144 /* Line Editing Macros. */
145 #define EDIT_FULL(E) ((E).left == (E).right)
146 #define EDIT_CAN_LEFT(E) ((E).left)
147 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
148 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
149 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
150 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
151 #define EDIT_BACKSPACE(E) (E).left--
152 #define EDIT_DELETE(E) (E).right++
153 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
155 enum editstate { CONTINUE, CONFIRM, CANCEL };
156 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
158 typedef int (*PROCESS)(const char *path);
160 #ifndef __dead
161 #define __dead __attribute__((noreturn))
162 #endif
164 static inline __dead void
165 quit(const char *reason)
167 int saved_errno;
169 saved_errno = errno;
170 endwin();
171 nocbreak();
172 fflush(stderr);
173 errno = saved_errno;
174 err(1, "%s", reason);
177 static inline void *
178 xmalloc(size_t size)
180 void *d;
182 if ((d = malloc(size)) == NULL)
183 quit("malloc");
184 return d;
187 static inline void *
188 xcalloc(size_t nmemb, size_t size)
190 void *d;
192 if ((d = calloc(nmemb, size)) == NULL)
193 quit("calloc");
194 return d;
197 static inline void *
198 xrealloc(void *p, size_t size)
200 void *d;
202 if ((d = realloc(p, size)) == NULL)
203 quit("realloc");
204 return d;
207 static void
208 init_marks(struct marks *marks)
210 strcpy(marks->dirpath, "");
211 marks->bulk = BULK_INIT;
212 marks->nentries = 0;
213 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
216 /* Unmark all entries. */
217 static void
218 mark_none(struct marks *marks)
220 int i;
222 strcpy(marks->dirpath, "");
223 for (i = 0; i < marks->bulk && marks->nentries; i++)
224 if (marks->entries[i]) {
225 free(marks->entries[i]);
226 marks->entries[i] = NULL;
227 marks->nentries--;
229 if (marks->bulk > BULK_THRESH) {
230 /* Reset bulk to free some memory. */
231 free(marks->entries);
232 marks->bulk = BULK_INIT;
233 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
237 static void
238 add_mark(struct marks *marks, char *dirpath, char *entry)
240 int i;
242 if (!strcmp(marks->dirpath, dirpath)) {
243 /* Append mark to directory. */
244 if (marks->nentries == marks->bulk) {
245 /* Expand bulk to accomodate new entry. */
246 int extra = marks->bulk / 2;
247 marks->bulk += extra; /* bulk *= 1.5; */
248 marks->entries = xrealloc(marks->entries,
249 marks->bulk * sizeof(*marks->entries));
250 memset(&marks->entries[marks->nentries], 0,
251 extra * sizeof(*marks->entries));
252 i = marks->nentries;
253 } else {
254 /* Search for empty slot (there must be one). */
255 for (i = 0; i < marks->bulk; i++)
256 if (!marks->entries[i])
257 break;
259 } else {
260 /* Directory changed. Discard old marks. */
261 mark_none(marks);
262 strcpy(marks->dirpath, dirpath);
263 i = 0;
265 marks->entries[i] = xmalloc(strlen(entry) + 1);
266 strcpy(marks->entries[i], entry);
267 marks->nentries++;
270 static void
271 del_mark(struct marks *marks, char *entry)
273 int i;
275 if (marks->nentries > 1) {
276 for (i = 0; i < marks->bulk; i++)
277 if (marks->entries[i] &&
278 !strcmp(marks->entries[i], entry))
279 break;
280 free(marks->entries[i]);
281 marks->entries[i] = NULL;
282 marks->nentries--;
283 } else
284 mark_none(marks);
287 static void
288 free_marks(struct marks *marks)
290 int i;
292 for (i = 0; i < marks->bulk && marks->nentries; i++)
293 if (marks->entries[i]) {
294 free(marks->entries[i]);
295 marks->nentries--;
297 free(marks->entries);
300 static void
301 handle_usr1(int sig)
303 fm.pending_usr1 = 1;
306 static void
307 handle_winch(int sig)
309 fm.pending_winch = 1;
312 static void
313 enable_handlers(void)
315 struct sigaction sa;
317 memset(&sa, 0, sizeof(struct sigaction));
318 sa.sa_handler = handle_usr1;
319 sigaction(SIGUSR1, &sa, NULL);
320 sa.sa_handler = handle_winch;
321 sigaction(SIGWINCH, &sa, NULL);
324 static void
325 disable_handlers(void)
327 struct sigaction sa;
329 memset(&sa, 0, sizeof(struct sigaction));
330 sa.sa_handler = SIG_DFL;
331 sigaction(SIGUSR1, &sa, NULL);
332 sigaction(SIGWINCH, &sa, NULL);
335 static void reload(void);
336 static void update_view(void);
338 /* Handle any signals received since last call. */
339 static void
340 sync_signals(void)
342 if (fm.pending_usr1) {
343 /* SIGUSR1 received: refresh directory listing. */
344 reload();
345 fm.pending_usr1 = 0;
347 if (fm.pending_winch) {
348 /* SIGWINCH received: resize application accordingly. */
349 delwin(fm.window);
350 endwin();
351 refresh();
352 clear();
353 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
354 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
355 SCROLL = ESEL - HEIGHT;
356 update_view();
357 fm.pending_winch = 0;
361 /*
362 * This function must be used in place of getch(). It handles signals
363 * while waiting for user input.
364 */
365 static int
366 fm_getch()
368 int ch;
370 while ((ch = getch()) == ERR)
371 sync_signals();
372 return ch;
375 /*
376 * This function must be used in place of get_wch(). It handles
377 * signals while waiting for user input.
378 */
379 static int
380 fm_get_wch(wint_t *wch)
382 wint_t ret;
384 while ((ret = get_wch(wch)) == (wint_t)ERR)
385 sync_signals();
386 return ret;
389 /* Get user programs from the environment. */
391 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
392 dst = getenv(#src);
394 static void
395 get_user_programs()
397 FM_ENV(user_shell, SHELL);
398 FM_ENV(user_pager, PAGER);
399 FM_ENV(user_editor, VISUAL);
400 if (!user_editor)
401 FM_ENV(user_editor, EDITOR);
402 FM_ENV(user_open, OPEN);
405 /* Do a fork-exec to external program (e.g. $EDITOR). */
406 static void
407 spawn(const char *argv0, ...)
409 pid_t pid;
410 int status;
411 size_t i;
412 const char *argv[16], *last;
413 va_list ap;
415 memset(argv, 0, sizeof(argv));
417 va_start(ap, argv0);
418 argv[0] = argv0;
419 for (i = 1; i < nitems(argv); ++i) {
420 last = va_arg(ap, const char *);
421 if (last == NULL)
422 break;
423 argv[i] = last;
425 va_end(ap);
427 if (last != NULL)
428 abort();
430 disable_handlers();
431 endwin();
433 switch (pid = fork()) {
434 case -1:
435 quit("fork");
436 case 0: /* child */
437 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
438 execvp(argv[0], (char *const *)argv);
439 quit("execvp");
440 default:
441 waitpid(pid, &status, 0);
442 enable_handlers();
443 kill(getpid(), SIGWINCH);
447 static void
448 shell_escaped_cat(char *buf, char *str, size_t n)
450 char *p = buf + strlen(buf);
451 *p++ = '\'';
452 for (n--; n; n--, str++) {
453 switch (*str) {
454 case '\'':
455 if (n < 4)
456 goto done;
457 strcpy(p, "'\\''");
458 n -= 4;
459 p += 4;
460 break;
461 case '\0':
462 goto done;
463 default:
464 *p = *str;
465 p++;
468 done:
469 strncat(p, "'", n);
472 static int
473 open_with_env(char *program, char *path)
475 if (program) {
476 #ifdef RV_SHELL
477 strncpy(BUF1, program, BUFLEN - 1);
478 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
479 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
480 spawn(RV_SHELL, "-c", BUF1, NULL );
481 #else
482 spawn(program, path, NULL);
483 #endif
484 return 1;
486 return 0;
489 /* Curses setup. */
490 static void
491 init_term()
493 setlocale(LC_ALL, "");
494 initscr();
495 raw();
496 timeout(100); /* For getch(). */
497 noecho();
498 nonl(); /* No NL->CR/NL on output. */
499 intrflush(stdscr, FALSE);
500 keypad(stdscr, TRUE);
501 curs_set(FALSE); /* Hide blinking cursor. */
502 if (has_colors()) {
503 short bg;
504 start_color();
505 #ifdef NCURSES_EXT_FUNCS
506 use_default_colors();
507 bg = -1;
508 #else
509 bg = COLOR_BLACK;
510 #endif
511 init_pair(RED, COLOR_RED, bg);
512 init_pair(GREEN, COLOR_GREEN, bg);
513 init_pair(YELLOW, COLOR_YELLOW, bg);
514 init_pair(BLUE, COLOR_BLUE, bg);
515 init_pair(CYAN, COLOR_CYAN, bg);
516 init_pair(MAGENTA, COLOR_MAGENTA, bg);
517 init_pair(WHITE, COLOR_WHITE, bg);
518 init_pair(BLACK, COLOR_BLACK, bg);
520 atexit((void (*)(void))endwin);
521 enable_handlers();
524 /* Update the listing view. */
525 static void
526 update_view()
528 int i, j;
529 int numsize;
530 int ishidden;
531 int marking;
533 mvhline(0, 0, ' ', COLS);
534 attr_on(A_BOLD, NULL);
535 color_set(RVC_TABNUM, NULL);
536 mvaddch(0, COLS - 2, fm.tab + '0');
537 attr_off(A_BOLD, NULL);
538 if (fm.marks.nentries) {
539 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
540 color_set(RVC_MARKS, NULL);
541 mvaddstr(0, COLS - 3 - numsize, BUF1);
542 } else
543 numsize = -1;
544 color_set(RVC_CWD, NULL);
545 mbstowcs(WBUF, CWD, PATH_MAX);
546 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
547 wcolor_set(fm.window, RVC_BORDER, NULL);
548 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
549 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
551 /*
552 * Selection might not be visible, due to cursor wrapping or
553 * window shrinking. In that case, the scroll must be moved to
554 * make it visible.
555 */
556 if (fm.nfiles > HEIGHT) {
557 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
558 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
559 } else
560 SCROLL = 0;
561 marking = !strcmp(CWD, fm.marks.dirpath);
562 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
563 ishidden = ENAME(j)[0] == '.';
564 if (j == ESEL)
565 wattr_on(fm.window, A_REVERSE, NULL);
566 if (ISLINK(j))
567 wcolor_set(fm.window, RVC_LINK, NULL);
568 else if (ishidden)
569 wcolor_set(fm.window, RVC_HIDDEN, NULL);
570 else if (S_ISREG(EMODE(j))) {
571 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
572 wcolor_set(fm.window, RVC_EXEC, NULL);
573 else
574 wcolor_set(fm.window, RVC_REG, NULL);
575 } else if (S_ISDIR(EMODE(j)))
576 wcolor_set(fm.window, RVC_DIR, NULL);
577 else if (S_ISCHR(EMODE(j)))
578 wcolor_set(fm.window, RVC_CHR, NULL);
579 else if (S_ISBLK(EMODE(j)))
580 wcolor_set(fm.window, RVC_BLK, NULL);
581 else if (S_ISFIFO(EMODE(j)))
582 wcolor_set(fm.window, RVC_FIFO, NULL);
583 else if (S_ISSOCK(EMODE(j)))
584 wcolor_set(fm.window, RVC_SOCK, NULL);
585 if (S_ISDIR(EMODE(j))) {
586 mbstowcs(WBUF, ENAME(j), PATH_MAX);
587 if (ISLINK(j))
588 wcscat(WBUF, L"/");
589 } else {
590 const char *suffix, *suffixes = "BKMGTPEZY";
591 off_t human_size = ESIZE(j) * 10;
592 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
593 int namecols = wcswidth(WBUF, length);
594 for (suffix = suffixes; human_size >= 10240; suffix++)
595 human_size = (human_size + 512) / 1024;
596 if (*suffix == 'B')
597 swprintf(WBUF + length, PATH_MAX - length,
598 L"%*d %c",
599 (int)(COLS - namecols - 6),
600 (int)human_size / 10, *suffix);
601 else
602 swprintf(WBUF + length, PATH_MAX - length,
603 L"%*d.%d %c",
604 (int)(COLS - namecols - 8),
605 (int)human_size / 10,
606 (int)human_size % 10, *suffix);
608 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
609 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
610 if (marking && MARKED(j)) {
611 wcolor_set(fm.window, RVC_MARKS, NULL);
612 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
613 } else
614 mvwaddch(fm.window, i + 1, 1, ' ');
615 if (j == ESEL)
616 wattr_off(fm.window, A_REVERSE, NULL);
618 for (; i < HEIGHT; i++)
619 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
620 if (fm.nfiles > HEIGHT) {
621 int center, height;
622 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
623 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
624 if (!height)
625 height = 1;
626 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
627 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
628 RVS_SCROLLBAR, height);
630 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
631 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
632 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
633 if (!fm.nfiles)
634 strcpy(BUF2, "0/0");
635 else
636 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
637 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
638 color_set(RVC_STATUS, NULL);
639 mvaddstr(LINES - 1, STATUSPOS, BUF1);
640 wrefresh(fm.window);
643 /* Show a message on the status bar. */
644 static void __attribute__((format(printf, 2, 3)))
645 message(enum color c, const char *fmt, ...)
647 int len, pos;
648 va_list args;
650 va_start(args, fmt);
651 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
652 va_end(args);
653 len = strlen(BUF1);
654 pos = (STATUSPOS - len) / 2;
655 attr_on(A_BOLD, NULL);
656 color_set(c, NULL);
657 mvaddstr(LINES - 1, pos, BUF1);
658 color_set(DEFAULT, NULL);
659 attr_off(A_BOLD, NULL);
662 /* Clear message area, leaving only status info. */
663 static void
664 clear_message()
666 mvhline(LINES - 1, 0, ' ', STATUSPOS);
669 /* Comparison used to sort listing entries. */
670 static int
671 rowcmp(const void *a, const void *b)
673 int isdir1, isdir2, cmpdir;
674 const struct row *r1 = a;
675 const struct row *r2 = b;
676 isdir1 = S_ISDIR(r1->mode);
677 isdir2 = S_ISDIR(r2->mode);
678 cmpdir = isdir2 - isdir1;
679 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
682 /* Get all entries in current working directory. */
683 static int
684 ls(struct row **rowsp, uint8_t flags)
686 DIR *dp;
687 struct dirent *ep;
688 struct stat statbuf;
689 struct row *rows;
690 int i, n;
692 if (!(dp = opendir(".")))
693 return -1;
694 n = -2; /* We don't want the entries "." and "..". */
695 while (readdir(dp))
696 n++;
697 if (n == 0) {
698 closedir(dp);
699 return 0;
701 rewinddir(dp);
702 rows = xmalloc(n * sizeof(*rows));
703 i = 0;
704 while ((ep = readdir(dp))) {
705 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
706 continue;
707 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
708 continue;
709 lstat(ep->d_name, &statbuf);
710 rows[i].islink = S_ISLNK(statbuf.st_mode);
711 stat(ep->d_name, &statbuf);
712 if (S_ISDIR(statbuf.st_mode)) {
713 if (flags & SHOW_DIRS) {
714 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
715 strcpy(rows[i].name, ep->d_name);
716 if (!rows[i].islink)
717 strcat(rows[i].name, "/");
718 rows[i].mode = statbuf.st_mode;
719 i++;
721 } else if (flags & SHOW_FILES) {
722 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
723 strcpy(rows[i].name, ep->d_name);
724 rows[i].size = statbuf.st_size;
725 rows[i].mode = statbuf.st_mode;
726 i++;
729 n = i; /* Ignore unused space in array caused by filters. */
730 qsort(rows, n, sizeof(*rows), rowcmp);
731 closedir(dp);
732 *rowsp = rows;
733 return n;
736 static void
737 free_rows(struct row **rowsp, int nfiles)
739 int i;
741 for (i = 0; i < nfiles; i++)
742 free((*rowsp)[i].name);
743 free(*rowsp);
744 *rowsp = NULL;
747 /* Change working directory to the path in CWD. */
748 static void
749 cd(int reset)
751 int i, j;
753 message(CYAN, "Loading \"%s\"...", CWD);
754 refresh();
755 if (chdir(CWD) == -1) {
756 getcwd(CWD, PATH_MAX - 1);
757 if (CWD[strlen(CWD) - 1] != '/')
758 strcat(CWD, "/");
759 goto done;
761 if (reset)
762 ESEL = SCROLL = 0;
763 if (fm.nfiles)
764 free_rows(&fm.rows, fm.nfiles);
765 fm.nfiles = ls(&fm.rows, FLAGS);
766 if (!strcmp(CWD, fm.marks.dirpath)) {
767 for (i = 0; i < fm.nfiles; i++) {
768 for (j = 0; j < fm.marks.bulk; j++)
769 if (fm.marks.entries[j] &&
770 !strcmp(fm.marks.entries[j], ENAME(i)))
771 break;
772 MARKED(i) = j < fm.marks.bulk;
774 } else
775 for (i = 0; i < fm.nfiles; i++)
776 MARKED(i) = 0;
777 done:
778 clear_message();
779 update_view();
782 /* Select a target entry, if it is present. */
783 static void
784 try_to_sel(const char *target)
786 ESEL = 0;
787 if (!ISDIR(target))
788 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
789 ESEL++;
790 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
791 ESEL++;
794 /* Reload CWD, but try to keep selection. */
795 static void
796 reload()
798 if (fm.nfiles) {
799 strcpy(INPUT, ENAME(ESEL));
800 cd(0);
801 try_to_sel(INPUT);
802 update_view();
803 } else
804 cd(1);
807 static off_t
808 count_dir(const char *path)
810 DIR *dp;
811 struct dirent *ep;
812 struct stat statbuf;
813 char subpath[PATH_MAX];
814 off_t total;
816 if (!(dp = opendir(path)))
817 return 0;
818 total = 0;
819 while ((ep = readdir(dp))) {
820 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
821 continue;
822 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
823 lstat(subpath, &statbuf);
824 if (S_ISDIR(statbuf.st_mode)) {
825 strcat(subpath, "/");
826 total += count_dir(subpath);
827 } else
828 total += statbuf.st_size;
830 closedir(dp);
831 return total;
834 static off_t
835 count_marked()
837 int i;
838 char *entry;
839 off_t total;
840 struct stat statbuf;
842 total = 0;
843 chdir(fm.marks.dirpath);
844 for (i = 0; i < fm.marks.bulk; i++) {
845 entry = fm.marks.entries[i];
846 if (entry) {
847 if (ISDIR(entry)) {
848 total += count_dir(entry);
849 } else {
850 lstat(entry, &statbuf);
851 total += statbuf.st_size;
855 chdir(CWD);
856 return total;
859 /*
860 * Recursively process a source directory using CWD as destination
861 * root. For each node (i.e. directory), do the following:
863 * 1. call pre(destination);
864 * 2. call proc() on every child leaf (i.e. files);
865 * 3. recurse into every child node;
866 * 4. call pos(source).
868 * E.g. to move directory /src/ (and all its contents) inside /dst/:
869 * strcpy(CWD, "/dst/");
870 * process_dir(adddir, movfile, deldir, "/src/");
871 */
872 static int
873 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
875 int ret;
876 DIR *dp;
877 struct dirent *ep;
878 struct stat statbuf;
879 char subpath[PATH_MAX];
881 ret = 0;
882 if (pre) {
883 char dstpath[PATH_MAX];
884 strcpy(dstpath, CWD);
885 strcat(dstpath, path + strlen(fm . marks . dirpath));
886 ret |= pre(dstpath);
888 if (!(dp = opendir(path)))
889 return -1;
890 while ((ep = readdir(dp))) {
891 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
892 continue;
893 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
894 lstat(subpath, &statbuf);
895 if (S_ISDIR(statbuf.st_mode)) {
896 strcat(subpath, "/");
897 ret |= process_dir(pre, proc, pos, subpath);
898 } else
899 ret |= proc(subpath);
901 closedir(dp);
902 if (pos)
903 ret |= pos(path);
904 return ret;
907 /*
908 * Process all marked entries using CWD as destination root. All
909 * marked entries that are directories will be recursively processed.
910 * See process_dir() for details on the parameters.
911 */
912 static void
913 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
914 const char *msg_done)
916 int i, ret;
917 char *entry;
918 char path[PATH_MAX];
920 clear_message();
921 message(CYAN, "%s...", msg_doing);
922 refresh();
923 fm.prog = (struct prog){0, count_marked(), msg_doing};
924 for (i = 0; i < fm.marks.bulk; i++) {
925 entry = fm.marks.entries[i];
926 if (entry) {
927 ret = 0;
928 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
929 entry);
930 if (ISDIR(entry)) {
931 if (!strncmp(path, CWD, strlen(path)))
932 ret = -1;
933 else
934 ret = process_dir(pre, proc, pos, path);
935 } else
936 ret = proc(path);
937 if (!ret) {
938 del_mark(&fm.marks, entry);
939 reload();
943 fm.prog.total = 0;
944 reload();
945 if (!fm.marks.nentries)
946 message(GREEN, "%s all marked entries.", msg_done);
947 else
948 message(RED, "Some errors occured while %s.", msg_doing);
949 RV_ALERT();
952 static void
953 update_progress(off_t delta)
955 int percent;
957 if (!fm.prog.total)
958 return;
959 fm.prog.partial += delta;
960 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
961 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
962 refresh();
965 /* Wrappers for file operations. */
966 static int
967 delfile(const char *path)
969 int ret;
970 struct stat st;
972 ret = lstat(path, &st);
973 if (ret < 0)
974 return ret;
975 update_progress(st.st_size);
976 return unlink(path);
979 static PROCESS deldir = rmdir;
980 static int
981 addfile(const char *path)
983 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
984 int ret;
986 ret = creat(path, 0644);
987 if (ret < 0)
988 return ret;
989 return close(ret);
992 static int
993 cpyfile(const char *srcpath)
995 int src, dst, ret;
996 size_t size;
997 struct stat st;
998 char buf[BUFSIZ];
999 char dstpath[PATH_MAX];
1001 strcpy(dstpath, CWD);
1002 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1003 ret = lstat(srcpath, &st);
1004 if (ret < 0)
1005 return ret;
1006 if (S_ISLNK(st.st_mode)) {
1007 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1008 if (ret < 0)
1009 return ret;
1010 BUF1[ret] = '\0';
1011 ret = symlink(BUF1, dstpath);
1012 } else {
1013 ret = src = open(srcpath, O_RDONLY);
1014 if (ret < 0)
1015 return ret;
1016 ret = dst = creat(dstpath, st.st_mode);
1017 if (ret < 0)
1018 return ret;
1019 while ((size = read(src, buf, BUFSIZ)) > 0) {
1020 write(dst, buf, size);
1021 update_progress(size);
1022 sync_signals();
1024 close(src);
1025 close(dst);
1026 ret = 0;
1028 return ret;
1031 static int
1032 adddir(const char *path)
1034 int ret;
1035 struct stat st;
1037 ret = stat(CWD, &st);
1038 if (ret < 0)
1039 return ret;
1040 return mkdir(path, st.st_mode);
1043 static int
1044 movfile(const char *srcpath)
1046 int ret;
1047 struct stat st;
1048 char dstpath[PATH_MAX];
1050 strcpy(dstpath, CWD);
1051 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1052 ret = rename(srcpath, dstpath);
1053 if (ret == 0) {
1054 ret = lstat(dstpath, &st);
1055 if (ret < 0)
1056 return ret;
1057 update_progress(st.st_size);
1058 } else if (errno == EXDEV) {
1059 ret = cpyfile(srcpath);
1060 if (ret < 0)
1061 return ret;
1062 ret = unlink(srcpath);
1064 return ret;
1067 static void
1068 start_line_edit(const char *init_input)
1070 curs_set(TRUE);
1071 strncpy(INPUT, init_input, BUFLEN);
1072 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1073 fm.edit.right = BUFLEN - 1;
1074 fm.edit.buffer[BUFLEN] = L'\0';
1075 fm.edit_scroll = 0;
1078 /* Read input and change editing state accordingly. */
1079 static enum editstate
1080 get_line_edit()
1082 wchar_t eraser, killer, wch;
1083 int ret, length;
1085 ret = fm_get_wch((wint_t *)&wch);
1086 erasewchar(&eraser);
1087 killwchar(&killer);
1088 if (ret == KEY_CODE_YES) {
1089 if (wch == KEY_ENTER) {
1090 curs_set(FALSE);
1091 return CONFIRM;
1092 } else if (wch == KEY_LEFT) {
1093 if (EDIT_CAN_LEFT(fm.edit))
1094 EDIT_LEFT(fm.edit);
1095 } else if (wch == KEY_RIGHT) {
1096 if (EDIT_CAN_RIGHT(fm.edit))
1097 EDIT_RIGHT(fm.edit);
1098 } else if (wch == KEY_UP) {
1099 while (EDIT_CAN_LEFT(fm.edit))
1100 EDIT_LEFT(fm.edit);
1101 } else if (wch == KEY_DOWN) {
1102 while (EDIT_CAN_RIGHT(fm.edit))
1103 EDIT_RIGHT(fm.edit);
1104 } else if (wch == KEY_BACKSPACE) {
1105 if (EDIT_CAN_LEFT(fm.edit))
1106 EDIT_BACKSPACE(fm.edit);
1107 } else if (wch == KEY_DC) {
1108 if (EDIT_CAN_RIGHT(fm.edit))
1109 EDIT_DELETE(fm.edit);
1111 } else {
1112 if (wch == L'\r' || wch == L'\n') {
1113 curs_set(FALSE);
1114 return CONFIRM;
1115 } else if (wch == L'\t') {
1116 curs_set(FALSE);
1117 return CANCEL;
1118 } else if (wch == eraser) {
1119 if (EDIT_CAN_LEFT(fm.edit))
1120 EDIT_BACKSPACE(fm.edit);
1121 } else if (wch == killer) {
1122 EDIT_CLEAR(fm.edit);
1123 clear_message();
1124 } else if (iswprint(wch)) {
1125 if (!EDIT_FULL(fm.edit))
1126 EDIT_INSERT(fm.edit, wch);
1129 /* Encode edit contents in INPUT. */
1130 fm.edit.buffer[fm.edit.left] = L'\0';
1131 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1132 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1133 BUFLEN - length);
1134 return CONTINUE;
1137 /* Update line input on the screen. */
1138 static void
1139 update_input(const char *prompt, enum color c)
1141 int plen, ilen, maxlen;
1143 plen = strlen(prompt);
1144 ilen = mbstowcs(NULL, INPUT, 0);
1145 maxlen = STATUSPOS - plen - 2;
1146 if (ilen - fm.edit_scroll < maxlen)
1147 fm.edit_scroll = MAX(ilen - maxlen, 0);
1148 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1149 fm.edit_scroll = fm.edit.left - maxlen;
1150 else if (fm.edit.left < fm.edit_scroll)
1151 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1152 color_set(RVC_PROMPT, NULL);
1153 mvaddstr(LINES - 1, 0, prompt);
1154 color_set(c, NULL);
1155 mbstowcs(WBUF, INPUT, COLS);
1156 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1157 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1158 ' ');
1159 color_set(DEFAULT, NULL);
1160 if (fm.edit_scroll)
1161 mvaddch(LINES - 1, plen - 1, '<');
1162 if (ilen > fm.edit_scroll + maxlen)
1163 mvaddch(LINES - 1, plen + maxlen, '>');
1164 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1167 static void
1168 cmd_down(void)
1170 if (fm.nfiles)
1171 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1174 static void
1175 cmd_up(void)
1177 if (fm.nfiles)
1178 ESEL = MAX(ESEL - 1, 0);
1181 static void
1182 cmd_scroll_down(void)
1184 if (!fm.nfiles)
1185 return;
1186 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1187 if (fm.nfiles > HEIGHT)
1188 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1191 static void
1192 cmd_scroll_up(void)
1194 if (!fm.nfiles)
1195 return;
1196 ESEL = MAX(ESEL - HEIGHT, 0);
1197 SCROLL = MAX(SCROLL - HEIGHT, 0);
1200 static void
1201 cmd_man(void)
1203 spawn("man", "fm", NULL);
1206 static void
1207 cmd_jump_top(void)
1209 if (fm.nfiles)
1210 ESEL = 0;
1213 static void
1214 cmd_jump_bottom(void)
1216 if (fm.nfiles)
1217 ESEL = fm.nfiles - 1;
1220 static void
1221 cmd_cd_down(void)
1223 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1224 return;
1225 if (chdir(ENAME(ESEL)) == -1) {
1226 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1227 return;
1229 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1230 cd(1);
1233 static void
1234 cmd_cd_up(void)
1236 char *dirname, first;
1238 if (!strcmp(CWD, "/"))
1239 return;
1241 /* dirname(3) basically */
1242 dirname = strrchr(CWD, '/');
1243 *dirname-- = '\0';
1244 dirname = strrchr(CWD, '/') + 1;
1246 first = dirname[0];
1247 dirname[0] = '\0';
1248 cd(1);
1249 dirname[0] = first;
1250 strlcat(dirname, "/", sizeof(dirname));
1251 try_to_sel(dirname);
1252 dirname[0] = '\0';
1253 if (fm.nfiles > HEIGHT)
1254 SCROLL = ESEL - HEIGHT / 2;
1257 static void
1258 cmd_home(void)
1260 const char *home;
1262 if ((home = getenv("HOME")) == NULL) {
1263 message(RED, "HOME is not defined!");
1264 return;
1267 strlcpy(CWD, home, sizeof(CWD));
1268 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1269 strlcat(CWD, "/", sizeof(CWD));
1270 cd(1);
1273 static void
1274 cmd_copy_path(void)
1276 const char *path;
1277 FILE *f;
1279 if ((path = getenv("CLIP")) == NULL ||
1280 (f = fopen(path, "w")) == NULL) {
1281 /* use internal clipboard */
1282 strlcpy(clipboard, CWD, sizeof(clipboard));
1283 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1284 return;
1287 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1288 fputc('\0', f);
1289 fclose(f);
1292 static void
1293 cmd_paste_path(void)
1295 ssize_t r;
1296 const char *path;
1297 char *nl;
1298 FILE *f;
1299 char p[PATH_MAX];
1301 if ((path = getenv("CLIP")) != NULL &&
1302 (f = fopen(path, "w")) != NULL) {
1303 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1304 fclose(f);
1305 if (r == -1 || r == 0)
1306 goto err;
1307 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1308 goto err;
1311 strlcpy(p, clipboard, sizeof(p));
1312 strlcpy(CWD, clipboard, sizeof(CWD));
1313 if ((nl = strrchr(CWD, '/')) != NULL) {
1314 *nl = '\0';
1315 nl = strrchr(p, '/');
1316 assert(nl != NULL);
1318 if (strcmp(CWD, "/") != 0)
1319 strlcat(CWD, "/", sizeof(CWD));
1320 cd(1);
1321 try_to_sel(nl+1);
1322 return;
1324 err:
1325 memset(clipboard, 0, sizeof(clipboard));
1328 static void
1329 cmd_reload(void)
1331 reload();
1334 static void
1335 cmd_shell(void)
1337 const char *shell;
1339 if ((shell = getenv("SHELL")) == NULL)
1340 shell = FM_SHELL;
1341 spawn(shell, NULL);
1344 static void
1345 cmd_view(void)
1347 const char *pager;
1349 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1350 return;
1352 if ((pager = getenv("PAGER")) == NULL)
1353 pager = FM_PAGER;
1354 spawn(pager, ENAME(ESEL), NULL);
1357 static void
1358 loop(void)
1360 int meta, ch, c;
1361 struct binding {
1362 int ch;
1363 #define K_META 1
1364 #define K_CTRL 2
1365 int chflags;
1366 void (*fn)(void);
1367 #define X_UPDV 1
1368 #define X_QUIT 2
1369 int flags;
1370 } bindings[] = {
1371 {'<', K_META, cmd_jump_top, X_UPDV},
1372 {'>', K_META, cmd_jump_bottom, X_UPDV},
1373 {'?', 0, cmd_man, 0},
1374 {'G', 0, cmd_jump_bottom, X_UPDV},
1375 {'H', 0, cmd_home, X_UPDV},
1376 {'J', 0, cmd_scroll_down, X_UPDV},
1377 {'K', 0, cmd_scroll_up, X_UPDV},
1378 {'P', 0, cmd_paste_path, X_UPDV},
1379 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1380 {'Y', 0, cmd_copy_path, X_UPDV},
1381 {'^', 0, cmd_cd_up, X_UPDV},
1382 {'b', 0, cmd_cd_up, X_UPDV},
1383 {'f', 0, cmd_cd_down, X_UPDV},
1384 {'g', 0, cmd_jump_top, X_UPDV},
1385 {'g', K_CTRL, NULL, X_UPDV},
1386 {'h', 0, cmd_cd_up, X_UPDV},
1387 {'j', 0, cmd_down, X_UPDV},
1388 {'k', 0, cmd_up, X_UPDV},
1389 {'l', 0, cmd_cd_down, X_UPDV},
1390 {'l', K_CTRL, cmd_reload, X_UPDV},
1391 {'n', 0, cmd_down, X_UPDV},
1392 {'n', K_CTRL, cmd_down, X_UPDV},
1393 {'m', K_CTRL, cmd_shell, X_UPDV},
1394 {'p', 0, cmd_up, X_UPDV},
1395 {'p', K_CTRL, cmd_up, X_UPDV},
1396 {'q', 0, NULL, X_QUIT},
1397 {'v', 0, cmd_view, X_UPDV},
1398 {'v', K_META, cmd_scroll_up, X_UPDV},
1399 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1400 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1401 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1402 {KEY_RESIZE, 0, NULL, X_UPDV},
1403 {KEY_RESIZE, K_META, NULL, X_UPDV},
1404 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1405 }, *b;
1406 size_t i;
1408 for (;;) {
1409 again:
1410 meta = 0;
1411 ch = fm_getch();
1412 if (ch == '\e') {
1413 meta = 1;
1414 if ((ch = fm_getch()) == '\e') {
1415 meta = 0;
1416 ch = '\e';
1420 clear_message();
1422 for (i = 0; i < nitems(bindings); ++i) {
1423 b = &bindings[i];
1424 c = b->ch;
1425 if (b->chflags & K_CTRL)
1426 c = CTRL(c);
1427 if ((!meta && b->chflags & K_META) || ch != c)
1428 continue;
1430 if (b->flags & X_QUIT)
1431 return;
1432 if (b->fn != NULL)
1433 b->fn();
1434 if (b->flags & X_UPDV)
1435 update_view();
1437 goto again;
1440 message(RED, "%s%s is undefined",
1441 meta ? "M-": "", keyname(ch));
1442 refresh();
1446 int
1447 main(int argc, char *argv[])
1449 int i, ch;
1450 char *program;
1451 char *entry;
1452 const char *key;
1453 const char *clip_path;
1454 DIR *d;
1455 enum editstate edit_stat;
1456 FILE *save_cwd_file = NULL;
1457 FILE *save_marks_file = NULL;
1458 FILE *clip_file;
1460 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1461 switch (ch) {
1462 case 'd':
1463 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1464 err(1, "open %s", optarg);
1465 break;
1466 case 'h':
1467 printf(""
1468 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1469 "Browse current directory or the ones specified.\n"
1470 "\n"
1471 "See fm(1) for more information.\n"
1472 "fm homepage <https://github.com/omar-polo/fm>\n");
1473 return 0;
1474 case 'm':
1475 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1476 err(1, "open %s", optarg);
1477 break;
1478 case 'v':
1479 printf("version: fm %s\n", RV_VERSION);
1480 return 0;
1484 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1485 err(1, "pledge");
1487 get_user_programs();
1488 init_term();
1489 fm.nfiles = 0;
1490 for (i = 0; i < 10; i++) {
1491 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1492 fm.tabs[i].flags = RV_FLAGS;
1494 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1495 for (i = 1; i < argc && i < 10; i++) {
1496 if ((d = opendir(argv[i]))) {
1497 realpath(argv[i], fm.tabs[i].cwd);
1498 closedir(d);
1499 } else
1500 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1502 getcwd(fm.tabs[i].cwd, PATH_MAX);
1503 for (i++; i < 10; i++)
1504 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1505 for (i = 0; i < 10; i++)
1506 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1507 strcat(fm.tabs[i].cwd, "/");
1508 fm.tab = 1;
1509 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1510 init_marks(&fm.marks);
1511 cd(1);
1512 strlcpy(clipboard, CWD, sizeof(clipboard));
1513 if (fm.nfiles > 0)
1514 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1516 loop();
1518 if (fm.nfiles)
1519 free_rows(&fm.rows, fm.nfiles);
1520 delwin(fm.window);
1521 if (save_cwd_file != NULL) {
1522 fputs(CWD, save_cwd_file);
1523 fclose(save_cwd_file);
1525 if (save_marks_file != NULL) {
1526 for (i = 0; i < fm.marks.bulk; i++) {
1527 entry = fm.marks.entries[i];
1528 if (entry)
1529 fprintf(save_marks_file, "%s%s\n",
1530 fm.marks.dirpath, entry);
1532 fclose(save_marks_file);
1534 free_marks(&fm.marks);
1535 return 0;