Blob


1 /* needed for some ncurses stuff */
2 #define _XOPEN_SOURCE_EXTENDED
3 #define _FILE_OFFSET_BITS 64
5 #include <sys/stat.h>
6 #include <sys/types.h>
7 #include <sys/wait.h>
9 #include <assert.h>
10 #include <ctype.h>
11 #include <curses.h>
12 #include <dirent.h>
13 #include <err.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <getopt.h>
17 #include <libgen.h>
18 #include <limits.h>
19 #include <locale.h>
20 #include <signal.h>
21 #include <stdarg.h>
22 #include <stdint.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <wchar.h>
28 #include <wctype.h>
30 #ifndef FM_SHELL
31 #define FM_SHELL "/bin/sh"
32 #endif
34 #ifndef FM_PAGER
35 #define FM_PAGER "/usr/bin/less"
36 #endif
38 #ifndef FM_ED
39 #define FM_ED "/bin/ed"
40 #endif
42 #ifndef FM_OPENER
43 #define FM_OPENER "xdg-open"
44 #endif
46 #include "config.h"
48 struct option opts[] = {
49 {"help", no_argument, NULL, 'h'},
50 {"version", no_argument, NULL, 'v'},
51 {NULL, 0, NULL, 0}
52 };
54 static char clipboard[PATH_MAX];
56 /* String buffers. */
57 #define BUFLEN PATH_MAX
58 static char BUF1[BUFLEN];
59 static char BUF2[BUFLEN];
60 static char INPUT[BUFLEN];
61 static wchar_t WBUF[BUFLEN];
63 /* Paths to external programs. */
64 static char *user_shell;
65 static char *user_pager;
66 static char *user_editor;
67 static char *user_open;
69 /* Listing view parameters. */
70 #define HEIGHT (LINES-4)
71 #define STATUSPOS (COLS-16)
73 /* Listing view flags. */
74 #define SHOW_FILES 0x01u
75 #define SHOW_DIRS 0x02u
76 #define SHOW_HIDDEN 0x04u
78 /* Marks parameters. */
79 #define BULK_INIT 5
80 #define BULK_THRESH 256
82 /* Information associated to each entry in listing. */
83 struct row {
84 char *name;
85 off_t size;
86 mode_t mode;
87 int islink;
88 int marked;
89 };
91 /* Dynamic array of marked entries. */
92 struct marks {
93 char dirpath[PATH_MAX];
94 int bulk;
95 int nentries;
96 char **entries;
97 };
99 /* Line editing state. */
100 struct edit {
101 wchar_t buffer[BUFLEN + 1];
102 int left, right;
103 };
105 /* Each tab only stores the following information. */
106 struct tab {
107 int scroll;
108 int esel;
109 uint8_t flags;
110 char cwd[PATH_MAX];
111 };
113 struct prog {
114 off_t partial;
115 off_t total;
116 const char *msg;
117 };
119 /* Global state. */
120 static struct state {
121 int tab;
122 int nfiles;
123 struct row *rows;
124 WINDOW *window;
125 struct marks marks;
126 struct edit edit;
127 int edit_scroll;
128 volatile sig_atomic_t pending_usr1;
129 volatile sig_atomic_t pending_winch;
130 struct prog prog;
131 struct tab tabs[10];
132 } fm;
134 /* Macros for accessing global state. */
135 #define ENAME(I) fm.rows[I].name
136 #define ESIZE(I) fm.rows[I].size
137 #define EMODE(I) fm.rows[I].mode
138 #define ISLINK(I) fm.rows[I].islink
139 #define MARKED(I) fm.rows[I].marked
140 #define SCROLL fm.tabs[fm.tab].scroll
141 #define ESEL fm.tabs[fm.tab].esel
142 #define FLAGS fm.tabs[fm.tab].flags
143 #define CWD fm.tabs[fm.tab].cwd
145 /* Helpers. */
146 #define MIN(A, B) ((A) < (B) ? (A) : (B))
147 #define MAX(A, B) ((A) > (B) ? (A) : (B))
148 #define ISDIR(E) (strchr((E), '/') != NULL)
149 #define CTRL(x) ((x) & 0x1f)
150 #define nitems(a) (sizeof(a)/sizeof(a[0]))
152 /* Line Editing Macros. */
153 #define EDIT_FULL(E) ((E).left == (E).right)
154 #define EDIT_CAN_LEFT(E) ((E).left)
155 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
156 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
157 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
158 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
159 #define EDIT_BACKSPACE(E) (E).left--
160 #define EDIT_DELETE(E) (E).right++
161 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
163 enum editstate { CONTINUE, CONFIRM, CANCEL };
164 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
166 typedef int (*PROCESS)(const char *path);
168 #ifndef __dead
169 #define __dead __attribute__((noreturn))
170 #endif
172 static inline __dead void
173 quit(const char *reason)
175 int saved_errno;
177 saved_errno = errno;
178 endwin();
179 nocbreak();
180 fflush(stderr);
181 errno = saved_errno;
182 err(1, "%s", reason);
185 static inline void *
186 xcalloc(size_t nmemb, size_t size)
188 void *d;
190 if ((d = calloc(nmemb, size)) == NULL)
191 quit("calloc");
192 return d;
195 static inline void *
196 xrealloc(void *p, size_t size)
198 void *d;
200 if ((d = realloc(p, size)) == NULL)
201 quit("realloc");
202 return d;
205 static inline int
206 xasprintf(char **ret, const char *fmt, ...)
208 va_list ap;
209 int r;
211 va_start(ap, fmt);
212 r = vasprintf(ret, fmt, ap);
213 va_end(ap);
215 if (r == -1)
216 quit("asprintf");
217 return r;
220 static inline char *
221 xstrdup(char *str)
223 char *s;
225 if ((s = strdup(str)) == NULL)
226 quit("strdup");
227 return s;
230 static void
231 init_marks(struct marks *marks)
233 strlcpy(marks->dirpath, "", sizeof(marks->dirpath));
234 marks->bulk = BULK_INIT;
235 marks->nentries = 0;
236 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
239 /* Unmark all entries. */
240 static void
241 mark_none(struct marks *marks)
243 int i;
245 strlcpy(marks->dirpath, "", sizeof(marks->dirpath));
246 for (i = 0; i < marks->bulk && marks->nentries; i++)
247 if (marks->entries[i]) {
248 free(marks->entries[i]);
249 marks->entries[i] = NULL;
250 marks->nentries--;
252 if (marks->bulk > BULK_THRESH) {
253 /* Reset bulk to free some memory. */
254 free(marks->entries);
255 marks->bulk = BULK_INIT;
256 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
260 static void
261 add_mark(struct marks *marks, char *dirpath, char *entry)
263 int i;
265 if (!strcmp(marks->dirpath, dirpath)) {
266 /* Append mark to directory. */
267 if (marks->nentries == marks->bulk) {
268 /* Expand bulk to accomodate new entry. */
269 int extra = marks->bulk / 2;
270 marks->bulk += extra; /* bulk *= 1.5; */
271 marks->entries = xrealloc(marks->entries,
272 marks->bulk * sizeof(*marks->entries));
273 memset(&marks->entries[marks->nentries], 0,
274 extra * sizeof(*marks->entries));
275 i = marks->nentries;
276 } else {
277 /* Search for empty slot (there must be one). */
278 for (i = 0; i < marks->bulk; i++)
279 if (!marks->entries[i])
280 break;
282 } else {
283 /* Directory changed. Discard old marks. */
284 mark_none(marks);
285 strlcpy(marks->dirpath, dirpath, sizeof(marks->dirpath));
286 i = 0;
288 marks->entries[i] = xstrdup(entry);
289 marks->nentries++;
292 static void
293 del_mark(struct marks *marks, char *entry)
295 int i;
297 if (marks->nentries > 1) {
298 for (i = 0; i < marks->bulk; i++)
299 if (marks->entries[i] &&
300 !strcmp(marks->entries[i], entry))
301 break;
302 free(marks->entries[i]);
303 marks->entries[i] = NULL;
304 marks->nentries--;
305 } else
306 mark_none(marks);
309 static void
310 free_marks(struct marks *marks)
312 int i;
314 for (i = 0; i < marks->bulk && marks->nentries; i++)
315 if (marks->entries[i]) {
316 free(marks->entries[i]);
317 marks->nentries--;
319 free(marks->entries);
322 static void
323 handle_usr1(int sig)
325 fm.pending_usr1 = 1;
328 static void
329 handle_winch(int sig)
331 fm.pending_winch = 1;
334 static void
335 enable_handlers(void)
337 struct sigaction sa;
339 memset(&sa, 0, sizeof(struct sigaction));
340 sa.sa_handler = handle_usr1;
341 sigaction(SIGUSR1, &sa, NULL);
342 sa.sa_handler = handle_winch;
343 sigaction(SIGWINCH, &sa, NULL);
346 static void
347 disable_handlers(void)
349 struct sigaction sa;
351 memset(&sa, 0, sizeof(struct sigaction));
352 sa.sa_handler = SIG_DFL;
353 sigaction(SIGUSR1, &sa, NULL);
354 sigaction(SIGWINCH, &sa, NULL);
357 static void reload(void);
358 static void update_view(void);
360 /* Handle any signals received since last call. */
361 static void
362 sync_signals(void)
364 if (fm.pending_usr1) {
365 /* SIGUSR1 received: refresh directory listing. */
366 reload();
367 fm.pending_usr1 = 0;
369 if (fm.pending_winch) {
370 /* SIGWINCH received: resize application accordingly. */
371 delwin(fm.window);
372 endwin();
373 refresh();
374 clear();
375 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
376 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
377 SCROLL = ESEL - HEIGHT;
378 update_view();
379 fm.pending_winch = 0;
383 /*
384 * This function must be used in place of getch(). It handles signals
385 * while waiting for user input.
386 */
387 static int
388 fm_getch()
390 int ch;
392 while ((ch = getch()) == ERR)
393 sync_signals();
394 return ch;
397 /*
398 * This function must be used in place of get_wch(). It handles
399 * signals while waiting for user input.
400 */
401 static int
402 fm_get_wch(wint_t *wch)
404 wint_t ret;
406 while ((ret = get_wch(wch)) == (wint_t)ERR)
407 sync_signals();
408 return ret;
411 /* Get user programs from the environment. */
413 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
414 dst = getenv(#src);
416 static void
417 get_user_programs()
419 FM_ENV(user_shell, SHELL);
420 FM_ENV(user_pager, PAGER);
421 FM_ENV(user_editor, VISUAL);
422 if (!user_editor)
423 FM_ENV(user_editor, EDITOR);
424 FM_ENV(user_open, OPEN);
427 /* Do a fork-exec to external program (e.g. $EDITOR). */
428 static void
429 spawn(const char *argv0, ...)
431 pid_t pid;
432 int status;
433 size_t i;
434 const char *argv[16], *last;
435 va_list ap;
437 memset(argv, 0, sizeof(argv));
439 va_start(ap, argv0);
440 argv[0] = argv0;
441 for (i = 1; i < nitems(argv); ++i) {
442 last = va_arg(ap, const char *);
443 if (last == NULL)
444 break;
445 argv[i] = last;
447 va_end(ap);
449 if (last != NULL)
450 abort();
452 disable_handlers();
453 endwin();
455 switch (pid = fork()) {
456 case -1:
457 quit("fork");
458 case 0: /* child */
459 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
460 execvp(argv[0], (char *const *)argv);
461 quit("execvp");
462 default:
463 waitpid(pid, &status, 0);
464 enable_handlers();
465 kill(getpid(), SIGWINCH);
469 static void
470 shell_escaped_cat(char *buf, char *str, size_t n)
472 char *p = buf + strlen(buf);
473 *p++ = '\'';
474 for (n--; n; n--, str++) {
475 switch (*str) {
476 case '\'':
477 if (n < 4)
478 goto done;
479 strlcpy(p, "'\\''", n);
480 n -= 4;
481 p += 4;
482 break;
483 case '\0':
484 goto done;
485 default:
486 *p = *str;
487 p++;
490 done:
491 strncat(p, "'", n);
494 static int
495 open_with_env(char *program, char *path)
497 if (program) {
498 #ifdef RV_SHELL
499 strncpy(BUF1, program, BUFLEN - 1);
500 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
501 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
502 spawn(RV_SHELL, "-c", BUF1, NULL );
503 #else
504 spawn(program, path, NULL);
505 #endif
506 return 1;
508 return 0;
511 /* Curses setup. */
512 static void
513 init_term()
515 setlocale(LC_ALL, "");
516 initscr();
517 raw();
518 timeout(100); /* For getch(). */
519 noecho();
520 nonl(); /* No NL->CR/NL on output. */
521 intrflush(stdscr, FALSE);
522 keypad(stdscr, TRUE);
523 curs_set(FALSE); /* Hide blinking cursor. */
524 if (has_colors()) {
525 short bg;
526 start_color();
527 #ifdef NCURSES_EXT_FUNCS
528 use_default_colors();
529 bg = -1;
530 #else
531 bg = COLOR_BLACK;
532 #endif
533 init_pair(RED, COLOR_RED, bg);
534 init_pair(GREEN, COLOR_GREEN, bg);
535 init_pair(YELLOW, COLOR_YELLOW, bg);
536 init_pair(BLUE, COLOR_BLUE, bg);
537 init_pair(CYAN, COLOR_CYAN, bg);
538 init_pair(MAGENTA, COLOR_MAGENTA, bg);
539 init_pair(WHITE, COLOR_WHITE, bg);
540 init_pair(BLACK, COLOR_BLACK, bg);
542 atexit((void (*)(void))endwin);
543 enable_handlers();
546 /* Update the listing view. */
547 static void
548 update_view()
550 int i, j;
551 int numsize;
552 int ishidden;
553 int marking;
555 mvhline(0, 0, ' ', COLS);
556 attr_on(A_BOLD, NULL);
557 color_set(RVC_TABNUM, NULL);
558 mvaddch(0, COLS - 2, fm.tab + '0');
559 attr_off(A_BOLD, NULL);
560 if (fm.marks.nentries) {
561 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
562 color_set(RVC_MARKS, NULL);
563 mvaddstr(0, COLS - 3 - numsize, BUF1);
564 } else
565 numsize = -1;
566 color_set(RVC_CWD, NULL);
567 mbstowcs(WBUF, CWD, PATH_MAX);
568 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
569 wcolor_set(fm.window, RVC_BORDER, NULL);
570 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
571 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
573 /*
574 * Selection might not be visible, due to cursor wrapping or
575 * window shrinking. In that case, the scroll must be moved to
576 * make it visible.
577 */
578 if (fm.nfiles > HEIGHT) {
579 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
580 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
581 } else
582 SCROLL = 0;
583 marking = !strcmp(CWD, fm.marks.dirpath);
584 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
585 ishidden = ENAME(j)[0] == '.';
586 if (j == ESEL)
587 wattr_on(fm.window, A_REVERSE, NULL);
588 if (ISLINK(j))
589 wcolor_set(fm.window, RVC_LINK, NULL);
590 else if (ishidden)
591 wcolor_set(fm.window, RVC_HIDDEN, NULL);
592 else if (S_ISREG(EMODE(j))) {
593 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
594 wcolor_set(fm.window, RVC_EXEC, NULL);
595 else
596 wcolor_set(fm.window, RVC_REG, NULL);
597 } else if (S_ISDIR(EMODE(j)))
598 wcolor_set(fm.window, RVC_DIR, NULL);
599 else if (S_ISCHR(EMODE(j)))
600 wcolor_set(fm.window, RVC_CHR, NULL);
601 else if (S_ISBLK(EMODE(j)))
602 wcolor_set(fm.window, RVC_BLK, NULL);
603 else if (S_ISFIFO(EMODE(j)))
604 wcolor_set(fm.window, RVC_FIFO, NULL);
605 else if (S_ISSOCK(EMODE(j)))
606 wcolor_set(fm.window, RVC_SOCK, NULL);
607 if (S_ISDIR(EMODE(j))) {
608 mbstowcs(WBUF, ENAME(j), PATH_MAX);
609 if (ISLINK(j))
610 wcslcat(WBUF, L"/", sizeof(WBUF));
611 } else {
612 const char *suffix, *suffixes = "BKMGTPEZY";
613 off_t human_size = ESIZE(j) * 10;
614 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
615 int namecols = wcswidth(WBUF, length);
616 for (suffix = suffixes; human_size >= 10240; suffix++)
617 human_size = (human_size + 512) / 1024;
618 if (*suffix == 'B')
619 swprintf(WBUF + length, PATH_MAX - length,
620 L"%*d %c",
621 (int)(COLS - namecols - 6),
622 (int)human_size / 10, *suffix);
623 else
624 swprintf(WBUF + length, PATH_MAX - length,
625 L"%*d.%d %c",
626 (int)(COLS - namecols - 8),
627 (int)human_size / 10,
628 (int)human_size % 10, *suffix);
630 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
631 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
632 if (marking && MARKED(j)) {
633 wcolor_set(fm.window, RVC_MARKS, NULL);
634 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
635 } else
636 mvwaddch(fm.window, i + 1, 1, ' ');
637 if (j == ESEL)
638 wattr_off(fm.window, A_REVERSE, NULL);
640 for (; i < HEIGHT; i++)
641 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
642 if (fm.nfiles > HEIGHT) {
643 int center, height;
644 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
645 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
646 if (!height)
647 height = 1;
648 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
649 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
650 RVS_SCROLLBAR, height);
652 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
653 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
654 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
655 if (!fm.nfiles)
656 strlcpy(BUF2, "0/0", sizeof(BUF2));
657 else
658 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
659 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
660 color_set(RVC_STATUS, NULL);
661 mvaddstr(LINES - 1, STATUSPOS, BUF1);
662 wrefresh(fm.window);
665 /* Show a message on the status bar. */
666 static void __attribute__((format(printf, 2, 3)))
667 message(enum color c, const char *fmt, ...)
669 int len, pos;
670 va_list args;
672 va_start(args, fmt);
673 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
674 va_end(args);
675 len = strlen(BUF1);
676 pos = (STATUSPOS - len) / 2;
677 attr_on(A_BOLD, NULL);
678 color_set(c, NULL);
679 mvaddstr(LINES - 1, pos, BUF1);
680 color_set(DEFAULT, NULL);
681 attr_off(A_BOLD, NULL);
684 /* Clear message area, leaving only status info. */
685 static void
686 clear_message()
688 mvhline(LINES - 1, 0, ' ', STATUSPOS);
691 /* Comparison used to sort listing entries. */
692 static int
693 rowcmp(const void *a, const void *b)
695 int isdir1, isdir2, cmpdir;
696 const struct row *r1 = a;
697 const struct row *r2 = b;
698 isdir1 = S_ISDIR(r1->mode);
699 isdir2 = S_ISDIR(r2->mode);
700 cmpdir = isdir2 - isdir1;
701 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
704 /* Get all entries in current working directory. */
705 static int
706 ls(struct row **rowsp, uint8_t flags)
708 DIR *dp;
709 struct dirent *ep;
710 struct stat statbuf;
711 struct row *rows;
712 int i, n;
714 if (!(dp = opendir(".")))
715 return -1;
716 n = -2; /* We don't want the entries "." and "..". */
717 while (readdir(dp))
718 n++;
719 if (n == 0) {
720 closedir(dp);
721 return 0;
723 rewinddir(dp);
724 rows = xcalloc(n, sizeof(*rows));
725 i = 0;
726 while ((ep = readdir(dp))) {
727 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
728 continue;
729 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
730 continue;
731 lstat(ep->d_name, &statbuf);
732 rows[i].islink = S_ISLNK(statbuf.st_mode);
733 stat(ep->d_name, &statbuf);
734 if (S_ISDIR(statbuf.st_mode)) {
735 if (flags & SHOW_DIRS) {
736 xasprintf(&rows[i].name, "%s%s",
737 ep->d_name, rows[i].islink ? "" : "/");
738 rows[i].mode = statbuf.st_mode;
739 i++;
741 } else if (flags & SHOW_FILES) {
742 rows[i].name = xstrdup(ep->d_name);
743 rows[i].size = statbuf.st_size;
744 rows[i].mode = statbuf.st_mode;
745 i++;
748 n = i; /* Ignore unused space in array caused by filters. */
749 qsort(rows, n, sizeof(*rows), rowcmp);
750 closedir(dp);
751 *rowsp = rows;
752 return n;
755 static void
756 free_rows(struct row **rowsp, int nfiles)
758 int i;
760 for (i = 0; i < nfiles; i++)
761 free((*rowsp)[i].name);
762 free(*rowsp);
763 *rowsp = NULL;
766 /* Change working directory to the path in CWD. */
767 static void
768 cd(int reset)
770 int i, j;
772 message(CYAN, "Loading \"%s\"...", CWD);
773 refresh();
774 if (chdir(CWD) == -1) {
775 getcwd(CWD, PATH_MAX - 1);
776 if (CWD[strlen(CWD) - 1] != '/')
777 strlcat(CWD, "/", sizeof(CWD));
778 goto done;
780 if (reset)
781 ESEL = SCROLL = 0;
782 if (fm.nfiles)
783 free_rows(&fm.rows, fm.nfiles);
784 fm.nfiles = ls(&fm.rows, FLAGS);
785 if (!strcmp(CWD, fm.marks.dirpath)) {
786 for (i = 0; i < fm.nfiles; i++) {
787 for (j = 0; j < fm.marks.bulk; j++)
788 if (fm.marks.entries[j] &&
789 !strcmp(fm.marks.entries[j], ENAME(i)))
790 break;
791 MARKED(i) = j < fm.marks.bulk;
793 } else
794 for (i = 0; i < fm.nfiles; i++)
795 MARKED(i) = 0;
796 done:
797 clear_message();
798 update_view();
801 /* Select a target entry, if it is present. */
802 static void
803 try_to_sel(const char *target)
805 ESEL = 0;
806 if (!ISDIR(target))
807 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
808 ESEL++;
809 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
810 ESEL++;
813 /* Reload CWD, but try to keep selection. */
814 static void
815 reload()
817 if (fm.nfiles) {
818 strlcpy(INPUT, ENAME(ESEL), sizeof(INPUT));
819 cd(0);
820 try_to_sel(INPUT);
821 update_view();
822 } else
823 cd(1);
826 static off_t
827 count_dir(const char *path)
829 DIR *dp;
830 struct dirent *ep;
831 struct stat statbuf;
832 char subpath[PATH_MAX];
833 off_t total;
835 if (!(dp = opendir(path)))
836 return 0;
837 total = 0;
838 while ((ep = readdir(dp))) {
839 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
840 continue;
841 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
842 lstat(subpath, &statbuf);
843 if (S_ISDIR(statbuf.st_mode)) {
844 strlcat(subpath, "/", sizeof(subpath));
845 total += count_dir(subpath);
846 } else
847 total += statbuf.st_size;
849 closedir(dp);
850 return total;
853 static off_t
854 count_marked()
856 int i;
857 char *entry;
858 off_t total;
859 struct stat statbuf;
861 total = 0;
862 chdir(fm.marks.dirpath);
863 for (i = 0; i < fm.marks.bulk; i++) {
864 entry = fm.marks.entries[i];
865 if (entry) {
866 if (ISDIR(entry)) {
867 total += count_dir(entry);
868 } else {
869 lstat(entry, &statbuf);
870 total += statbuf.st_size;
874 chdir(CWD);
875 return total;
878 /*
879 * Recursively process a source directory using CWD as destination
880 * root. For each node (i.e. directory), do the following:
882 * 1. call pre(destination);
883 * 2. call proc() on every child leaf (i.e. files);
884 * 3. recurse into every child node;
885 * 4. call pos(source).
887 * E.g. to move directory /src/ (and all its contents) inside /dst/:
888 * strlcpy(CWD, "/dst/", sizeof(CWD));
889 * process_dir(adddir, movfile, deldir, "/src/");
890 */
891 static int
892 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
894 int ret;
895 DIR *dp;
896 struct dirent *ep;
897 struct stat statbuf;
898 char subpath[PATH_MAX];
900 ret = 0;
901 if (pre) {
902 char dstpath[PATH_MAX];
903 strlcpy(dstpath, CWD, sizeof(dstpath));
904 strlcat(dstpath, path + strlen(fm.marks.dirpath),
905 sizeof(dstpath));
906 ret |= pre(dstpath);
908 if (!(dp = opendir(path)))
909 return -1;
910 while ((ep = readdir(dp))) {
911 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
912 continue;
913 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
914 lstat(subpath, &statbuf);
915 if (S_ISDIR(statbuf.st_mode)) {
916 strcat(subpath, "/");
917 ret |= process_dir(pre, proc, pos, subpath);
918 } else
919 ret |= proc(subpath);
921 closedir(dp);
922 if (pos)
923 ret |= pos(path);
924 return ret;
927 /*
928 * Process all marked entries using CWD as destination root. All
929 * marked entries that are directories will be recursively processed.
930 * See process_dir() for details on the parameters.
931 */
932 static void
933 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
934 const char *msg_done)
936 int i, ret;
937 char *entry;
938 char path[PATH_MAX];
940 clear_message();
941 message(CYAN, "%s...", msg_doing);
942 refresh();
943 fm.prog = (struct prog){0, count_marked(), msg_doing};
944 for (i = 0; i < fm.marks.bulk; i++) {
945 entry = fm.marks.entries[i];
946 if (entry) {
947 ret = 0;
948 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
949 entry);
950 if (ISDIR(entry)) {
951 if (!strncmp(path, CWD, strlen(path)))
952 ret = -1;
953 else
954 ret = process_dir(pre, proc, pos, path);
955 } else
956 ret = proc(path);
957 if (!ret) {
958 del_mark(&fm.marks, entry);
959 reload();
963 fm.prog.total = 0;
964 reload();
965 if (!fm.marks.nentries)
966 message(GREEN, "%s all marked entries.", msg_done);
967 else
968 message(RED, "Some errors occured while %s.", msg_doing);
969 RV_ALERT();
972 static void
973 update_progress(off_t delta)
975 int percent;
977 if (!fm.prog.total)
978 return;
979 fm.prog.partial += delta;
980 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
981 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
982 refresh();
985 /* Wrappers for file operations. */
986 static int
987 delfile(const char *path)
989 int ret;
990 struct stat st;
992 ret = lstat(path, &st);
993 if (ret < 0)
994 return ret;
995 update_progress(st.st_size);
996 return unlink(path);
999 static int
1000 addfile(const char *path)
1002 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
1003 int ret;
1005 ret = creat(path, 0644);
1006 if (ret < 0)
1007 return ret;
1008 return close(ret);
1011 static int
1012 cpyfile(const char *srcpath)
1014 int src, dst, ret;
1015 size_t size;
1016 struct stat st;
1017 char buf[BUFSIZ];
1018 char dstpath[PATH_MAX];
1020 strlcpy(dstpath, CWD, sizeof(dstpath));
1021 strlcat(dstpath, srcpath + strlen(fm.marks.dirpath), sizeof(dstpath));
1022 ret = lstat(srcpath, &st);
1023 if (ret < 0)
1024 return ret;
1025 if (S_ISLNK(st.st_mode)) {
1026 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1027 if (ret < 0)
1028 return ret;
1029 BUF1[ret] = '\0';
1030 ret = symlink(BUF1, dstpath);
1031 } else {
1032 ret = src = open(srcpath, O_RDONLY);
1033 if (ret < 0)
1034 return ret;
1035 ret = dst = creat(dstpath, st.st_mode);
1036 if (ret < 0)
1037 return ret;
1038 while ((size = read(src, buf, BUFSIZ)) > 0) {
1039 write(dst, buf, size);
1040 update_progress(size);
1041 sync_signals();
1043 close(src);
1044 close(dst);
1045 ret = 0;
1047 return ret;
1050 static int
1051 adddir(const char *path)
1053 int ret;
1054 struct stat st;
1056 ret = stat(CWD, &st);
1057 if (ret < 0)
1058 return ret;
1059 return mkdir(path, st.st_mode);
1062 static int
1063 movfile(const char *srcpath)
1065 int ret;
1066 struct stat st;
1067 char dstpath[PATH_MAX];
1069 strlcpy(dstpath, CWD, sizeof(dstpath));
1070 strlcat(dstpath, srcpath + strlen(fm.marks.dirpath), sizeof(dstpath));
1071 ret = rename(srcpath, dstpath);
1072 if (ret == 0) {
1073 ret = lstat(dstpath, &st);
1074 if (ret < 0)
1075 return ret;
1076 update_progress(st.st_size);
1077 } else if (errno == EXDEV) {
1078 ret = cpyfile(srcpath);
1079 if (ret < 0)
1080 return ret;
1081 ret = unlink(srcpath);
1083 return ret;
1086 static void
1087 start_line_edit(const char *init_input)
1089 curs_set(TRUE);
1090 strncpy(INPUT, init_input, BUFLEN);
1091 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1092 fm.edit.right = BUFLEN - 1;
1093 fm.edit.buffer[BUFLEN] = L'\0';
1094 fm.edit_scroll = 0;
1097 /* Read input and change editing state accordingly. */
1098 static enum editstate
1099 get_line_edit()
1101 wchar_t eraser, killer, wch;
1102 int ret, length;
1104 ret = fm_get_wch((wint_t *)&wch);
1105 erasewchar(&eraser);
1106 killwchar(&killer);
1107 if (ret == KEY_CODE_YES) {
1108 if (wch == KEY_ENTER) {
1109 curs_set(FALSE);
1110 return CONFIRM;
1111 } else if (wch == KEY_LEFT) {
1112 if (EDIT_CAN_LEFT(fm.edit))
1113 EDIT_LEFT(fm.edit);
1114 } else if (wch == KEY_RIGHT) {
1115 if (EDIT_CAN_RIGHT(fm.edit))
1116 EDIT_RIGHT(fm.edit);
1117 } else if (wch == KEY_UP) {
1118 while (EDIT_CAN_LEFT(fm.edit))
1119 EDIT_LEFT(fm.edit);
1120 } else if (wch == KEY_DOWN) {
1121 while (EDIT_CAN_RIGHT(fm.edit))
1122 EDIT_RIGHT(fm.edit);
1123 } else if (wch == KEY_BACKSPACE) {
1124 if (EDIT_CAN_LEFT(fm.edit))
1125 EDIT_BACKSPACE(fm.edit);
1126 } else if (wch == KEY_DC) {
1127 if (EDIT_CAN_RIGHT(fm.edit))
1128 EDIT_DELETE(fm.edit);
1130 } else {
1131 if (wch == L'\r' || wch == L'\n') {
1132 curs_set(FALSE);
1133 return CONFIRM;
1134 } else if (wch == L'\t') {
1135 curs_set(FALSE);
1136 return CANCEL;
1137 } else if (wch == eraser) {
1138 if (EDIT_CAN_LEFT(fm.edit))
1139 EDIT_BACKSPACE(fm.edit);
1140 } else if (wch == killer) {
1141 EDIT_CLEAR(fm.edit);
1142 clear_message();
1143 } else if (iswprint(wch)) {
1144 if (!EDIT_FULL(fm.edit))
1145 EDIT_INSERT(fm.edit, wch);
1148 /* Encode edit contents in INPUT. */
1149 fm.edit.buffer[fm.edit.left] = L'\0';
1150 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1151 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1152 BUFLEN - length);
1153 return CONTINUE;
1156 /* Update line input on the screen. */
1157 static void
1158 update_input(const char *prompt, enum color c)
1160 int plen, ilen, maxlen;
1162 plen = strlen(prompt);
1163 ilen = mbstowcs(NULL, INPUT, 0);
1164 maxlen = STATUSPOS - plen - 2;
1165 if (ilen - fm.edit_scroll < maxlen)
1166 fm.edit_scroll = MAX(ilen - maxlen, 0);
1167 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1168 fm.edit_scroll = fm.edit.left - maxlen;
1169 else if (fm.edit.left < fm.edit_scroll)
1170 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1171 color_set(RVC_PROMPT, NULL);
1172 mvaddstr(LINES - 1, 0, prompt);
1173 color_set(c, NULL);
1174 mbstowcs(WBUF, INPUT, COLS);
1175 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1176 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1177 ' ');
1178 color_set(DEFAULT, NULL);
1179 if (fm.edit_scroll)
1180 mvaddch(LINES - 1, plen - 1, '<');
1181 if (ilen > fm.edit_scroll + maxlen)
1182 mvaddch(LINES - 1, plen + maxlen, '>');
1183 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1186 static void
1187 cmd_down(void)
1189 if (fm.nfiles)
1190 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1193 static void
1194 cmd_up(void)
1196 if (fm.nfiles)
1197 ESEL = MAX(ESEL - 1, 0);
1200 static void
1201 cmd_scroll_down(void)
1203 if (!fm.nfiles)
1204 return;
1205 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1206 if (fm.nfiles > HEIGHT)
1207 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1210 static void
1211 cmd_scroll_up(void)
1213 if (!fm.nfiles)
1214 return;
1215 ESEL = MAX(ESEL - HEIGHT, 0);
1216 SCROLL = MAX(SCROLL - HEIGHT, 0);
1219 static void
1220 cmd_man(void)
1222 spawn("man", "fm", NULL);
1225 static void
1226 cmd_jump_top(void)
1228 if (fm.nfiles)
1229 ESEL = 0;
1232 static void
1233 cmd_jump_bottom(void)
1235 if (fm.nfiles)
1236 ESEL = fm.nfiles - 1;
1239 static void
1240 cmd_cd_down(void)
1242 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1243 return;
1244 if (chdir(ENAME(ESEL)) == -1) {
1245 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1246 return;
1248 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1249 cd(1);
1252 static void
1253 cmd_cd_up(void)
1255 char *dirname, first;
1257 if (!strcmp(CWD, "/"))
1258 return;
1260 /* dirname(3) basically */
1261 dirname = strrchr(CWD, '/');
1262 *dirname-- = '\0';
1263 dirname = strrchr(CWD, '/') + 1;
1265 first = dirname[0];
1266 dirname[0] = '\0';
1267 cd(1);
1268 dirname[0] = first;
1269 strlcat(dirname, "/", sizeof(dirname));
1270 try_to_sel(dirname);
1271 dirname[0] = '\0';
1272 if (fm.nfiles > HEIGHT)
1273 SCROLL = ESEL - HEIGHT / 2;
1276 static void
1277 cmd_home(void)
1279 const char *home;
1281 if ((home = getenv("HOME")) == NULL) {
1282 message(RED, "HOME is not defined!");
1283 return;
1286 strlcpy(CWD, home, sizeof(CWD));
1287 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1288 strlcat(CWD, "/", sizeof(CWD));
1289 cd(1);
1292 static void
1293 cmd_copy_path(void)
1295 const char *path;
1296 FILE *f;
1298 if ((path = getenv("CLIP")) == NULL ||
1299 (f = fopen(path, "w")) == NULL) {
1300 /* use internal clipboard */
1301 strlcpy(clipboard, CWD, sizeof(clipboard));
1302 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1303 return;
1306 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1307 fputc('\0', f);
1308 fclose(f);
1311 static void
1312 cmd_paste_path(void)
1314 ssize_t r;
1315 const char *path;
1316 char *nl;
1317 FILE *f;
1318 char p[PATH_MAX];
1320 if ((path = getenv("CLIP")) != NULL &&
1321 (f = fopen(path, "w")) != NULL) {
1322 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1323 fclose(f);
1324 if (r == -1 || r == 0)
1325 goto err;
1326 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1327 goto err;
1330 strlcpy(p, clipboard, sizeof(p));
1331 strlcpy(CWD, clipboard, sizeof(CWD));
1332 if ((nl = strrchr(CWD, '/')) != NULL) {
1333 *nl = '\0';
1334 nl = strrchr(p, '/');
1335 assert(nl != NULL);
1337 if (strcmp(CWD, "/") != 0)
1338 strlcat(CWD, "/", sizeof(CWD));
1339 cd(1);
1340 try_to_sel(nl+1);
1341 return;
1343 err:
1344 memset(clipboard, 0, sizeof(clipboard));
1347 static void
1348 cmd_reload(void)
1350 reload();
1353 static void
1354 cmd_shell(void)
1356 const char *shell;
1358 if ((shell = getenv("SHELL")) == NULL)
1359 shell = FM_SHELL;
1360 spawn(shell, NULL);
1363 static void
1364 cmd_view(void)
1366 const char *pager;
1368 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1369 return;
1371 if ((pager = getenv("PAGER")) == NULL)
1372 pager = FM_PAGER;
1373 spawn(pager, ENAME(ESEL), NULL);
1376 static void
1377 cmd_edit(void)
1379 const char *editor;
1381 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1382 return;
1384 if ((editor = getenv("VISUAL")) == NULL ||
1385 (editor = getenv("EDITOR")) == NULL)
1386 editor = FM_ED;
1388 spawn(editor, ENAME(ESEL), NULL);
1391 static void
1392 cmd_open(void)
1394 const char *opener;
1396 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1397 return;
1399 if ((opener = getenv("OPENER")) == NULL)
1400 opener = FM_OPENER;
1402 spawn(opener, ENAME(ESEL), NULL);
1405 static void
1406 cmd_mark(void)
1408 if (MARKED(ESEL))
1409 del_mark(&fm.marks, ENAME(ESEL));
1410 else
1411 add_mark(&fm.marks, CWD, ENAME(ESEL));
1413 MARKED(ESEL) = !MARKED(ESEL);
1414 ESEL = (ESEL + 1) % fm.nfiles;
1417 static void
1418 cmd_toggle_mark(void)
1420 int i;
1422 for (i = 0; i < fm.nfiles; ++i) {
1423 if (MARKED(i))
1424 del_mark(&fm.marks, ENAME(i));
1425 else
1426 add_mark(&fm.marks, CWD, ENAME(ESEL));
1427 MARKED(i) = !MARKED(i);
1431 static void
1432 cmd_mark_all(void)
1434 int i;
1436 for (i = 0; i < fm.nfiles; ++i)
1437 if (!MARKED(i)) {
1438 add_mark(&fm.marks, CWD, ENAME(ESEL));
1439 MARKED(i) = 1;
1443 static void
1444 loop(void)
1446 int meta, ch, c;
1447 struct binding {
1448 int ch;
1449 #define K_META 1
1450 #define K_CTRL 2
1451 int chflags;
1452 void (*fn)(void);
1453 #define X_UPDV 1
1454 #define X_QUIT 2
1455 int flags;
1456 } bindings[] = {
1457 {'<', K_META, cmd_jump_top, X_UPDV},
1458 {'>', K_META, cmd_jump_bottom, X_UPDV},
1459 {'?', 0, cmd_man, 0},
1460 {'G', 0, cmd_jump_bottom, X_UPDV},
1461 {'H', 0, cmd_home, X_UPDV},
1462 {'J', 0, cmd_scroll_down, X_UPDV},
1463 {'K', 0, cmd_scroll_up, X_UPDV},
1464 {'M', 0, cmd_mark_all, X_UPDV},
1465 {'P', 0, cmd_paste_path, X_UPDV},
1466 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1467 {'Y', 0, cmd_copy_path, X_UPDV},
1468 {'^', 0, cmd_cd_up, X_UPDV},
1469 {'b', 0, cmd_cd_up, X_UPDV},
1470 {'e', 0, cmd_edit, X_UPDV},
1471 {'f', 0, cmd_cd_down, X_UPDV},
1472 {'g', 0, cmd_jump_top, X_UPDV},
1473 {'g', K_CTRL, NULL, X_UPDV},
1474 {'h', 0, cmd_cd_up, X_UPDV},
1475 {'j', 0, cmd_down, X_UPDV},
1476 {'k', 0, cmd_up, X_UPDV},
1477 {'l', 0, cmd_cd_down, X_UPDV},
1478 {'l', K_CTRL, cmd_reload, X_UPDV},
1479 {'n', 0, cmd_down, X_UPDV},
1480 {'n', K_CTRL, cmd_down, X_UPDV},
1481 {'m', 0, cmd_mark, X_UPDV},
1482 {'m', K_CTRL, cmd_shell, X_UPDV},
1483 {'o', 0, cmd_open, X_UPDV},
1484 {'p', 0, cmd_up, X_UPDV},
1485 {'p', K_CTRL, cmd_up, X_UPDV},
1486 {'q', 0, NULL, X_QUIT},
1487 {'t', 0, cmd_toggle_mark, X_UPDV},
1488 {'v', 0, cmd_view, X_UPDV},
1489 {'v', K_META, cmd_scroll_up, X_UPDV},
1490 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1491 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1492 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1493 {KEY_RESIZE, 0, NULL, X_UPDV},
1494 {KEY_RESIZE, K_META, NULL, X_UPDV},
1495 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1496 }, *b;
1497 size_t i;
1499 for (;;) {
1500 again:
1501 meta = 0;
1502 ch = fm_getch();
1503 if (ch == '\e') {
1504 meta = 1;
1505 if ((ch = fm_getch()) == '\e') {
1506 meta = 0;
1507 ch = '\e';
1511 clear_message();
1513 for (i = 0; i < nitems(bindings); ++i) {
1514 b = &bindings[i];
1515 c = b->ch;
1516 if (b->chflags & K_CTRL)
1517 c = CTRL(c);
1518 if ((!meta && b->chflags & K_META) || ch != c)
1519 continue;
1521 if (b->flags & X_QUIT)
1522 return;
1523 if (b->fn != NULL)
1524 b->fn();
1525 if (b->flags & X_UPDV)
1526 update_view();
1528 goto again;
1531 message(RED, "%s%s is undefined",
1532 meta ? "M-": "", keyname(ch));
1533 refresh();
1537 static __dead void
1538 usage(void)
1540 fprintf(stderr, "usage: %s [-hv] [-d file] [-m file] [dirs ...]\n",
1541 getprogname());
1542 fprintf(stderr, "version: %s\n", RV_VERSION);
1543 exit(1);
1546 int
1547 main(int argc, char *argv[])
1549 int i, ch;
1550 char *entry;
1551 DIR *d;
1552 FILE *save_cwd_file = NULL;
1553 FILE *save_marks_file = NULL;
1555 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1556 err(1, "pledge");
1558 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1559 switch (ch) {
1560 case 'd':
1561 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1562 err(1, "open %s", optarg);
1563 break;
1564 case 'h':
1565 usage();
1566 break;
1567 case 'm':
1568 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1569 err(1, "open %s", optarg);
1570 break;
1571 case 'v':
1572 printf("version: fm %s\n", RV_VERSION);
1573 return 0;
1574 default:
1575 usage();
1579 get_user_programs();
1580 init_term();
1581 fm.nfiles = 0;
1582 for (i = 0; i < 10; i++) {
1583 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1584 fm.tabs[i].flags = RV_FLAGS;
1586 strlcpy(fm.tabs[0].cwd, getenv("HOME"), sizeof(fm.tabs[0].cwd));
1587 for (i = 1; i < argc && i < 10; i++) {
1588 if ((d = opendir(argv[i]))) {
1589 realpath(argv[i], fm.tabs[i].cwd);
1590 closedir(d);
1591 } else {
1592 strlcpy(fm.tabs[i].cwd, fm.tabs[0].cwd,
1593 sizeof(fm.tabs[i].cwd));
1596 getcwd(fm.tabs[i].cwd, PATH_MAX);
1597 for (i++; i < 10; i++)
1598 strlcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd,
1599 sizeof(fm.tabs[i].cwd));
1600 for (i = 0; i < 10; i++)
1601 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1602 strlcat(fm.tabs[i].cwd, "/", sizeof(fm.tabs[i].cwd));
1603 fm.tab = 1;
1604 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1605 init_marks(&fm.marks);
1606 cd(1);
1607 strlcpy(clipboard, CWD, sizeof(clipboard));
1608 if (fm.nfiles > 0)
1609 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1611 loop();
1613 if (fm.nfiles)
1614 free_rows(&fm.rows, fm.nfiles);
1615 delwin(fm.window);
1616 if (save_cwd_file != NULL) {
1617 fputs(CWD, save_cwd_file);
1618 fclose(save_cwd_file);
1620 if (save_marks_file != NULL) {
1621 for (i = 0; i < fm.marks.bulk; i++) {
1622 entry = fm.marks.entries[i];
1623 if (entry)
1624 fprintf(save_marks_file, "%s%s\n",
1625 fm.marks.dirpath, entry);
1627 fclose(save_marks_file);
1629 free_marks(&fm.marks);
1630 return 0;