Blob


1 /*
2 * fm.c was written by Omar Polo <op@omarpolo.com>, based on the work
3 * of Marcel Rodrigues, and is placed in the public domain. The author
4 * hereby disclaims copyright to this source code.
5 */
7 /* needed for some ncurses stuff */
8 #define _XOPEN_SOURCE_EXTENDED
9 #define _FILE_OFFSET_BITS 64
11 #include <sys/stat.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
15 #include <assert.h>
16 #include <ctype.h>
17 #include <curses.h>
18 #include <dirent.h>
19 #include <err.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <getopt.h>
23 #include <libgen.h>
24 #include <limits.h>
25 #include <locale.h>
26 #include <signal.h>
27 #include <stdarg.h>
28 #include <stdint.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <wchar.h>
34 #include <wctype.h>
36 #ifndef FM_SHELL
37 #define FM_SHELL "/bin/sh"
38 #endif
40 #ifndef FM_PAGER
41 #define FM_PAGER "/usr/bin/less"
42 #endif
44 #ifndef FM_ED
45 #define FM_ED "/bin/ed"
46 #endif
48 #ifndef FM_OPENER
49 #define FM_OPENER "xdg-open"
50 #endif
52 #include "config.h"
54 struct option opts[] = {
55 {"help", no_argument, NULL, 'h'},
56 {"version", no_argument, NULL, 'v'},
57 {NULL, 0, NULL, 0}
58 };
60 static char clipboard[PATH_MAX];
62 /* String buffers. */
63 #define BUFLEN PATH_MAX
64 static char BUF1[BUFLEN];
65 static char BUF2[BUFLEN];
66 static char INPUT[BUFLEN];
67 static wchar_t WBUF[BUFLEN];
69 /* Paths to external programs. */
70 static char *user_shell;
71 static char *user_pager;
72 static char *user_editor;
73 static char *user_open;
75 /* Listing view parameters. */
76 #define HEIGHT (LINES-4)
77 #define STATUSPOS (COLS-16)
79 /* Listing view flags. */
80 #define SHOW_FILES 0x01u
81 #define SHOW_DIRS 0x02u
82 #define SHOW_HIDDEN 0x04u
84 /* Marks parameters. */
85 #define BULK_INIT 5
86 #define BULK_THRESH 256
88 /* Information associated to each entry in listing. */
89 struct row {
90 char *name;
91 off_t size;
92 mode_t mode;
93 int islink;
94 int marked;
95 };
97 /* Dynamic array of marked entries. */
98 struct marks {
99 char dirpath[PATH_MAX];
100 int bulk;
101 int nentries;
102 char **entries;
103 };
105 /* Line editing state. */
106 struct edit {
107 wchar_t buffer[BUFLEN + 1];
108 int left, right;
109 };
111 /* Each tab only stores the following information. */
112 struct tab {
113 int scroll;
114 int esel;
115 uint8_t flags;
116 char cwd[PATH_MAX];
117 };
119 struct prog {
120 off_t partial;
121 off_t total;
122 const char *msg;
123 };
125 /* Global state. */
126 static struct state {
127 int tab;
128 int nfiles;
129 struct row *rows;
130 WINDOW *window;
131 struct marks marks;
132 struct edit edit;
133 int edit_scroll;
134 volatile sig_atomic_t pending_usr1;
135 volatile sig_atomic_t pending_winch;
136 struct prog prog;
137 struct tab tabs[10];
138 } fm;
140 /* Macros for accessing global state. */
141 #define ENAME(I) fm.rows[I].name
142 #define ESIZE(I) fm.rows[I].size
143 #define EMODE(I) fm.rows[I].mode
144 #define ISLINK(I) fm.rows[I].islink
145 #define MARKED(I) fm.rows[I].marked
146 #define SCROLL fm.tabs[fm.tab].scroll
147 #define ESEL fm.tabs[fm.tab].esel
148 #define FLAGS fm.tabs[fm.tab].flags
149 #define CWD fm.tabs[fm.tab].cwd
151 /* Helpers. */
152 #define MIN(A, B) ((A) < (B) ? (A) : (B))
153 #define MAX(A, B) ((A) > (B) ? (A) : (B))
154 #define ISDIR(E) (strchr((E), '/') != NULL)
155 #define CTRL(x) ((x) & 0x1f)
156 #define nitems(a) (sizeof(a)/sizeof(a[0]))
158 /* Line Editing Macros. */
159 #define EDIT_FULL(E) ((E).left == (E).right)
160 #define EDIT_CAN_LEFT(E) ((E).left)
161 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
162 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
163 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
164 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
165 #define EDIT_BACKSPACE(E) (E).left--
166 #define EDIT_DELETE(E) (E).right++
167 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
169 enum editstate { CONTINUE, CONFIRM, CANCEL };
170 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
172 typedef int (*PROCESS)(const char *path);
174 #ifndef __dead
175 #define __dead __attribute__((noreturn))
176 #endif
178 static inline __dead void
179 quit(const char *reason)
181 int saved_errno;
183 saved_errno = errno;
184 endwin();
185 nocbreak();
186 fflush(stderr);
187 errno = saved_errno;
188 err(1, "%s", reason);
191 static inline void *
192 xcalloc(size_t nmemb, size_t size)
194 void *d;
196 if ((d = calloc(nmemb, size)) == NULL)
197 quit("calloc");
198 return d;
201 static inline void *
202 xrealloc(void *p, size_t size)
204 void *d;
206 if ((d = realloc(p, size)) == NULL)
207 quit("realloc");
208 return d;
211 static inline int
212 xasprintf(char **ret, const char *fmt, ...)
214 va_list ap;
215 int r;
217 va_start(ap, fmt);
218 r = vasprintf(ret, fmt, ap);
219 va_end(ap);
221 if (r == -1)
222 quit("asprintf");
223 return r;
226 static inline char *
227 xstrdup(char *str)
229 char *s;
231 if ((s = strdup(str)) == NULL)
232 quit("strdup");
233 return s;
236 static void
237 init_marks(struct marks *marks)
239 strlcpy(marks->dirpath, "", sizeof(marks->dirpath));
240 marks->bulk = BULK_INIT;
241 marks->nentries = 0;
242 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
245 /* Unmark all entries. */
246 static void
247 mark_none(struct marks *marks)
249 int i;
251 strlcpy(marks->dirpath, "", sizeof(marks->dirpath));
252 for (i = 0; i < marks->bulk && marks->nentries; i++)
253 if (marks->entries[i]) {
254 free(marks->entries[i]);
255 marks->entries[i] = NULL;
256 marks->nentries--;
258 if (marks->bulk > BULK_THRESH) {
259 /* Reset bulk to free some memory. */
260 free(marks->entries);
261 marks->bulk = BULK_INIT;
262 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
266 static void
267 add_mark(struct marks *marks, char *dirpath, char *entry)
269 int i;
271 if (!strcmp(marks->dirpath, dirpath)) {
272 /* Append mark to directory. */
273 if (marks->nentries == marks->bulk) {
274 /* Expand bulk to accomodate new entry. */
275 int extra = marks->bulk / 2;
276 marks->bulk += extra; /* bulk *= 1.5; */
277 marks->entries = xrealloc(marks->entries,
278 marks->bulk * sizeof(*marks->entries));
279 memset(&marks->entries[marks->nentries], 0,
280 extra * sizeof(*marks->entries));
281 i = marks->nentries;
282 } else {
283 /* Search for empty slot (there must be one). */
284 for (i = 0; i < marks->bulk; i++)
285 if (!marks->entries[i])
286 break;
288 } else {
289 /* Directory changed. Discard old marks. */
290 mark_none(marks);
291 strlcpy(marks->dirpath, dirpath, sizeof(marks->dirpath));
292 i = 0;
294 marks->entries[i] = xstrdup(entry);
295 marks->nentries++;
298 static void
299 del_mark(struct marks *marks, char *entry)
301 int i;
303 if (marks->nentries > 1) {
304 for (i = 0; i < marks->bulk; i++)
305 if (marks->entries[i] &&
306 !strcmp(marks->entries[i], entry))
307 break;
308 free(marks->entries[i]);
309 marks->entries[i] = NULL;
310 marks->nentries--;
311 } else
312 mark_none(marks);
315 static void
316 free_marks(struct marks *marks)
318 int i;
320 for (i = 0; i < marks->bulk && marks->nentries; i++)
321 if (marks->entries[i]) {
322 free(marks->entries[i]);
323 marks->nentries--;
325 free(marks->entries);
328 static void
329 handle_usr1(int sig)
331 fm.pending_usr1 = 1;
334 static void
335 handle_winch(int sig)
337 fm.pending_winch = 1;
340 static void
341 enable_handlers(void)
343 struct sigaction sa;
345 memset(&sa, 0, sizeof(struct sigaction));
346 sa.sa_handler = handle_usr1;
347 sigaction(SIGUSR1, &sa, NULL);
348 sa.sa_handler = handle_winch;
349 sigaction(SIGWINCH, &sa, NULL);
352 static void
353 disable_handlers(void)
355 struct sigaction sa;
357 memset(&sa, 0, sizeof(struct sigaction));
358 sa.sa_handler = SIG_DFL;
359 sigaction(SIGUSR1, &sa, NULL);
360 sigaction(SIGWINCH, &sa, NULL);
363 static void reload(void);
364 static void update_view(void);
366 /* Handle any signals received since last call. */
367 static void
368 sync_signals(void)
370 if (fm.pending_usr1) {
371 /* SIGUSR1 received: refresh directory listing. */
372 reload();
373 fm.pending_usr1 = 0;
375 if (fm.pending_winch) {
376 /* SIGWINCH received: resize application accordingly. */
377 delwin(fm.window);
378 endwin();
379 refresh();
380 clear();
381 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
382 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
383 SCROLL = ESEL - HEIGHT;
384 update_view();
385 fm.pending_winch = 0;
389 /*
390 * This function must be used in place of getch(). It handles signals
391 * while waiting for user input.
392 */
393 static int
394 fm_getch()
396 int ch;
398 while ((ch = getch()) == ERR)
399 sync_signals();
400 return ch;
403 /*
404 * This function must be used in place of get_wch(). It handles
405 * signals while waiting for user input.
406 */
407 static int
408 fm_get_wch(wint_t *wch)
410 wint_t ret;
412 while ((ret = get_wch(wch)) == (wint_t)ERR)
413 sync_signals();
414 return ret;
417 /* Get user programs from the environment. */
419 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
420 dst = getenv(#src);
422 static void
423 get_user_programs()
425 FM_ENV(user_shell, SHELL);
426 FM_ENV(user_pager, PAGER);
427 FM_ENV(user_editor, VISUAL);
428 if (!user_editor)
429 FM_ENV(user_editor, EDITOR);
430 FM_ENV(user_open, OPEN);
433 /* Do a fork-exec to external program (e.g. $EDITOR). */
434 static void
435 spawn(const char *argv0, ...)
437 pid_t pid;
438 int status;
439 size_t i;
440 const char *argv[16], *last;
441 va_list ap;
443 memset(argv, 0, sizeof(argv));
445 va_start(ap, argv0);
446 argv[0] = argv0;
447 for (i = 1; i < nitems(argv); ++i) {
448 last = va_arg(ap, const char *);
449 if (last == NULL)
450 break;
451 argv[i] = last;
453 va_end(ap);
455 if (last != NULL)
456 abort();
458 disable_handlers();
459 endwin();
461 switch (pid = fork()) {
462 case -1:
463 quit("fork");
464 case 0: /* child */
465 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
466 execvp(argv[0], (char *const *)argv);
467 quit("execvp");
468 default:
469 waitpid(pid, &status, 0);
470 enable_handlers();
471 kill(getpid(), SIGWINCH);
475 static void
476 shell_escaped_cat(char *buf, char *str, size_t n)
478 char *p = buf + strlen(buf);
479 *p++ = '\'';
480 for (n--; n; n--, str++) {
481 switch (*str) {
482 case '\'':
483 if (n < 4)
484 goto done;
485 strlcpy(p, "'\\''", n);
486 n -= 4;
487 p += 4;
488 break;
489 case '\0':
490 goto done;
491 default:
492 *p = *str;
493 p++;
496 done:
497 strncat(p, "'", n);
500 static int
501 open_with_env(char *program, char *path)
503 if (program) {
504 #ifdef RV_SHELL
505 strncpy(BUF1, program, BUFLEN - 1);
506 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
507 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
508 spawn(RV_SHELL, "-c", BUF1, NULL );
509 #else
510 spawn(program, path, NULL);
511 #endif
512 return 1;
514 return 0;
517 /* Curses setup. */
518 static void
519 init_term()
521 setlocale(LC_ALL, "");
522 initscr();
523 raw();
524 timeout(100); /* For getch(). */
525 noecho();
526 nonl(); /* No NL->CR/NL on output. */
527 intrflush(stdscr, FALSE);
528 keypad(stdscr, TRUE);
529 curs_set(FALSE); /* Hide blinking cursor. */
530 if (has_colors()) {
531 short bg;
532 start_color();
533 #ifdef NCURSES_EXT_FUNCS
534 use_default_colors();
535 bg = -1;
536 #else
537 bg = COLOR_BLACK;
538 #endif
539 init_pair(RED, COLOR_RED, bg);
540 init_pair(GREEN, COLOR_GREEN, bg);
541 init_pair(YELLOW, COLOR_YELLOW, bg);
542 init_pair(BLUE, COLOR_BLUE, bg);
543 init_pair(CYAN, COLOR_CYAN, bg);
544 init_pair(MAGENTA, COLOR_MAGENTA, bg);
545 init_pair(WHITE, COLOR_WHITE, bg);
546 init_pair(BLACK, COLOR_BLACK, bg);
548 atexit((void (*)(void))endwin);
549 enable_handlers();
552 /* Update the listing view. */
553 static void
554 update_view()
556 int i, j;
557 int numsize;
558 int ishidden;
559 int marking;
561 mvhline(0, 0, ' ', COLS);
562 attr_on(A_BOLD, NULL);
563 color_set(RVC_TABNUM, NULL);
564 mvaddch(0, COLS - 2, fm.tab + '0');
565 attr_off(A_BOLD, NULL);
566 if (fm.marks.nentries) {
567 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
568 color_set(RVC_MARKS, NULL);
569 mvaddstr(0, COLS - 3 - numsize, BUF1);
570 } else
571 numsize = -1;
572 color_set(RVC_CWD, NULL);
573 mbstowcs(WBUF, CWD, PATH_MAX);
574 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
575 wcolor_set(fm.window, RVC_BORDER, NULL);
576 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
577 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
579 /*
580 * Selection might not be visible, due to cursor wrapping or
581 * window shrinking. In that case, the scroll must be moved to
582 * make it visible.
583 */
584 if (fm.nfiles > HEIGHT) {
585 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
586 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
587 } else
588 SCROLL = 0;
589 marking = !strcmp(CWD, fm.marks.dirpath);
590 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
591 ishidden = ENAME(j)[0] == '.';
592 if (j == ESEL)
593 wattr_on(fm.window, A_REVERSE, NULL);
594 if (ISLINK(j))
595 wcolor_set(fm.window, RVC_LINK, NULL);
596 else if (ishidden)
597 wcolor_set(fm.window, RVC_HIDDEN, NULL);
598 else if (S_ISREG(EMODE(j))) {
599 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
600 wcolor_set(fm.window, RVC_EXEC, NULL);
601 else
602 wcolor_set(fm.window, RVC_REG, NULL);
603 } else if (S_ISDIR(EMODE(j)))
604 wcolor_set(fm.window, RVC_DIR, NULL);
605 else if (S_ISCHR(EMODE(j)))
606 wcolor_set(fm.window, RVC_CHR, NULL);
607 else if (S_ISBLK(EMODE(j)))
608 wcolor_set(fm.window, RVC_BLK, NULL);
609 else if (S_ISFIFO(EMODE(j)))
610 wcolor_set(fm.window, RVC_FIFO, NULL);
611 else if (S_ISSOCK(EMODE(j)))
612 wcolor_set(fm.window, RVC_SOCK, NULL);
613 if (S_ISDIR(EMODE(j))) {
614 mbstowcs(WBUF, ENAME(j), PATH_MAX);
615 if (ISLINK(j))
616 wcslcat(WBUF, L"/", sizeof(WBUF));
617 } else {
618 const char *suffix, *suffixes = "BKMGTPEZY";
619 off_t human_size = ESIZE(j) * 10;
620 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
621 int namecols = wcswidth(WBUF, length);
622 for (suffix = suffixes; human_size >= 10240; suffix++)
623 human_size = (human_size + 512) / 1024;
624 if (*suffix == 'B')
625 swprintf(WBUF + length, PATH_MAX - length,
626 L"%*d %c",
627 (int)(COLS - namecols - 6),
628 (int)human_size / 10, *suffix);
629 else
630 swprintf(WBUF + length, PATH_MAX - length,
631 L"%*d.%d %c",
632 (int)(COLS - namecols - 8),
633 (int)human_size / 10,
634 (int)human_size % 10, *suffix);
636 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
637 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
638 if (marking && MARKED(j)) {
639 wcolor_set(fm.window, RVC_MARKS, NULL);
640 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
641 } else
642 mvwaddch(fm.window, i + 1, 1, ' ');
643 if (j == ESEL)
644 wattr_off(fm.window, A_REVERSE, NULL);
646 for (; i < HEIGHT; i++)
647 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
648 if (fm.nfiles > HEIGHT) {
649 int center, height;
650 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
651 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
652 if (!height)
653 height = 1;
654 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
655 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
656 RVS_SCROLLBAR, height);
658 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
659 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
660 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
661 if (!fm.nfiles)
662 strlcpy(BUF2, "0/0", sizeof(BUF2));
663 else
664 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
665 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
666 color_set(RVC_STATUS, NULL);
667 mvaddstr(LINES - 1, STATUSPOS, BUF1);
668 wrefresh(fm.window);
671 /* Show a message on the status bar. */
672 static void __attribute__((format(printf, 2, 3)))
673 message(enum color c, const char *fmt, ...)
675 int len, pos;
676 va_list args;
678 va_start(args, fmt);
679 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
680 va_end(args);
681 len = strlen(BUF1);
682 pos = (STATUSPOS - len) / 2;
683 attr_on(A_BOLD, NULL);
684 color_set(c, NULL);
685 mvaddstr(LINES - 1, pos, BUF1);
686 color_set(DEFAULT, NULL);
687 attr_off(A_BOLD, NULL);
690 /* Clear message area, leaving only status info. */
691 static void
692 clear_message()
694 mvhline(LINES - 1, 0, ' ', STATUSPOS);
697 /* Comparison used to sort listing entries. */
698 static int
699 rowcmp(const void *a, const void *b)
701 int isdir1, isdir2, cmpdir;
702 const struct row *r1 = a;
703 const struct row *r2 = b;
704 isdir1 = S_ISDIR(r1->mode);
705 isdir2 = S_ISDIR(r2->mode);
706 cmpdir = isdir2 - isdir1;
707 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
710 /* Get all entries in current working directory. */
711 static int
712 ls(struct row **rowsp, uint8_t flags)
714 DIR *dp;
715 struct dirent *ep;
716 struct stat statbuf;
717 struct row *rows;
718 int i, n;
720 if (!(dp = opendir(".")))
721 return -1;
722 n = -2; /* We don't want the entries "." and "..". */
723 while (readdir(dp))
724 n++;
725 if (n == 0) {
726 closedir(dp);
727 return 0;
729 rewinddir(dp);
730 rows = xcalloc(n, sizeof(*rows));
731 i = 0;
732 while ((ep = readdir(dp))) {
733 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
734 continue;
735 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
736 continue;
737 lstat(ep->d_name, &statbuf);
738 rows[i].islink = S_ISLNK(statbuf.st_mode);
739 stat(ep->d_name, &statbuf);
740 if (S_ISDIR(statbuf.st_mode)) {
741 if (flags & SHOW_DIRS) {
742 xasprintf(&rows[i].name, "%s%s",
743 ep->d_name, rows[i].islink ? "" : "/");
744 rows[i].mode = statbuf.st_mode;
745 i++;
747 } else if (flags & SHOW_FILES) {
748 rows[i].name = xstrdup(ep->d_name);
749 rows[i].size = statbuf.st_size;
750 rows[i].mode = statbuf.st_mode;
751 i++;
754 n = i; /* Ignore unused space in array caused by filters. */
755 qsort(rows, n, sizeof(*rows), rowcmp);
756 closedir(dp);
757 *rowsp = rows;
758 return n;
761 static void
762 free_rows(struct row **rowsp, int nfiles)
764 int i;
766 for (i = 0; i < nfiles; i++)
767 free((*rowsp)[i].name);
768 free(*rowsp);
769 *rowsp = NULL;
772 /* Change working directory to the path in CWD. */
773 static void
774 cd(int reset)
776 int i, j;
778 message(CYAN, "Loading \"%s\"...", CWD);
779 refresh();
780 if (chdir(CWD) == -1) {
781 getcwd(CWD, PATH_MAX - 1);
782 if (CWD[strlen(CWD) - 1] != '/')
783 strlcat(CWD, "/", sizeof(CWD));
784 goto done;
786 if (reset)
787 ESEL = SCROLL = 0;
788 if (fm.nfiles)
789 free_rows(&fm.rows, fm.nfiles);
790 fm.nfiles = ls(&fm.rows, FLAGS);
791 if (!strcmp(CWD, fm.marks.dirpath)) {
792 for (i = 0; i < fm.nfiles; i++) {
793 for (j = 0; j < fm.marks.bulk; j++)
794 if (fm.marks.entries[j] &&
795 !strcmp(fm.marks.entries[j], ENAME(i)))
796 break;
797 MARKED(i) = j < fm.marks.bulk;
799 } else
800 for (i = 0; i < fm.nfiles; i++)
801 MARKED(i) = 0;
802 done:
803 clear_message();
804 update_view();
807 /* Select a target entry, if it is present. */
808 static void
809 try_to_sel(const char *target)
811 ESEL = 0;
812 if (!ISDIR(target))
813 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
814 ESEL++;
815 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
816 ESEL++;
819 /* Reload CWD, but try to keep selection. */
820 static void
821 reload()
823 if (fm.nfiles) {
824 strlcpy(INPUT, ENAME(ESEL), sizeof(INPUT));
825 cd(0);
826 try_to_sel(INPUT);
827 update_view();
828 } else
829 cd(1);
832 static off_t
833 count_dir(const char *path)
835 DIR *dp;
836 struct dirent *ep;
837 struct stat statbuf;
838 char subpath[PATH_MAX];
839 off_t total;
841 if (!(dp = opendir(path)))
842 return 0;
843 total = 0;
844 while ((ep = readdir(dp))) {
845 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
846 continue;
847 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
848 lstat(subpath, &statbuf);
849 if (S_ISDIR(statbuf.st_mode)) {
850 strlcat(subpath, "/", sizeof(subpath));
851 total += count_dir(subpath);
852 } else
853 total += statbuf.st_size;
855 closedir(dp);
856 return total;
859 static off_t
860 count_marked()
862 int i;
863 char *entry;
864 off_t total;
865 struct stat statbuf;
867 total = 0;
868 chdir(fm.marks.dirpath);
869 for (i = 0; i < fm.marks.bulk; i++) {
870 entry = fm.marks.entries[i];
871 if (entry) {
872 if (ISDIR(entry)) {
873 total += count_dir(entry);
874 } else {
875 lstat(entry, &statbuf);
876 total += statbuf.st_size;
880 chdir(CWD);
881 return total;
884 /*
885 * Recursively process a source directory using CWD as destination
886 * root. For each node (i.e. directory), do the following:
888 * 1. call pre(destination);
889 * 2. call proc() on every child leaf (i.e. files);
890 * 3. recurse into every child node;
891 * 4. call pos(source).
893 * E.g. to move directory /src/ (and all its contents) inside /dst/:
894 * strlcpy(CWD, "/dst/", sizeof(CWD));
895 * process_dir(adddir, movfile, deldir, "/src/");
896 */
897 static int
898 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
900 int ret;
901 DIR *dp;
902 struct dirent *ep;
903 struct stat statbuf;
904 char subpath[PATH_MAX];
906 ret = 0;
907 if (pre) {
908 char dstpath[PATH_MAX];
909 strlcpy(dstpath, CWD, sizeof(dstpath));
910 strlcat(dstpath, path + strlen(fm.marks.dirpath),
911 sizeof(dstpath));
912 ret |= pre(dstpath);
914 if (!(dp = opendir(path)))
915 return -1;
916 while ((ep = readdir(dp))) {
917 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
918 continue;
919 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
920 lstat(subpath, &statbuf);
921 if (S_ISDIR(statbuf.st_mode)) {
922 strcat(subpath, "/");
923 ret |= process_dir(pre, proc, pos, subpath);
924 } else
925 ret |= proc(subpath);
927 closedir(dp);
928 if (pos)
929 ret |= pos(path);
930 return ret;
933 /*
934 * Process all marked entries using CWD as destination root. All
935 * marked entries that are directories will be recursively processed.
936 * See process_dir() for details on the parameters.
937 */
938 static void
939 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
940 const char *msg_done)
942 int i, ret;
943 char *entry;
944 char path[PATH_MAX];
946 clear_message();
947 message(CYAN, "%s...", msg_doing);
948 refresh();
949 fm.prog = (struct prog){0, count_marked(), msg_doing};
950 for (i = 0; i < fm.marks.bulk; i++) {
951 entry = fm.marks.entries[i];
952 if (entry) {
953 ret = 0;
954 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
955 entry);
956 if (ISDIR(entry)) {
957 if (!strncmp(path, CWD, strlen(path)))
958 ret = -1;
959 else
960 ret = process_dir(pre, proc, pos, path);
961 } else
962 ret = proc(path);
963 if (!ret) {
964 del_mark(&fm.marks, entry);
965 reload();
969 fm.prog.total = 0;
970 reload();
971 if (!fm.marks.nentries)
972 message(GREEN, "%s all marked entries.", msg_done);
973 else
974 message(RED, "Some errors occured while %s.", msg_doing);
975 RV_ALERT();
978 static void
979 update_progress(off_t delta)
981 int percent;
983 if (!fm.prog.total)
984 return;
985 fm.prog.partial += delta;
986 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
987 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
988 refresh();
991 /* Wrappers for file operations. */
992 static int
993 delfile(const char *path)
995 int ret;
996 struct stat st;
998 ret = lstat(path, &st);
999 if (ret < 0)
1000 return ret;
1001 update_progress(st.st_size);
1002 return unlink(path);
1005 static int
1006 addfile(const char *path)
1008 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
1009 int ret;
1011 ret = creat(path, 0644);
1012 if (ret < 0)
1013 return ret;
1014 return close(ret);
1017 static int
1018 cpyfile(const char *srcpath)
1020 int src, dst, ret;
1021 size_t size;
1022 struct stat st;
1023 char buf[BUFSIZ];
1024 char dstpath[PATH_MAX];
1026 strlcpy(dstpath, CWD, sizeof(dstpath));
1027 strlcat(dstpath, srcpath + strlen(fm.marks.dirpath), sizeof(dstpath));
1028 ret = lstat(srcpath, &st);
1029 if (ret < 0)
1030 return ret;
1031 if (S_ISLNK(st.st_mode)) {
1032 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1033 if (ret < 0)
1034 return ret;
1035 BUF1[ret] = '\0';
1036 ret = symlink(BUF1, dstpath);
1037 } else {
1038 ret = src = open(srcpath, O_RDONLY);
1039 if (ret < 0)
1040 return ret;
1041 ret = dst = creat(dstpath, st.st_mode);
1042 if (ret < 0)
1043 return ret;
1044 while ((size = read(src, buf, BUFSIZ)) > 0) {
1045 write(dst, buf, size);
1046 update_progress(size);
1047 sync_signals();
1049 close(src);
1050 close(dst);
1051 ret = 0;
1053 return ret;
1056 static int
1057 adddir(const char *path)
1059 int ret;
1060 struct stat st;
1062 ret = stat(CWD, &st);
1063 if (ret < 0)
1064 return ret;
1065 return mkdir(path, st.st_mode);
1068 static int
1069 movfile(const char *srcpath)
1071 int ret;
1072 struct stat st;
1073 char dstpath[PATH_MAX];
1075 strlcpy(dstpath, CWD, sizeof(dstpath));
1076 strlcat(dstpath, srcpath + strlen(fm.marks.dirpath), sizeof(dstpath));
1077 ret = rename(srcpath, dstpath);
1078 if (ret == 0) {
1079 ret = lstat(dstpath, &st);
1080 if (ret < 0)
1081 return ret;
1082 update_progress(st.st_size);
1083 } else if (errno == EXDEV) {
1084 ret = cpyfile(srcpath);
1085 if (ret < 0)
1086 return ret;
1087 ret = unlink(srcpath);
1089 return ret;
1092 static void
1093 start_line_edit(const char *init_input)
1095 curs_set(TRUE);
1096 strncpy(INPUT, init_input, BUFLEN);
1097 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1098 fm.edit.right = BUFLEN - 1;
1099 fm.edit.buffer[BUFLEN] = L'\0';
1100 fm.edit_scroll = 0;
1103 /* Read input and change editing state accordingly. */
1104 static enum editstate
1105 get_line_edit()
1107 wchar_t eraser, killer, wch;
1108 int ret, length;
1110 ret = fm_get_wch((wint_t *)&wch);
1111 erasewchar(&eraser);
1112 killwchar(&killer);
1113 if (ret == KEY_CODE_YES) {
1114 if (wch == KEY_ENTER) {
1115 curs_set(FALSE);
1116 return CONFIRM;
1117 } else if (wch == KEY_LEFT) {
1118 if (EDIT_CAN_LEFT(fm.edit))
1119 EDIT_LEFT(fm.edit);
1120 } else if (wch == KEY_RIGHT) {
1121 if (EDIT_CAN_RIGHT(fm.edit))
1122 EDIT_RIGHT(fm.edit);
1123 } else if (wch == KEY_UP) {
1124 while (EDIT_CAN_LEFT(fm.edit))
1125 EDIT_LEFT(fm.edit);
1126 } else if (wch == KEY_DOWN) {
1127 while (EDIT_CAN_RIGHT(fm.edit))
1128 EDIT_RIGHT(fm.edit);
1129 } else if (wch == KEY_BACKSPACE) {
1130 if (EDIT_CAN_LEFT(fm.edit))
1131 EDIT_BACKSPACE(fm.edit);
1132 } else if (wch == KEY_DC) {
1133 if (EDIT_CAN_RIGHT(fm.edit))
1134 EDIT_DELETE(fm.edit);
1136 } else {
1137 if (wch == L'\r' || wch == L'\n') {
1138 curs_set(FALSE);
1139 return CONFIRM;
1140 } else if (wch == L'\t') {
1141 curs_set(FALSE);
1142 return CANCEL;
1143 } else if (wch == eraser) {
1144 if (EDIT_CAN_LEFT(fm.edit))
1145 EDIT_BACKSPACE(fm.edit);
1146 } else if (wch == killer) {
1147 EDIT_CLEAR(fm.edit);
1148 clear_message();
1149 } else if (iswprint(wch)) {
1150 if (!EDIT_FULL(fm.edit))
1151 EDIT_INSERT(fm.edit, wch);
1154 /* Encode edit contents in INPUT. */
1155 fm.edit.buffer[fm.edit.left] = L'\0';
1156 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1157 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1158 BUFLEN - length);
1159 return CONTINUE;
1162 /* Update line input on the screen. */
1163 static void
1164 update_input(const char *prompt, enum color c)
1166 int plen, ilen, maxlen;
1168 plen = strlen(prompt);
1169 ilen = mbstowcs(NULL, INPUT, 0);
1170 maxlen = STATUSPOS - plen - 2;
1171 if (ilen - fm.edit_scroll < maxlen)
1172 fm.edit_scroll = MAX(ilen - maxlen, 0);
1173 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1174 fm.edit_scroll = fm.edit.left - maxlen;
1175 else if (fm.edit.left < fm.edit_scroll)
1176 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1177 color_set(RVC_PROMPT, NULL);
1178 mvaddstr(LINES - 1, 0, prompt);
1179 color_set(c, NULL);
1180 mbstowcs(WBUF, INPUT, COLS);
1181 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1182 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1183 ' ');
1184 color_set(DEFAULT, NULL);
1185 if (fm.edit_scroll)
1186 mvaddch(LINES - 1, plen - 1, '<');
1187 if (ilen > fm.edit_scroll + maxlen)
1188 mvaddch(LINES - 1, plen + maxlen, '>');
1189 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1192 static void
1193 cmd_down(void)
1195 if (fm.nfiles)
1196 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1199 static void
1200 cmd_up(void)
1202 if (fm.nfiles)
1203 ESEL = MAX(ESEL - 1, 0);
1206 static void
1207 cmd_scroll_down(void)
1209 if (!fm.nfiles)
1210 return;
1211 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1212 if (fm.nfiles > HEIGHT)
1213 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1216 static void
1217 cmd_scroll_up(void)
1219 if (!fm.nfiles)
1220 return;
1221 ESEL = MAX(ESEL - HEIGHT, 0);
1222 SCROLL = MAX(SCROLL - HEIGHT, 0);
1225 static void
1226 cmd_man(void)
1228 spawn("man", "fm", NULL);
1231 static void
1232 cmd_jump_top(void)
1234 if (fm.nfiles)
1235 ESEL = 0;
1238 static void
1239 cmd_jump_bottom(void)
1241 if (fm.nfiles)
1242 ESEL = fm.nfiles - 1;
1245 static void
1246 cmd_cd_down(void)
1248 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1249 return;
1250 if (chdir(ENAME(ESEL)) == -1) {
1251 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1252 return;
1254 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1255 cd(1);
1258 static void
1259 cmd_cd_up(void)
1261 char *dirname, first;
1263 if (!strcmp(CWD, "/"))
1264 return;
1266 /* dirname(3) basically */
1267 dirname = strrchr(CWD, '/');
1268 *dirname-- = '\0';
1269 dirname = strrchr(CWD, '/') + 1;
1271 first = dirname[0];
1272 dirname[0] = '\0';
1273 cd(1);
1274 dirname[0] = first;
1275 strlcat(dirname, "/", sizeof(dirname));
1276 try_to_sel(dirname);
1277 dirname[0] = '\0';
1278 if (fm.nfiles > HEIGHT)
1279 SCROLL = ESEL - HEIGHT / 2;
1282 static void
1283 cmd_home(void)
1285 const char *home;
1287 if ((home = getenv("HOME")) == NULL) {
1288 message(RED, "HOME is not defined!");
1289 return;
1292 strlcpy(CWD, home, sizeof(CWD));
1293 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1294 strlcat(CWD, "/", sizeof(CWD));
1295 cd(1);
1298 static void
1299 cmd_copy_path(void)
1301 const char *path;
1302 FILE *f;
1304 if ((path = getenv("CLIP")) == NULL ||
1305 (f = fopen(path, "w")) == NULL) {
1306 /* use internal clipboard */
1307 strlcpy(clipboard, CWD, sizeof(clipboard));
1308 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1309 return;
1312 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1313 fputc('\0', f);
1314 fclose(f);
1317 static void
1318 cmd_paste_path(void)
1320 ssize_t r;
1321 const char *path;
1322 char *nl;
1323 FILE *f;
1324 char p[PATH_MAX];
1326 if ((path = getenv("CLIP")) != NULL &&
1327 (f = fopen(path, "w")) != NULL) {
1328 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1329 fclose(f);
1330 if (r == -1 || r == 0)
1331 goto err;
1332 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1333 goto err;
1336 strlcpy(p, clipboard, sizeof(p));
1337 strlcpy(CWD, clipboard, sizeof(CWD));
1338 if ((nl = strrchr(CWD, '/')) != NULL) {
1339 *nl = '\0';
1340 nl = strrchr(p, '/');
1341 assert(nl != NULL);
1343 if (strcmp(CWD, "/") != 0)
1344 strlcat(CWD, "/", sizeof(CWD));
1345 cd(1);
1346 try_to_sel(nl+1);
1347 return;
1349 err:
1350 memset(clipboard, 0, sizeof(clipboard));
1353 static void
1354 cmd_reload(void)
1356 reload();
1359 static void
1360 cmd_shell(void)
1362 const char *shell;
1364 if ((shell = getenv("SHELL")) == NULL)
1365 shell = FM_SHELL;
1366 spawn(shell, NULL);
1369 static void
1370 cmd_view(void)
1372 const char *pager;
1374 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1375 return;
1377 if ((pager = getenv("PAGER")) == NULL)
1378 pager = FM_PAGER;
1379 spawn(pager, ENAME(ESEL), NULL);
1382 static void
1383 cmd_edit(void)
1385 const char *editor;
1387 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1388 return;
1390 if ((editor = getenv("VISUAL")) == NULL ||
1391 (editor = getenv("EDITOR")) == NULL)
1392 editor = FM_ED;
1394 spawn(editor, ENAME(ESEL), NULL);
1397 static void
1398 cmd_open(void)
1400 const char *opener;
1402 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1403 return;
1405 if ((opener = getenv("OPENER")) == NULL)
1406 opener = FM_OPENER;
1408 spawn(opener, ENAME(ESEL), NULL);
1411 static void
1412 cmd_mark(void)
1414 if (MARKED(ESEL))
1415 del_mark(&fm.marks, ENAME(ESEL));
1416 else
1417 add_mark(&fm.marks, CWD, ENAME(ESEL));
1419 MARKED(ESEL) = !MARKED(ESEL);
1420 ESEL = (ESEL + 1) % fm.nfiles;
1423 static void
1424 cmd_toggle_mark(void)
1426 int i;
1428 for (i = 0; i < fm.nfiles; ++i) {
1429 if (MARKED(i))
1430 del_mark(&fm.marks, ENAME(i));
1431 else
1432 add_mark(&fm.marks, CWD, ENAME(ESEL));
1433 MARKED(i) = !MARKED(i);
1437 static void
1438 cmd_mark_all(void)
1440 int i;
1442 for (i = 0; i < fm.nfiles; ++i)
1443 if (!MARKED(i)) {
1444 add_mark(&fm.marks, CWD, ENAME(ESEL));
1445 MARKED(i) = 1;
1449 static void
1450 loop(void)
1452 int meta, ch, c;
1453 struct binding {
1454 int ch;
1455 #define K_META 1
1456 #define K_CTRL 2
1457 int chflags;
1458 void (*fn)(void);
1459 #define X_UPDV 1
1460 #define X_QUIT 2
1461 int flags;
1462 } bindings[] = {
1463 {'<', K_META, cmd_jump_top, X_UPDV},
1464 {'>', K_META, cmd_jump_bottom, X_UPDV},
1465 {'?', 0, cmd_man, 0},
1466 {'G', 0, cmd_jump_bottom, X_UPDV},
1467 {'H', 0, cmd_home, X_UPDV},
1468 {'J', 0, cmd_scroll_down, X_UPDV},
1469 {'K', 0, cmd_scroll_up, X_UPDV},
1470 {'M', 0, cmd_mark_all, X_UPDV},
1471 {'P', 0, cmd_paste_path, X_UPDV},
1472 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1473 {'Y', 0, cmd_copy_path, X_UPDV},
1474 {'^', 0, cmd_cd_up, X_UPDV},
1475 {'b', 0, cmd_cd_up, X_UPDV},
1476 {'e', 0, cmd_edit, X_UPDV},
1477 {'f', 0, cmd_cd_down, X_UPDV},
1478 {'g', 0, cmd_jump_top, X_UPDV},
1479 {'g', K_CTRL, NULL, X_UPDV},
1480 {'h', 0, cmd_cd_up, X_UPDV},
1481 {'j', 0, cmd_down, X_UPDV},
1482 {'k', 0, cmd_up, X_UPDV},
1483 {'l', 0, cmd_cd_down, X_UPDV},
1484 {'l', K_CTRL, cmd_reload, X_UPDV},
1485 {'n', 0, cmd_down, X_UPDV},
1486 {'n', K_CTRL, cmd_down, X_UPDV},
1487 {'m', 0, cmd_mark, X_UPDV},
1488 {'m', K_CTRL, cmd_shell, X_UPDV},
1489 {'o', 0, cmd_open, X_UPDV},
1490 {'p', 0, cmd_up, X_UPDV},
1491 {'p', K_CTRL, cmd_up, X_UPDV},
1492 {'q', 0, NULL, X_QUIT},
1493 {'t', 0, cmd_toggle_mark, X_UPDV},
1494 {'v', 0, cmd_view, X_UPDV},
1495 {'v', K_META, cmd_scroll_up, X_UPDV},
1496 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1497 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1498 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1499 {KEY_RESIZE, 0, NULL, X_UPDV},
1500 {KEY_RESIZE, K_META, NULL, X_UPDV},
1501 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1502 }, *b;
1503 size_t i;
1505 for (;;) {
1506 again:
1507 meta = 0;
1508 ch = fm_getch();
1509 if (ch == '\e') {
1510 meta = 1;
1511 if ((ch = fm_getch()) == '\e') {
1512 meta = 0;
1513 ch = '\e';
1517 clear_message();
1519 for (i = 0; i < nitems(bindings); ++i) {
1520 b = &bindings[i];
1521 c = b->ch;
1522 if (b->chflags & K_CTRL)
1523 c = CTRL(c);
1524 if ((!meta && b->chflags & K_META) || ch != c)
1525 continue;
1527 if (b->flags & X_QUIT)
1528 return;
1529 if (b->fn != NULL)
1530 b->fn();
1531 if (b->flags & X_UPDV)
1532 update_view();
1534 goto again;
1537 message(RED, "%s%s is undefined",
1538 meta ? "M-": "", keyname(ch));
1539 refresh();
1543 static __dead void
1544 usage(void)
1546 fprintf(stderr, "usage: %s [-hv] [-d file] [-m file] [dirs ...]\n",
1547 getprogname());
1548 fprintf(stderr, "version: %s\n", RV_VERSION);
1549 exit(1);
1552 int
1553 main(int argc, char *argv[])
1555 int i, ch;
1556 char *entry;
1557 DIR *d;
1558 FILE *save_cwd_file = NULL;
1559 FILE *save_marks_file = NULL;
1561 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1562 err(1, "pledge");
1564 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1565 switch (ch) {
1566 case 'd':
1567 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1568 err(1, "open %s", optarg);
1569 break;
1570 case 'h':
1571 usage();
1572 break;
1573 case 'm':
1574 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1575 err(1, "open %s", optarg);
1576 break;
1577 case 'v':
1578 printf("version: fm %s\n", RV_VERSION);
1579 return 0;
1580 default:
1581 usage();
1585 get_user_programs();
1586 init_term();
1587 fm.nfiles = 0;
1588 for (i = 0; i < 10; i++) {
1589 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1590 fm.tabs[i].flags = RV_FLAGS;
1592 strlcpy(fm.tabs[0].cwd, getenv("HOME"), sizeof(fm.tabs[0].cwd));
1593 for (i = 1; i < argc && i < 10; i++) {
1594 if ((d = opendir(argv[i]))) {
1595 realpath(argv[i], fm.tabs[i].cwd);
1596 closedir(d);
1597 } else {
1598 strlcpy(fm.tabs[i].cwd, fm.tabs[0].cwd,
1599 sizeof(fm.tabs[i].cwd));
1602 getcwd(fm.tabs[i].cwd, PATH_MAX);
1603 for (i++; i < 10; i++)
1604 strlcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd,
1605 sizeof(fm.tabs[i].cwd));
1606 for (i = 0; i < 10; i++)
1607 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1608 strlcat(fm.tabs[i].cwd, "/", sizeof(fm.tabs[i].cwd));
1609 fm.tab = 1;
1610 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1611 init_marks(&fm.marks);
1612 cd(1);
1613 strlcpy(clipboard, CWD, sizeof(clipboard));
1614 if (fm.nfiles > 0)
1615 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1617 loop();
1619 if (fm.nfiles)
1620 free_rows(&fm.rows, fm.nfiles);
1621 delwin(fm.window);
1622 if (save_cwd_file != NULL) {
1623 fputs(CWD, save_cwd_file);
1624 fclose(save_cwd_file);
1626 if (save_marks_file != NULL) {
1627 for (i = 0; i < fm.marks.bulk; i++) {
1628 entry = fm.marks.entries[i];
1629 if (entry)
1630 fprintf(save_marks_file, "%s%s\n",
1631 fm.marks.dirpath, entry);
1633 fclose(save_marks_file);
1635 free_marks(&fm.marks);
1636 return 0;