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 #include "config.h"
32 struct option opts[] = {
33 {"help", no_argument, NULL, 'h'},
34 {"version", no_argument, NULL, 'v'},
35 {NULL, 0, NULL, 0}
36 };
38 static char clipboard[PATH_MAX];
40 /* String buffers. */
41 #define BUFLEN PATH_MAX
42 static char BUF1[BUFLEN];
43 static char BUF2[BUFLEN];
44 static char INPUT[BUFLEN];
45 static wchar_t WBUF[BUFLEN];
47 /* Paths to external programs. */
48 static char *user_shell;
49 static char *user_pager;
50 static char *user_editor;
51 static char *user_open;
53 /* Listing view parameters. */
54 #define HEIGHT (LINES-4)
55 #define STATUSPOS (COLS-16)
57 /* Listing view flags. */
58 #define SHOW_FILES 0x01u
59 #define SHOW_DIRS 0x02u
60 #define SHOW_HIDDEN 0x04u
62 /* Marks parameters. */
63 #define BULK_INIT 5
64 #define BULK_THRESH 256
66 /* Information associated to each entry in listing. */
67 struct row {
68 char *name;
69 off_t size;
70 mode_t mode;
71 int islink;
72 int marked;
73 };
75 /* Dynamic array of marked entries. */
76 struct marks {
77 char dirpath[PATH_MAX];
78 int bulk;
79 int nentries;
80 char **entries;
81 };
83 /* Line editing state. */
84 struct edit {
85 wchar_t buffer[BUFLEN + 1];
86 int left, right;
87 };
89 /* Each tab only stores the following information. */
90 struct tab {
91 int scroll;
92 int esel;
93 uint8_t flags;
94 char cwd[PATH_MAX];
95 };
97 struct prog {
98 off_t partial;
99 off_t total;
100 const char *msg;
101 };
103 /* Global state. */
104 static struct state {
105 int tab;
106 int nfiles;
107 struct row *rows;
108 WINDOW *window;
109 struct marks marks;
110 struct edit edit;
111 int edit_scroll;
112 volatile sig_atomic_t pending_usr1;
113 volatile sig_atomic_t pending_winch;
114 struct prog prog;
115 struct tab tabs[10];
116 } fm;
118 /* Macros for accessing global state. */
119 #define ENAME(I) fm.rows[I].name
120 #define ESIZE(I) fm.rows[I].size
121 #define EMODE(I) fm.rows[I].mode
122 #define ISLINK(I) fm.rows[I].islink
123 #define MARKED(I) fm.rows[I].marked
124 #define SCROLL fm.tabs[fm.tab].scroll
125 #define ESEL fm.tabs[fm.tab].esel
126 #define FLAGS fm.tabs[fm.tab].flags
127 #define CWD fm.tabs[fm.tab].cwd
129 /* Helpers. */
130 #define MIN(A, B) ((A) < (B) ? (A) : (B))
131 #define MAX(A, B) ((A) > (B) ? (A) : (B))
132 #define ISDIR(E) (strchr((E), '/') != NULL)
133 #define CTRL(x) ((x) & 0x1f)
134 #define nitems(a) (sizeof(a)/sizeof(a[0]))
136 /* Line Editing Macros. */
137 #define EDIT_FULL(E) ((E).left == (E).right)
138 #define EDIT_CAN_LEFT(E) ((E).left)
139 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
140 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
141 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
142 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
143 #define EDIT_BACKSPACE(E) (E).left--
144 #define EDIT_DELETE(E) (E).right++
145 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
147 enum editstate { CONTINUE, CONFIRM, CANCEL };
148 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
150 typedef int (*PROCESS)(const char *path);
152 #ifndef __dead
153 #define __dead __attribute__((noreturn))
154 #endif
156 static inline __dead void
157 quit(const char *reason)
159 int saved_errno;
161 saved_errno = errno;
162 endwin();
163 nocbreak();
164 fflush(stderr);
165 errno = saved_errno;
166 err(1, "%s", reason);
169 static inline void *
170 xmalloc(size_t size)
172 void *d;
174 if ((d = malloc(size)) == NULL)
175 quit("malloc");
176 return d;
179 static inline void *
180 xcalloc(size_t nmemb, size_t size)
182 void *d;
184 if ((d = calloc(nmemb, size)) == NULL)
185 quit("calloc");
186 return d;
189 static inline void *
190 xrealloc(void *p, size_t size)
192 void *d;
194 if ((d = realloc(p, size)) == NULL)
195 quit("realloc");
196 return d;
199 static void
200 init_marks(struct marks *marks)
202 strcpy(marks->dirpath, "");
203 marks->bulk = BULK_INIT;
204 marks->nentries = 0;
205 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
208 /* Unmark all entries. */
209 static void
210 mark_none(struct marks *marks)
212 int i;
214 strcpy(marks->dirpath, "");
215 for (i = 0; i < marks->bulk && marks->nentries; i++)
216 if (marks->entries[i]) {
217 free(marks->entries[i]);
218 marks->entries[i] = NULL;
219 marks->nentries--;
221 if (marks->bulk > BULK_THRESH) {
222 /* Reset bulk to free some memory. */
223 free(marks->entries);
224 marks->bulk = BULK_INIT;
225 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
229 static void
230 add_mark(struct marks *marks, char *dirpath, char *entry)
232 int i;
234 if (!strcmp(marks->dirpath, dirpath)) {
235 /* Append mark to directory. */
236 if (marks->nentries == marks->bulk) {
237 /* Expand bulk to accomodate new entry. */
238 int extra = marks->bulk / 2;
239 marks->bulk += extra; /* bulk *= 1.5; */
240 marks->entries = xrealloc(marks->entries,
241 marks->bulk * sizeof(*marks->entries));
242 memset(&marks->entries[marks->nentries], 0,
243 extra * sizeof(*marks->entries));
244 i = marks->nentries;
245 } else {
246 /* Search for empty slot (there must be one). */
247 for (i = 0; i < marks->bulk; i++)
248 if (!marks->entries[i])
249 break;
251 } else {
252 /* Directory changed. Discard old marks. */
253 mark_none(marks);
254 strcpy(marks->dirpath, dirpath);
255 i = 0;
257 marks->entries[i] = xmalloc(strlen(entry) + 1);
258 strcpy(marks->entries[i], entry);
259 marks->nentries++;
262 static void
263 del_mark(struct marks *marks, char *entry)
265 int i;
267 if (marks->nentries > 1) {
268 for (i = 0; i < marks->bulk; i++)
269 if (marks->entries[i] &&
270 !strcmp(marks->entries[i], entry))
271 break;
272 free(marks->entries[i]);
273 marks->entries[i] = NULL;
274 marks->nentries--;
275 } else
276 mark_none(marks);
279 static void
280 free_marks(struct marks *marks)
282 int i;
284 for (i = 0; i < marks->bulk && marks->nentries; i++)
285 if (marks->entries[i]) {
286 free(marks->entries[i]);
287 marks->nentries--;
289 free(marks->entries);
292 static void
293 handle_usr1(int sig)
295 fm.pending_usr1 = 1;
298 static void
299 handle_winch(int sig)
301 fm.pending_winch = 1;
304 static void
305 enable_handlers(void)
307 struct sigaction sa;
309 memset(&sa, 0, sizeof(struct sigaction));
310 sa.sa_handler = handle_usr1;
311 sigaction(SIGUSR1, &sa, NULL);
312 sa.sa_handler = handle_winch;
313 sigaction(SIGWINCH, &sa, NULL);
316 static void
317 disable_handlers(void)
319 struct sigaction sa;
321 memset(&sa, 0, sizeof(struct sigaction));
322 sa.sa_handler = SIG_DFL;
323 sigaction(SIGUSR1, &sa, NULL);
324 sigaction(SIGWINCH, &sa, NULL);
327 static void reload(void);
328 static void update_view(void);
330 /* Handle any signals received since last call. */
331 static void
332 sync_signals(void)
334 if (fm.pending_usr1) {
335 /* SIGUSR1 received: refresh directory listing. */
336 reload();
337 fm.pending_usr1 = 0;
339 if (fm.pending_winch) {
340 /* SIGWINCH received: resize application accordingly. */
341 delwin(fm.window);
342 endwin();
343 refresh();
344 clear();
345 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
346 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
347 SCROLL = ESEL - HEIGHT;
348 update_view();
349 fm.pending_winch = 0;
353 /*
354 * This function must be used in place of getch(). It handles signals
355 * while waiting for user input.
356 */
357 static int
358 fm_getch()
360 int ch;
362 while ((ch = getch()) == ERR)
363 sync_signals();
364 return ch;
367 /*
368 * This function must be used in place of get_wch(). It handles
369 * signals while waiting for user input.
370 */
371 static int
372 fm_get_wch(wint_t *wch)
374 wint_t ret;
376 while ((ret = get_wch(wch)) == (wint_t)ERR)
377 sync_signals();
378 return ret;
381 /* Get user programs from the environment. */
383 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
384 dst = getenv(#src);
386 static void
387 get_user_programs()
389 FM_ENV(user_shell, SHELL);
390 FM_ENV(user_pager, PAGER);
391 FM_ENV(user_editor, VISUAL);
392 if (!user_editor)
393 FM_ENV(user_editor, EDITOR);
394 FM_ENV(user_open, OPEN);
397 /* Do a fork-exec to external program (e.g. $EDITOR). */
398 static void
399 spawn(const char *argv0, ...)
401 pid_t pid;
402 int status;
403 size_t i;
404 const char *argv[16], *last;
405 va_list ap;
407 memset(argv, 0, sizeof(argv));
409 va_start(ap, argv0);
410 argv[0] = argv0;
411 for (i = 1; i < nitems(argv); ++i) {
412 last = va_arg(ap, const char *);
413 if (last == NULL)
414 break;
415 argv[i] = last;
417 va_end(ap);
419 if (last != NULL)
420 abort();
422 disable_handlers();
423 endwin();
425 switch (pid = fork()) {
426 case -1:
427 quit("fork");
428 case 0: /* child */
429 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
430 execvp(argv[0], (char *const *)argv);
431 quit("execvp");
432 default:
433 waitpid(pid, &status, 0);
434 enable_handlers();
435 kill(getpid(), SIGWINCH);
439 static void
440 shell_escaped_cat(char *buf, char *str, size_t n)
442 char *p = buf + strlen(buf);
443 *p++ = '\'';
444 for (n--; n; n--, str++) {
445 switch (*str) {
446 case '\'':
447 if (n < 4)
448 goto done;
449 strcpy(p, "'\\''");
450 n -= 4;
451 p += 4;
452 break;
453 case '\0':
454 goto done;
455 default:
456 *p = *str;
457 p++;
460 done:
461 strncat(p, "'", n);
464 static int
465 open_with_env(char *program, char *path)
467 if (program) {
468 #ifdef RV_SHELL
469 strncpy(BUF1, program, BUFLEN - 1);
470 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
471 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
472 spawn(RV_SHELL, "-c", BUF1, NULL );
473 #else
474 spawn(program, path, NULL);
475 #endif
476 return 1;
478 return 0;
481 /* Curses setup. */
482 static void
483 init_term()
485 setlocale(LC_ALL, "");
486 initscr();
487 raw();
488 timeout(100); /* For getch(). */
489 noecho();
490 nonl(); /* No NL->CR/NL on output. */
491 intrflush(stdscr, FALSE);
492 keypad(stdscr, TRUE);
493 curs_set(FALSE); /* Hide blinking cursor. */
494 if (has_colors()) {
495 short bg;
496 start_color();
497 #ifdef NCURSES_EXT_FUNCS
498 use_default_colors();
499 bg = -1;
500 #else
501 bg = COLOR_BLACK;
502 #endif
503 init_pair(RED, COLOR_RED, bg);
504 init_pair(GREEN, COLOR_GREEN, bg);
505 init_pair(YELLOW, COLOR_YELLOW, bg);
506 init_pair(BLUE, COLOR_BLUE, bg);
507 init_pair(CYAN, COLOR_CYAN, bg);
508 init_pair(MAGENTA, COLOR_MAGENTA, bg);
509 init_pair(WHITE, COLOR_WHITE, bg);
510 init_pair(BLACK, COLOR_BLACK, bg);
512 atexit((void (*)(void))endwin);
513 enable_handlers();
516 /* Update the listing view. */
517 static void
518 update_view()
520 int i, j;
521 int numsize;
522 int ishidden;
523 int marking;
525 mvhline(0, 0, ' ', COLS);
526 attr_on(A_BOLD, NULL);
527 color_set(RVC_TABNUM, NULL);
528 mvaddch(0, COLS - 2, fm.tab + '0');
529 attr_off(A_BOLD, NULL);
530 if (fm.marks.nentries) {
531 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
532 color_set(RVC_MARKS, NULL);
533 mvaddstr(0, COLS - 3 - numsize, BUF1);
534 } else
535 numsize = -1;
536 color_set(RVC_CWD, NULL);
537 mbstowcs(WBUF, CWD, PATH_MAX);
538 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
539 wcolor_set(fm.window, RVC_BORDER, NULL);
540 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
541 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
543 /*
544 * Selection might not be visible, due to cursor wrapping or
545 * window shrinking. In that case, the scroll must be moved to
546 * make it visible.
547 */
548 if (fm.nfiles > HEIGHT) {
549 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
550 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
551 } else
552 SCROLL = 0;
553 marking = !strcmp(CWD, fm.marks.dirpath);
554 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
555 ishidden = ENAME(j)[0] == '.';
556 if (j == ESEL)
557 wattr_on(fm.window, A_REVERSE, NULL);
558 if (ISLINK(j))
559 wcolor_set(fm.window, RVC_LINK, NULL);
560 else if (ishidden)
561 wcolor_set(fm.window, RVC_HIDDEN, NULL);
562 else if (S_ISREG(EMODE(j))) {
563 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
564 wcolor_set(fm.window, RVC_EXEC, NULL);
565 else
566 wcolor_set(fm.window, RVC_REG, NULL);
567 } else if (S_ISDIR(EMODE(j)))
568 wcolor_set(fm.window, RVC_DIR, NULL);
569 else if (S_ISCHR(EMODE(j)))
570 wcolor_set(fm.window, RVC_CHR, NULL);
571 else if (S_ISBLK(EMODE(j)))
572 wcolor_set(fm.window, RVC_BLK, NULL);
573 else if (S_ISFIFO(EMODE(j)))
574 wcolor_set(fm.window, RVC_FIFO, NULL);
575 else if (S_ISSOCK(EMODE(j)))
576 wcolor_set(fm.window, RVC_SOCK, NULL);
577 if (S_ISDIR(EMODE(j))) {
578 mbstowcs(WBUF, ENAME(j), PATH_MAX);
579 if (ISLINK(j))
580 wcscat(WBUF, L"/");
581 } else {
582 const char *suffix, *suffixes = "BKMGTPEZY";
583 off_t human_size = ESIZE(j) * 10;
584 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
585 int namecols = wcswidth(WBUF, length);
586 for (suffix = suffixes; human_size >= 10240; suffix++)
587 human_size = (human_size + 512) / 1024;
588 if (*suffix == 'B')
589 swprintf(WBUF + length, PATH_MAX - length,
590 L"%*d %c",
591 (int)(COLS - namecols - 6),
592 (int)human_size / 10, *suffix);
593 else
594 swprintf(WBUF + length, PATH_MAX - length,
595 L"%*d.%d %c",
596 (int)(COLS - namecols - 8),
597 (int)human_size / 10,
598 (int)human_size % 10, *suffix);
600 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
601 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
602 if (marking && MARKED(j)) {
603 wcolor_set(fm.window, RVC_MARKS, NULL);
604 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
605 } else
606 mvwaddch(fm.window, i + 1, 1, ' ');
607 if (j == ESEL)
608 wattr_off(fm.window, A_REVERSE, NULL);
610 for (; i < HEIGHT; i++)
611 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
612 if (fm.nfiles > HEIGHT) {
613 int center, height;
614 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
615 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
616 if (!height)
617 height = 1;
618 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
619 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
620 RVS_SCROLLBAR, height);
622 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
623 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
624 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
625 if (!fm.nfiles)
626 strcpy(BUF2, "0/0");
627 else
628 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
629 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
630 color_set(RVC_STATUS, NULL);
631 mvaddstr(LINES - 1, STATUSPOS, BUF1);
632 wrefresh(fm.window);
635 /* Show a message on the status bar. */
636 static void __attribute__((format(printf, 2, 3)))
637 message(enum color c, const char *fmt, ...)
639 int len, pos;
640 va_list args;
642 va_start(args, fmt);
643 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
644 va_end(args);
645 len = strlen(BUF1);
646 pos = (STATUSPOS - len) / 2;
647 attr_on(A_BOLD, NULL);
648 color_set(c, NULL);
649 mvaddstr(LINES - 1, pos, BUF1);
650 color_set(DEFAULT, NULL);
651 attr_off(A_BOLD, NULL);
654 /* Clear message area, leaving only status info. */
655 static void
656 clear_message()
658 mvhline(LINES - 1, 0, ' ', STATUSPOS);
661 /* Comparison used to sort listing entries. */
662 static int
663 rowcmp(const void *a, const void *b)
665 int isdir1, isdir2, cmpdir;
666 const struct row *r1 = a;
667 const struct row *r2 = b;
668 isdir1 = S_ISDIR(r1->mode);
669 isdir2 = S_ISDIR(r2->mode);
670 cmpdir = isdir2 - isdir1;
671 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
674 /* Get all entries in current working directory. */
675 static int
676 ls(struct row **rowsp, uint8_t flags)
678 DIR *dp;
679 struct dirent *ep;
680 struct stat statbuf;
681 struct row *rows;
682 int i, n;
684 if (!(dp = opendir(".")))
685 return -1;
686 n = -2; /* We don't want the entries "." and "..". */
687 while (readdir(dp))
688 n++;
689 if (n == 0) {
690 closedir(dp);
691 return 0;
693 rewinddir(dp);
694 rows = xmalloc(n * sizeof(*rows));
695 i = 0;
696 while ((ep = readdir(dp))) {
697 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
698 continue;
699 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
700 continue;
701 lstat(ep->d_name, &statbuf);
702 rows[i].islink = S_ISLNK(statbuf.st_mode);
703 stat(ep->d_name, &statbuf);
704 if (S_ISDIR(statbuf.st_mode)) {
705 if (flags & SHOW_DIRS) {
706 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
707 strcpy(rows[i].name, ep->d_name);
708 if (!rows[i].islink)
709 strcat(rows[i].name, "/");
710 rows[i].mode = statbuf.st_mode;
711 i++;
713 } else if (flags & SHOW_FILES) {
714 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
715 strcpy(rows[i].name, ep->d_name);
716 rows[i].size = statbuf.st_size;
717 rows[i].mode = statbuf.st_mode;
718 i++;
721 n = i; /* Ignore unused space in array caused by filters. */
722 qsort(rows, n, sizeof(*rows), rowcmp);
723 closedir(dp);
724 *rowsp = rows;
725 return n;
728 static void
729 free_rows(struct row **rowsp, int nfiles)
731 int i;
733 for (i = 0; i < nfiles; i++)
734 free((*rowsp)[i].name);
735 free(*rowsp);
736 *rowsp = NULL;
739 /* Change working directory to the path in CWD. */
740 static void
741 cd(int reset)
743 int i, j;
745 message(CYAN, "Loading \"%s\"...", CWD);
746 refresh();
747 if (chdir(CWD) == -1) {
748 getcwd(CWD, PATH_MAX - 1);
749 if (CWD[strlen(CWD) - 1] != '/')
750 strcat(CWD, "/");
751 goto done;
753 if (reset)
754 ESEL = SCROLL = 0;
755 if (fm.nfiles)
756 free_rows(&fm.rows, fm.nfiles);
757 fm.nfiles = ls(&fm.rows, FLAGS);
758 if (!strcmp(CWD, fm.marks.dirpath)) {
759 for (i = 0; i < fm.nfiles; i++) {
760 for (j = 0; j < fm.marks.bulk; j++)
761 if (fm.marks.entries[j] &&
762 !strcmp(fm.marks.entries[j], ENAME(i)))
763 break;
764 MARKED(i) = j < fm.marks.bulk;
766 } else
767 for (i = 0; i < fm.nfiles; i++)
768 MARKED(i) = 0;
769 done:
770 clear_message();
771 update_view();
774 /* Select a target entry, if it is present. */
775 static void
776 try_to_sel(const char *target)
778 ESEL = 0;
779 if (!ISDIR(target))
780 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
781 ESEL++;
782 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
783 ESEL++;
786 /* Reload CWD, but try to keep selection. */
787 static void
788 reload()
790 if (fm.nfiles) {
791 strcpy(INPUT, ENAME(ESEL));
792 cd(0);
793 try_to_sel(INPUT);
794 update_view();
795 } else
796 cd(1);
799 static off_t
800 count_dir(const char *path)
802 DIR *dp;
803 struct dirent *ep;
804 struct stat statbuf;
805 char subpath[PATH_MAX];
806 off_t total;
808 if (!(dp = opendir(path)))
809 return 0;
810 total = 0;
811 while ((ep = readdir(dp))) {
812 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
813 continue;
814 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
815 lstat(subpath, &statbuf);
816 if (S_ISDIR(statbuf.st_mode)) {
817 strcat(subpath, "/");
818 total += count_dir(subpath);
819 } else
820 total += statbuf.st_size;
822 closedir(dp);
823 return total;
826 static off_t
827 count_marked()
829 int i;
830 char *entry;
831 off_t total;
832 struct stat statbuf;
834 total = 0;
835 chdir(fm.marks.dirpath);
836 for (i = 0; i < fm.marks.bulk; i++) {
837 entry = fm.marks.entries[i];
838 if (entry) {
839 if (ISDIR(entry)) {
840 total += count_dir(entry);
841 } else {
842 lstat(entry, &statbuf);
843 total += statbuf.st_size;
847 chdir(CWD);
848 return total;
851 /*
852 * Recursively process a source directory using CWD as destination
853 * root. For each node (i.e. directory), do the following:
855 * 1. call pre(destination);
856 * 2. call proc() on every child leaf (i.e. files);
857 * 3. recurse into every child node;
858 * 4. call pos(source).
860 * E.g. to move directory /src/ (and all its contents) inside /dst/:
861 * strcpy(CWD, "/dst/");
862 * process_dir(adddir, movfile, deldir, "/src/");
863 */
864 static int
865 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
867 int ret;
868 DIR *dp;
869 struct dirent *ep;
870 struct stat statbuf;
871 char subpath[PATH_MAX];
873 ret = 0;
874 if (pre) {
875 char dstpath[PATH_MAX];
876 strcpy(dstpath, CWD);
877 strcat(dstpath, path + strlen(fm . marks . dirpath));
878 ret |= pre(dstpath);
880 if (!(dp = opendir(path)))
881 return -1;
882 while ((ep = readdir(dp))) {
883 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
884 continue;
885 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
886 lstat(subpath, &statbuf);
887 if (S_ISDIR(statbuf.st_mode)) {
888 strcat(subpath, "/");
889 ret |= process_dir(pre, proc, pos, subpath);
890 } else
891 ret |= proc(subpath);
893 closedir(dp);
894 if (pos)
895 ret |= pos(path);
896 return ret;
899 /*
900 * Process all marked entries using CWD as destination root. All
901 * marked entries that are directories will be recursively processed.
902 * See process_dir() for details on the parameters.
903 */
904 static void
905 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
906 const char *msg_done)
908 int i, ret;
909 char *entry;
910 char path[PATH_MAX];
912 clear_message();
913 message(CYAN, "%s...", msg_doing);
914 refresh();
915 fm.prog = (struct prog){0, count_marked(), msg_doing};
916 for (i = 0; i < fm.marks.bulk; i++) {
917 entry = fm.marks.entries[i];
918 if (entry) {
919 ret = 0;
920 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
921 entry);
922 if (ISDIR(entry)) {
923 if (!strncmp(path, CWD, strlen(path)))
924 ret = -1;
925 else
926 ret = process_dir(pre, proc, pos, path);
927 } else
928 ret = proc(path);
929 if (!ret) {
930 del_mark(&fm.marks, entry);
931 reload();
935 fm.prog.total = 0;
936 reload();
937 if (!fm.marks.nentries)
938 message(GREEN, "%s all marked entries.", msg_done);
939 else
940 message(RED, "Some errors occured while %s.", msg_doing);
941 RV_ALERT();
944 static void
945 update_progress(off_t delta)
947 int percent;
949 if (!fm.prog.total)
950 return;
951 fm.prog.partial += delta;
952 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
953 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
954 refresh();
957 /* Wrappers for file operations. */
958 static int
959 delfile(const char *path)
961 int ret;
962 struct stat st;
964 ret = lstat(path, &st);
965 if (ret < 0)
966 return ret;
967 update_progress(st.st_size);
968 return unlink(path);
971 static PROCESS deldir = rmdir;
972 static int
973 addfile(const char *path)
975 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
976 int ret;
978 ret = creat(path, 0644);
979 if (ret < 0)
980 return ret;
981 return close(ret);
984 static int
985 cpyfile(const char *srcpath)
987 int src, dst, ret;
988 size_t size;
989 struct stat st;
990 char buf[BUFSIZ];
991 char dstpath[PATH_MAX];
993 strcpy(dstpath, CWD);
994 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
995 ret = lstat(srcpath, &st);
996 if (ret < 0)
997 return ret;
998 if (S_ISLNK(st.st_mode)) {
999 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1000 if (ret < 0)
1001 return ret;
1002 BUF1[ret] = '\0';
1003 ret = symlink(BUF1, dstpath);
1004 } else {
1005 ret = src = open(srcpath, O_RDONLY);
1006 if (ret < 0)
1007 return ret;
1008 ret = dst = creat(dstpath, st.st_mode);
1009 if (ret < 0)
1010 return ret;
1011 while ((size = read(src, buf, BUFSIZ)) > 0) {
1012 write(dst, buf, size);
1013 update_progress(size);
1014 sync_signals();
1016 close(src);
1017 close(dst);
1018 ret = 0;
1020 return ret;
1023 static int
1024 adddir(const char *path)
1026 int ret;
1027 struct stat st;
1029 ret = stat(CWD, &st);
1030 if (ret < 0)
1031 return ret;
1032 return mkdir(path, st.st_mode);
1035 static int
1036 movfile(const char *srcpath)
1038 int ret;
1039 struct stat st;
1040 char dstpath[PATH_MAX];
1042 strcpy(dstpath, CWD);
1043 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1044 ret = rename(srcpath, dstpath);
1045 if (ret == 0) {
1046 ret = lstat(dstpath, &st);
1047 if (ret < 0)
1048 return ret;
1049 update_progress(st.st_size);
1050 } else if (errno == EXDEV) {
1051 ret = cpyfile(srcpath);
1052 if (ret < 0)
1053 return ret;
1054 ret = unlink(srcpath);
1056 return ret;
1059 static void
1060 start_line_edit(const char *init_input)
1062 curs_set(TRUE);
1063 strncpy(INPUT, init_input, BUFLEN);
1064 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1065 fm.edit.right = BUFLEN - 1;
1066 fm.edit.buffer[BUFLEN] = L'\0';
1067 fm.edit_scroll = 0;
1070 /* Read input and change editing state accordingly. */
1071 static enum editstate
1072 get_line_edit()
1074 wchar_t eraser, killer, wch;
1075 int ret, length;
1077 ret = fm_get_wch((wint_t *)&wch);
1078 erasewchar(&eraser);
1079 killwchar(&killer);
1080 if (ret == KEY_CODE_YES) {
1081 if (wch == KEY_ENTER) {
1082 curs_set(FALSE);
1083 return CONFIRM;
1084 } else if (wch == KEY_LEFT) {
1085 if (EDIT_CAN_LEFT(fm.edit))
1086 EDIT_LEFT(fm.edit);
1087 } else if (wch == KEY_RIGHT) {
1088 if (EDIT_CAN_RIGHT(fm.edit))
1089 EDIT_RIGHT(fm.edit);
1090 } else if (wch == KEY_UP) {
1091 while (EDIT_CAN_LEFT(fm.edit))
1092 EDIT_LEFT(fm.edit);
1093 } else if (wch == KEY_DOWN) {
1094 while (EDIT_CAN_RIGHT(fm.edit))
1095 EDIT_RIGHT(fm.edit);
1096 } else if (wch == KEY_BACKSPACE) {
1097 if (EDIT_CAN_LEFT(fm.edit))
1098 EDIT_BACKSPACE(fm.edit);
1099 } else if (wch == KEY_DC) {
1100 if (EDIT_CAN_RIGHT(fm.edit))
1101 EDIT_DELETE(fm.edit);
1103 } else {
1104 if (wch == L'\r' || wch == L'\n') {
1105 curs_set(FALSE);
1106 return CONFIRM;
1107 } else if (wch == L'\t') {
1108 curs_set(FALSE);
1109 return CANCEL;
1110 } else if (wch == eraser) {
1111 if (EDIT_CAN_LEFT(fm.edit))
1112 EDIT_BACKSPACE(fm.edit);
1113 } else if (wch == killer) {
1114 EDIT_CLEAR(fm.edit);
1115 clear_message();
1116 } else if (iswprint(wch)) {
1117 if (!EDIT_FULL(fm.edit))
1118 EDIT_INSERT(fm.edit, wch);
1121 /* Encode edit contents in INPUT. */
1122 fm.edit.buffer[fm.edit.left] = L'\0';
1123 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1124 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1125 BUFLEN - length);
1126 return CONTINUE;
1129 /* Update line input on the screen. */
1130 static void
1131 update_input(const char *prompt, enum color c)
1133 int plen, ilen, maxlen;
1135 plen = strlen(prompt);
1136 ilen = mbstowcs(NULL, INPUT, 0);
1137 maxlen = STATUSPOS - plen - 2;
1138 if (ilen - fm.edit_scroll < maxlen)
1139 fm.edit_scroll = MAX(ilen - maxlen, 0);
1140 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1141 fm.edit_scroll = fm.edit.left - maxlen;
1142 else if (fm.edit.left < fm.edit_scroll)
1143 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1144 color_set(RVC_PROMPT, NULL);
1145 mvaddstr(LINES - 1, 0, prompt);
1146 color_set(c, NULL);
1147 mbstowcs(WBUF, INPUT, COLS);
1148 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1149 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1150 ' ');
1151 color_set(DEFAULT, NULL);
1152 if (fm.edit_scroll)
1153 mvaddch(LINES - 1, plen - 1, '<');
1154 if (ilen > fm.edit_scroll + maxlen)
1155 mvaddch(LINES - 1, plen + maxlen, '>');
1156 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1159 static void
1160 cmd_down(void)
1162 if (fm.nfiles)
1163 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1166 static void
1167 cmd_up(void)
1169 if (fm.nfiles)
1170 ESEL = MAX(ESEL - 1, 0);
1173 static void
1174 cmd_scroll_down(void)
1176 if (!fm.nfiles)
1177 return;
1178 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1179 if (fm.nfiles > HEIGHT)
1180 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1183 static void
1184 cmd_scroll_up(void)
1186 if (!fm.nfiles)
1187 return;
1188 ESEL = MAX(ESEL - HEIGHT, 0);
1189 SCROLL = MAX(SCROLL - HEIGHT, 0);
1192 static void
1193 cmd_man(void)
1195 spawn("man", "fm", NULL);
1198 static void
1199 cmd_jump_top(void)
1201 if (fm.nfiles)
1202 ESEL = 0;
1205 static void
1206 cmd_jump_bottom(void)
1208 if (fm.nfiles)
1209 ESEL = fm.nfiles - 1;
1212 static void
1213 cmd_cd_down(void)
1215 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1216 return;
1217 if (chdir(ENAME(ESEL)) == -1) {
1218 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1219 return;
1221 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1222 cd(1);
1225 static void
1226 cmd_cd_up(void)
1228 char *dirname, first;
1230 if (!strcmp(CWD, "/"))
1231 return;
1233 /* dirname(3) basically */
1234 dirname = strrchr(CWD, '/');
1235 *dirname-- = '\0';
1236 dirname = strrchr(CWD, '/') + 1;
1238 first = dirname[0];
1239 dirname[0] = '\0';
1240 cd(1);
1241 dirname[0] = first;
1242 strlcat(dirname, "/", sizeof(dirname));
1243 try_to_sel(dirname);
1244 dirname[0] = '\0';
1245 if (fm.nfiles > HEIGHT)
1246 SCROLL = ESEL - HEIGHT / 2;
1249 static void
1250 cmd_home(void)
1252 const char *home;
1254 if ((home = getenv("HOME")) == NULL) {
1255 message(RED, "HOME is not defined!");
1256 return;
1259 strlcpy(CWD, home, sizeof(CWD));
1260 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1261 strlcat(CWD, "/", sizeof(CWD));
1262 cd(1);
1265 static void
1266 cmd_copy_path(void)
1268 const char *path;
1269 FILE *f;
1271 if ((path = getenv("CLIP")) == NULL ||
1272 (f = fopen(path, "w")) == NULL) {
1273 /* use internal clipboard */
1274 strlcpy(clipboard, CWD, sizeof(clipboard));
1275 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1276 return;
1279 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1280 fputc('\0', f);
1281 fclose(f);
1284 static void
1285 cmd_paste_path(void)
1287 ssize_t r;
1288 const char *path;
1289 char *nl;
1290 FILE *f;
1291 char p[PATH_MAX];
1293 if ((path = getenv("CLIP")) != NULL &&
1294 (f = fopen(path, "w")) != NULL) {
1295 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1296 fclose(f);
1297 if (r == -1 || r == 0)
1298 goto err;
1299 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1300 goto err;
1303 strlcpy(p, clipboard, sizeof(p));
1304 strlcpy(CWD, clipboard, sizeof(CWD));
1305 if ((nl = strrchr(CWD, '/')) != NULL) {
1306 *nl = '\0';
1307 nl = strrchr(p, '/');
1308 assert(nl != NULL);
1310 if (strcmp(CWD, "/") != 0)
1311 strlcat(CWD, "/", sizeof(CWD));
1312 cd(1);
1313 try_to_sel(nl+1);
1314 return;
1316 err:
1317 memset(clipboard, 0, sizeof(clipboard));
1320 static void
1321 loop(void)
1323 int meta, ch, c;
1324 struct binding {
1325 int ch;
1326 #define K_META 1
1327 #define K_CTRL 2
1328 int chflags;
1329 void (*fn)(void);
1330 #define X_UPDV 1
1331 #define X_QUIT 2
1332 int flags;
1333 } bindings[] = {
1334 {'^', 0, cmd_cd_up, X_UPDV},
1335 {'h', 0, cmd_cd_up, X_UPDV},
1336 {'b', 0, cmd_cd_up, X_UPDV},
1337 {'l', 0, cmd_cd_down, X_UPDV},
1338 {'f', 0, cmd_cd_down, X_UPDV},
1339 {'<', K_META, cmd_jump_top, X_UPDV},
1340 {'>', K_META, cmd_jump_bottom, X_UPDV},
1341 {'?', 0, cmd_man, 0},
1342 {'G', 0, cmd_jump_bottom, X_UPDV},
1343 {'H', 0, cmd_home, X_UPDV},
1344 {'J', 0, cmd_scroll_down, X_UPDV},
1345 {'K', 0, cmd_scroll_up, X_UPDV},
1346 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1347 {'g', 0, cmd_jump_top, X_UPDV},
1348 {'g', K_CTRL, NULL, X_UPDV},
1349 {'j', 0, cmd_down, X_UPDV},
1350 {'k', 0, cmd_up, X_UPDV},
1351 {'n', 0, cmd_down, X_UPDV},
1352 {'n', K_CTRL, cmd_down, X_UPDV},
1353 {'P', 0, cmd_paste_path, X_UPDV},
1354 {'p', 0, cmd_up, X_UPDV},
1355 {'p', K_CTRL, cmd_up, X_UPDV},
1356 {'q', 0, NULL, X_QUIT},
1357 {'v', K_META, cmd_scroll_up, X_UPDV},
1358 {'Y', 0, cmd_copy_path, X_UPDV},
1359 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1360 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1361 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1362 {KEY_RESIZE, 0, NULL, X_UPDV},
1363 {KEY_RESIZE, K_META, NULL, X_UPDV},
1364 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1365 }, *b;
1366 size_t i;
1368 for (;;) {
1369 again:
1370 meta = 0;
1371 ch = fm_getch();
1372 if (ch == '\e') {
1373 meta = 1;
1374 if ((ch = fm_getch()) == '\e') {
1375 meta = 0;
1376 ch = '\e';
1380 clear_message();
1382 for (i = 0; i < nitems(bindings); ++i) {
1383 b = &bindings[i];
1384 c = b->ch;
1385 if (b->chflags & K_CTRL)
1386 c = CTRL(c);
1387 if ((!meta && b->chflags & K_META) || ch != c)
1388 continue;
1390 if (b->flags & X_QUIT)
1391 return;
1392 if (b->fn != NULL)
1393 b->fn();
1394 if (b->flags & X_UPDV)
1395 update_view();
1397 goto again;
1400 message(RED, "%s%s is undefined",
1401 meta ? "M-": "", keyname(ch));
1402 refresh();
1406 int
1407 main(int argc, char *argv[])
1409 int i, ch;
1410 char *program;
1411 char *entry;
1412 const char *key;
1413 const char *clip_path;
1414 DIR *d;
1415 enum editstate edit_stat;
1416 FILE *save_cwd_file = NULL;
1417 FILE *save_marks_file = NULL;
1418 FILE *clip_file;
1420 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1421 switch (ch) {
1422 case 'd':
1423 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1424 err(1, "open %s", optarg);
1425 break;
1426 case 'h':
1427 printf(""
1428 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1429 "Browse current directory or the ones specified.\n"
1430 "\n"
1431 "See fm(1) for more information.\n"
1432 "fm homepage <https://github.com/omar-polo/fm>\n");
1433 return 0;
1434 case 'm':
1435 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1436 err(1, "open %s", optarg);
1437 break;
1438 case 'v':
1439 printf("version: fm %s\n", RV_VERSION);
1440 return 0;
1444 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1445 err(1, "pledge");
1447 get_user_programs();
1448 init_term();
1449 fm.nfiles = 0;
1450 for (i = 0; i < 10; i++) {
1451 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1452 fm.tabs[i].flags = RV_FLAGS;
1454 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1455 for (i = 1; i < argc && i < 10; i++) {
1456 if ((d = opendir(argv[i]))) {
1457 realpath(argv[i], fm.tabs[i].cwd);
1458 closedir(d);
1459 } else
1460 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1462 getcwd(fm.tabs[i].cwd, PATH_MAX);
1463 for (i++; i < 10; i++)
1464 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1465 for (i = 0; i < 10; i++)
1466 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1467 strcat(fm.tabs[i].cwd, "/");
1468 fm.tab = 1;
1469 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1470 init_marks(&fm.marks);
1471 cd(1);
1472 strlcpy(clipboard, CWD, sizeof(clipboard));
1473 if (fm.nfiles > 0)
1474 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1476 loop();
1478 if (fm.nfiles)
1479 free_rows(&fm.rows, fm.nfiles);
1480 delwin(fm.window);
1481 if (save_cwd_file != NULL) {
1482 fputs(CWD, save_cwd_file);
1483 fclose(save_cwd_file);
1485 if (save_marks_file != NULL) {
1486 for (i = 0; i < fm.marks.bulk; i++) {
1487 entry = fm.marks.entries[i];
1488 if (entry)
1489 fprintf(save_marks_file, "%s%s\n",
1490 fm.marks.dirpath, entry);
1492 fclose(save_marks_file);
1494 free_marks(&fm.marks);
1495 return 0;