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 xmalloc(size_t size)
188 void *d;
190 if ((d = malloc(size)) == NULL)
191 quit("malloc");
192 return d;
195 static inline void *
196 xcalloc(size_t nmemb, size_t size)
198 void *d;
200 if ((d = calloc(nmemb, size)) == NULL)
201 quit("calloc");
202 return d;
205 static inline void *
206 xrealloc(void *p, size_t size)
208 void *d;
210 if ((d = realloc(p, size)) == NULL)
211 quit("realloc");
212 return d;
215 static void
216 init_marks(struct marks *marks)
218 strcpy(marks->dirpath, "");
219 marks->bulk = BULK_INIT;
220 marks->nentries = 0;
221 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
224 /* Unmark all entries. */
225 static void
226 mark_none(struct marks *marks)
228 int i;
230 strcpy(marks->dirpath, "");
231 for (i = 0; i < marks->bulk && marks->nentries; i++)
232 if (marks->entries[i]) {
233 free(marks->entries[i]);
234 marks->entries[i] = NULL;
235 marks->nentries--;
237 if (marks->bulk > BULK_THRESH) {
238 /* Reset bulk to free some memory. */
239 free(marks->entries);
240 marks->bulk = BULK_INIT;
241 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
245 static void
246 add_mark(struct marks *marks, char *dirpath, char *entry)
248 int i;
250 if (!strcmp(marks->dirpath, dirpath)) {
251 /* Append mark to directory. */
252 if (marks->nentries == marks->bulk) {
253 /* Expand bulk to accomodate new entry. */
254 int extra = marks->bulk / 2;
255 marks->bulk += extra; /* bulk *= 1.5; */
256 marks->entries = xrealloc(marks->entries,
257 marks->bulk * sizeof(*marks->entries));
258 memset(&marks->entries[marks->nentries], 0,
259 extra * sizeof(*marks->entries));
260 i = marks->nentries;
261 } else {
262 /* Search for empty slot (there must be one). */
263 for (i = 0; i < marks->bulk; i++)
264 if (!marks->entries[i])
265 break;
267 } else {
268 /* Directory changed. Discard old marks. */
269 mark_none(marks);
270 strcpy(marks->dirpath, dirpath);
271 i = 0;
273 marks->entries[i] = xmalloc(strlen(entry) + 1);
274 strcpy(marks->entries[i], entry);
275 marks->nentries++;
278 static void
279 del_mark(struct marks *marks, char *entry)
281 int i;
283 if (marks->nentries > 1) {
284 for (i = 0; i < marks->bulk; i++)
285 if (marks->entries[i] &&
286 !strcmp(marks->entries[i], entry))
287 break;
288 free(marks->entries[i]);
289 marks->entries[i] = NULL;
290 marks->nentries--;
291 } else
292 mark_none(marks);
295 static void
296 free_marks(struct marks *marks)
298 int i;
300 for (i = 0; i < marks->bulk && marks->nentries; i++)
301 if (marks->entries[i]) {
302 free(marks->entries[i]);
303 marks->nentries--;
305 free(marks->entries);
308 static void
309 handle_usr1(int sig)
311 fm.pending_usr1 = 1;
314 static void
315 handle_winch(int sig)
317 fm.pending_winch = 1;
320 static void
321 enable_handlers(void)
323 struct sigaction sa;
325 memset(&sa, 0, sizeof(struct sigaction));
326 sa.sa_handler = handle_usr1;
327 sigaction(SIGUSR1, &sa, NULL);
328 sa.sa_handler = handle_winch;
329 sigaction(SIGWINCH, &sa, NULL);
332 static void
333 disable_handlers(void)
335 struct sigaction sa;
337 memset(&sa, 0, sizeof(struct sigaction));
338 sa.sa_handler = SIG_DFL;
339 sigaction(SIGUSR1, &sa, NULL);
340 sigaction(SIGWINCH, &sa, NULL);
343 static void reload(void);
344 static void update_view(void);
346 /* Handle any signals received since last call. */
347 static void
348 sync_signals(void)
350 if (fm.pending_usr1) {
351 /* SIGUSR1 received: refresh directory listing. */
352 reload();
353 fm.pending_usr1 = 0;
355 if (fm.pending_winch) {
356 /* SIGWINCH received: resize application accordingly. */
357 delwin(fm.window);
358 endwin();
359 refresh();
360 clear();
361 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
362 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
363 SCROLL = ESEL - HEIGHT;
364 update_view();
365 fm.pending_winch = 0;
369 /*
370 * This function must be used in place of getch(). It handles signals
371 * while waiting for user input.
372 */
373 static int
374 fm_getch()
376 int ch;
378 while ((ch = getch()) == ERR)
379 sync_signals();
380 return ch;
383 /*
384 * This function must be used in place of get_wch(). It handles
385 * signals while waiting for user input.
386 */
387 static int
388 fm_get_wch(wint_t *wch)
390 wint_t ret;
392 while ((ret = get_wch(wch)) == (wint_t)ERR)
393 sync_signals();
394 return ret;
397 /* Get user programs from the environment. */
399 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
400 dst = getenv(#src);
402 static void
403 get_user_programs()
405 FM_ENV(user_shell, SHELL);
406 FM_ENV(user_pager, PAGER);
407 FM_ENV(user_editor, VISUAL);
408 if (!user_editor)
409 FM_ENV(user_editor, EDITOR);
410 FM_ENV(user_open, OPEN);
413 /* Do a fork-exec to external program (e.g. $EDITOR). */
414 static void
415 spawn(const char *argv0, ...)
417 pid_t pid;
418 int status;
419 size_t i;
420 const char *argv[16], *last;
421 va_list ap;
423 memset(argv, 0, sizeof(argv));
425 va_start(ap, argv0);
426 argv[0] = argv0;
427 for (i = 1; i < nitems(argv); ++i) {
428 last = va_arg(ap, const char *);
429 if (last == NULL)
430 break;
431 argv[i] = last;
433 va_end(ap);
435 if (last != NULL)
436 abort();
438 disable_handlers();
439 endwin();
441 switch (pid = fork()) {
442 case -1:
443 quit("fork");
444 case 0: /* child */
445 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
446 execvp(argv[0], (char *const *)argv);
447 quit("execvp");
448 default:
449 waitpid(pid, &status, 0);
450 enable_handlers();
451 kill(getpid(), SIGWINCH);
455 static void
456 shell_escaped_cat(char *buf, char *str, size_t n)
458 char *p = buf + strlen(buf);
459 *p++ = '\'';
460 for (n--; n; n--, str++) {
461 switch (*str) {
462 case '\'':
463 if (n < 4)
464 goto done;
465 strcpy(p, "'\\''");
466 n -= 4;
467 p += 4;
468 break;
469 case '\0':
470 goto done;
471 default:
472 *p = *str;
473 p++;
476 done:
477 strncat(p, "'", n);
480 static int
481 open_with_env(char *program, char *path)
483 if (program) {
484 #ifdef RV_SHELL
485 strncpy(BUF1, program, BUFLEN - 1);
486 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
487 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
488 spawn(RV_SHELL, "-c", BUF1, NULL );
489 #else
490 spawn(program, path, NULL);
491 #endif
492 return 1;
494 return 0;
497 /* Curses setup. */
498 static void
499 init_term()
501 setlocale(LC_ALL, "");
502 initscr();
503 raw();
504 timeout(100); /* For getch(). */
505 noecho();
506 nonl(); /* No NL->CR/NL on output. */
507 intrflush(stdscr, FALSE);
508 keypad(stdscr, TRUE);
509 curs_set(FALSE); /* Hide blinking cursor. */
510 if (has_colors()) {
511 short bg;
512 start_color();
513 #ifdef NCURSES_EXT_FUNCS
514 use_default_colors();
515 bg = -1;
516 #else
517 bg = COLOR_BLACK;
518 #endif
519 init_pair(RED, COLOR_RED, bg);
520 init_pair(GREEN, COLOR_GREEN, bg);
521 init_pair(YELLOW, COLOR_YELLOW, bg);
522 init_pair(BLUE, COLOR_BLUE, bg);
523 init_pair(CYAN, COLOR_CYAN, bg);
524 init_pair(MAGENTA, COLOR_MAGENTA, bg);
525 init_pair(WHITE, COLOR_WHITE, bg);
526 init_pair(BLACK, COLOR_BLACK, bg);
528 atexit((void (*)(void))endwin);
529 enable_handlers();
532 /* Update the listing view. */
533 static void
534 update_view()
536 int i, j;
537 int numsize;
538 int ishidden;
539 int marking;
541 mvhline(0, 0, ' ', COLS);
542 attr_on(A_BOLD, NULL);
543 color_set(RVC_TABNUM, NULL);
544 mvaddch(0, COLS - 2, fm.tab + '0');
545 attr_off(A_BOLD, NULL);
546 if (fm.marks.nentries) {
547 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
548 color_set(RVC_MARKS, NULL);
549 mvaddstr(0, COLS - 3 - numsize, BUF1);
550 } else
551 numsize = -1;
552 color_set(RVC_CWD, NULL);
553 mbstowcs(WBUF, CWD, PATH_MAX);
554 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
555 wcolor_set(fm.window, RVC_BORDER, NULL);
556 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
557 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
559 /*
560 * Selection might not be visible, due to cursor wrapping or
561 * window shrinking. In that case, the scroll must be moved to
562 * make it visible.
563 */
564 if (fm.nfiles > HEIGHT) {
565 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
566 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
567 } else
568 SCROLL = 0;
569 marking = !strcmp(CWD, fm.marks.dirpath);
570 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
571 ishidden = ENAME(j)[0] == '.';
572 if (j == ESEL)
573 wattr_on(fm.window, A_REVERSE, NULL);
574 if (ISLINK(j))
575 wcolor_set(fm.window, RVC_LINK, NULL);
576 else if (ishidden)
577 wcolor_set(fm.window, RVC_HIDDEN, NULL);
578 else if (S_ISREG(EMODE(j))) {
579 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
580 wcolor_set(fm.window, RVC_EXEC, NULL);
581 else
582 wcolor_set(fm.window, RVC_REG, NULL);
583 } else if (S_ISDIR(EMODE(j)))
584 wcolor_set(fm.window, RVC_DIR, NULL);
585 else if (S_ISCHR(EMODE(j)))
586 wcolor_set(fm.window, RVC_CHR, NULL);
587 else if (S_ISBLK(EMODE(j)))
588 wcolor_set(fm.window, RVC_BLK, NULL);
589 else if (S_ISFIFO(EMODE(j)))
590 wcolor_set(fm.window, RVC_FIFO, NULL);
591 else if (S_ISSOCK(EMODE(j)))
592 wcolor_set(fm.window, RVC_SOCK, NULL);
593 if (S_ISDIR(EMODE(j))) {
594 mbstowcs(WBUF, ENAME(j), PATH_MAX);
595 if (ISLINK(j))
596 wcscat(WBUF, L"/");
597 } else {
598 const char *suffix, *suffixes = "BKMGTPEZY";
599 off_t human_size = ESIZE(j) * 10;
600 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
601 int namecols = wcswidth(WBUF, length);
602 for (suffix = suffixes; human_size >= 10240; suffix++)
603 human_size = (human_size + 512) / 1024;
604 if (*suffix == 'B')
605 swprintf(WBUF + length, PATH_MAX - length,
606 L"%*d %c",
607 (int)(COLS - namecols - 6),
608 (int)human_size / 10, *suffix);
609 else
610 swprintf(WBUF + length, PATH_MAX - length,
611 L"%*d.%d %c",
612 (int)(COLS - namecols - 8),
613 (int)human_size / 10,
614 (int)human_size % 10, *suffix);
616 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
617 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
618 if (marking && MARKED(j)) {
619 wcolor_set(fm.window, RVC_MARKS, NULL);
620 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
621 } else
622 mvwaddch(fm.window, i + 1, 1, ' ');
623 if (j == ESEL)
624 wattr_off(fm.window, A_REVERSE, NULL);
626 for (; i < HEIGHT; i++)
627 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
628 if (fm.nfiles > HEIGHT) {
629 int center, height;
630 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
631 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
632 if (!height)
633 height = 1;
634 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
635 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
636 RVS_SCROLLBAR, height);
638 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
639 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
640 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
641 if (!fm.nfiles)
642 strcpy(BUF2, "0/0");
643 else
644 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
645 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
646 color_set(RVC_STATUS, NULL);
647 mvaddstr(LINES - 1, STATUSPOS, BUF1);
648 wrefresh(fm.window);
651 /* Show a message on the status bar. */
652 static void __attribute__((format(printf, 2, 3)))
653 message(enum color c, const char *fmt, ...)
655 int len, pos;
656 va_list args;
658 va_start(args, fmt);
659 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
660 va_end(args);
661 len = strlen(BUF1);
662 pos = (STATUSPOS - len) / 2;
663 attr_on(A_BOLD, NULL);
664 color_set(c, NULL);
665 mvaddstr(LINES - 1, pos, BUF1);
666 color_set(DEFAULT, NULL);
667 attr_off(A_BOLD, NULL);
670 /* Clear message area, leaving only status info. */
671 static void
672 clear_message()
674 mvhline(LINES - 1, 0, ' ', STATUSPOS);
677 /* Comparison used to sort listing entries. */
678 static int
679 rowcmp(const void *a, const void *b)
681 int isdir1, isdir2, cmpdir;
682 const struct row *r1 = a;
683 const struct row *r2 = b;
684 isdir1 = S_ISDIR(r1->mode);
685 isdir2 = S_ISDIR(r2->mode);
686 cmpdir = isdir2 - isdir1;
687 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
690 /* Get all entries in current working directory. */
691 static int
692 ls(struct row **rowsp, uint8_t flags)
694 DIR *dp;
695 struct dirent *ep;
696 struct stat statbuf;
697 struct row *rows;
698 int i, n;
700 if (!(dp = opendir(".")))
701 return -1;
702 n = -2; /* We don't want the entries "." and "..". */
703 while (readdir(dp))
704 n++;
705 if (n == 0) {
706 closedir(dp);
707 return 0;
709 rewinddir(dp);
710 rows = xmalloc(n * sizeof(*rows));
711 i = 0;
712 while ((ep = readdir(dp))) {
713 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
714 continue;
715 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
716 continue;
717 lstat(ep->d_name, &statbuf);
718 rows[i].islink = S_ISLNK(statbuf.st_mode);
719 stat(ep->d_name, &statbuf);
720 if (S_ISDIR(statbuf.st_mode)) {
721 if (flags & SHOW_DIRS) {
722 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
723 strcpy(rows[i].name, ep->d_name);
724 if (!rows[i].islink)
725 strcat(rows[i].name, "/");
726 rows[i].mode = statbuf.st_mode;
727 i++;
729 } else if (flags & SHOW_FILES) {
730 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
731 strcpy(rows[i].name, ep->d_name);
732 rows[i].size = statbuf.st_size;
733 rows[i].mode = statbuf.st_mode;
734 i++;
737 n = i; /* Ignore unused space in array caused by filters. */
738 qsort(rows, n, sizeof(*rows), rowcmp);
739 closedir(dp);
740 *rowsp = rows;
741 return n;
744 static void
745 free_rows(struct row **rowsp, int nfiles)
747 int i;
749 for (i = 0; i < nfiles; i++)
750 free((*rowsp)[i].name);
751 free(*rowsp);
752 *rowsp = NULL;
755 /* Change working directory to the path in CWD. */
756 static void
757 cd(int reset)
759 int i, j;
761 message(CYAN, "Loading \"%s\"...", CWD);
762 refresh();
763 if (chdir(CWD) == -1) {
764 getcwd(CWD, PATH_MAX - 1);
765 if (CWD[strlen(CWD) - 1] != '/')
766 strcat(CWD, "/");
767 goto done;
769 if (reset)
770 ESEL = SCROLL = 0;
771 if (fm.nfiles)
772 free_rows(&fm.rows, fm.nfiles);
773 fm.nfiles = ls(&fm.rows, FLAGS);
774 if (!strcmp(CWD, fm.marks.dirpath)) {
775 for (i = 0; i < fm.nfiles; i++) {
776 for (j = 0; j < fm.marks.bulk; j++)
777 if (fm.marks.entries[j] &&
778 !strcmp(fm.marks.entries[j], ENAME(i)))
779 break;
780 MARKED(i) = j < fm.marks.bulk;
782 } else
783 for (i = 0; i < fm.nfiles; i++)
784 MARKED(i) = 0;
785 done:
786 clear_message();
787 update_view();
790 /* Select a target entry, if it is present. */
791 static void
792 try_to_sel(const char *target)
794 ESEL = 0;
795 if (!ISDIR(target))
796 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
797 ESEL++;
798 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
799 ESEL++;
802 /* Reload CWD, but try to keep selection. */
803 static void
804 reload()
806 if (fm.nfiles) {
807 strcpy(INPUT, ENAME(ESEL));
808 cd(0);
809 try_to_sel(INPUT);
810 update_view();
811 } else
812 cd(1);
815 static off_t
816 count_dir(const char *path)
818 DIR *dp;
819 struct dirent *ep;
820 struct stat statbuf;
821 char subpath[PATH_MAX];
822 off_t total;
824 if (!(dp = opendir(path)))
825 return 0;
826 total = 0;
827 while ((ep = readdir(dp))) {
828 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
829 continue;
830 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
831 lstat(subpath, &statbuf);
832 if (S_ISDIR(statbuf.st_mode)) {
833 strcat(subpath, "/");
834 total += count_dir(subpath);
835 } else
836 total += statbuf.st_size;
838 closedir(dp);
839 return total;
842 static off_t
843 count_marked()
845 int i;
846 char *entry;
847 off_t total;
848 struct stat statbuf;
850 total = 0;
851 chdir(fm.marks.dirpath);
852 for (i = 0; i < fm.marks.bulk; i++) {
853 entry = fm.marks.entries[i];
854 if (entry) {
855 if (ISDIR(entry)) {
856 total += count_dir(entry);
857 } else {
858 lstat(entry, &statbuf);
859 total += statbuf.st_size;
863 chdir(CWD);
864 return total;
867 /*
868 * Recursively process a source directory using CWD as destination
869 * root. For each node (i.e. directory), do the following:
871 * 1. call pre(destination);
872 * 2. call proc() on every child leaf (i.e. files);
873 * 3. recurse into every child node;
874 * 4. call pos(source).
876 * E.g. to move directory /src/ (and all its contents) inside /dst/:
877 * strcpy(CWD, "/dst/");
878 * process_dir(adddir, movfile, deldir, "/src/");
879 */
880 static int
881 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
883 int ret;
884 DIR *dp;
885 struct dirent *ep;
886 struct stat statbuf;
887 char subpath[PATH_MAX];
889 ret = 0;
890 if (pre) {
891 char dstpath[PATH_MAX];
892 strcpy(dstpath, CWD);
893 strcat(dstpath, path + strlen(fm . marks . dirpath));
894 ret |= pre(dstpath);
896 if (!(dp = opendir(path)))
897 return -1;
898 while ((ep = readdir(dp))) {
899 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
900 continue;
901 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
902 lstat(subpath, &statbuf);
903 if (S_ISDIR(statbuf.st_mode)) {
904 strcat(subpath, "/");
905 ret |= process_dir(pre, proc, pos, subpath);
906 } else
907 ret |= proc(subpath);
909 closedir(dp);
910 if (pos)
911 ret |= pos(path);
912 return ret;
915 /*
916 * Process all marked entries using CWD as destination root. All
917 * marked entries that are directories will be recursively processed.
918 * See process_dir() for details on the parameters.
919 */
920 static void
921 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
922 const char *msg_done)
924 int i, ret;
925 char *entry;
926 char path[PATH_MAX];
928 clear_message();
929 message(CYAN, "%s...", msg_doing);
930 refresh();
931 fm.prog = (struct prog){0, count_marked(), msg_doing};
932 for (i = 0; i < fm.marks.bulk; i++) {
933 entry = fm.marks.entries[i];
934 if (entry) {
935 ret = 0;
936 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
937 entry);
938 if (ISDIR(entry)) {
939 if (!strncmp(path, CWD, strlen(path)))
940 ret = -1;
941 else
942 ret = process_dir(pre, proc, pos, path);
943 } else
944 ret = proc(path);
945 if (!ret) {
946 del_mark(&fm.marks, entry);
947 reload();
951 fm.prog.total = 0;
952 reload();
953 if (!fm.marks.nentries)
954 message(GREEN, "%s all marked entries.", msg_done);
955 else
956 message(RED, "Some errors occured while %s.", msg_doing);
957 RV_ALERT();
960 static void
961 update_progress(off_t delta)
963 int percent;
965 if (!fm.prog.total)
966 return;
967 fm.prog.partial += delta;
968 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
969 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
970 refresh();
973 /* Wrappers for file operations. */
974 static int
975 delfile(const char *path)
977 int ret;
978 struct stat st;
980 ret = lstat(path, &st);
981 if (ret < 0)
982 return ret;
983 update_progress(st.st_size);
984 return unlink(path);
987 static PROCESS deldir = rmdir;
988 static int
989 addfile(const char *path)
991 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
992 int ret;
994 ret = creat(path, 0644);
995 if (ret < 0)
996 return ret;
997 return close(ret);
1000 static int
1001 cpyfile(const char *srcpath)
1003 int src, dst, ret;
1004 size_t size;
1005 struct stat st;
1006 char buf[BUFSIZ];
1007 char dstpath[PATH_MAX];
1009 strcpy(dstpath, CWD);
1010 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1011 ret = lstat(srcpath, &st);
1012 if (ret < 0)
1013 return ret;
1014 if (S_ISLNK(st.st_mode)) {
1015 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1016 if (ret < 0)
1017 return ret;
1018 BUF1[ret] = '\0';
1019 ret = symlink(BUF1, dstpath);
1020 } else {
1021 ret = src = open(srcpath, O_RDONLY);
1022 if (ret < 0)
1023 return ret;
1024 ret = dst = creat(dstpath, st.st_mode);
1025 if (ret < 0)
1026 return ret;
1027 while ((size = read(src, buf, BUFSIZ)) > 0) {
1028 write(dst, buf, size);
1029 update_progress(size);
1030 sync_signals();
1032 close(src);
1033 close(dst);
1034 ret = 0;
1036 return ret;
1039 static int
1040 adddir(const char *path)
1042 int ret;
1043 struct stat st;
1045 ret = stat(CWD, &st);
1046 if (ret < 0)
1047 return ret;
1048 return mkdir(path, st.st_mode);
1051 static int
1052 movfile(const char *srcpath)
1054 int ret;
1055 struct stat st;
1056 char dstpath[PATH_MAX];
1058 strcpy(dstpath, CWD);
1059 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1060 ret = rename(srcpath, dstpath);
1061 if (ret == 0) {
1062 ret = lstat(dstpath, &st);
1063 if (ret < 0)
1064 return ret;
1065 update_progress(st.st_size);
1066 } else if (errno == EXDEV) {
1067 ret = cpyfile(srcpath);
1068 if (ret < 0)
1069 return ret;
1070 ret = unlink(srcpath);
1072 return ret;
1075 static void
1076 start_line_edit(const char *init_input)
1078 curs_set(TRUE);
1079 strncpy(INPUT, init_input, BUFLEN);
1080 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1081 fm.edit.right = BUFLEN - 1;
1082 fm.edit.buffer[BUFLEN] = L'\0';
1083 fm.edit_scroll = 0;
1086 /* Read input and change editing state accordingly. */
1087 static enum editstate
1088 get_line_edit()
1090 wchar_t eraser, killer, wch;
1091 int ret, length;
1093 ret = fm_get_wch((wint_t *)&wch);
1094 erasewchar(&eraser);
1095 killwchar(&killer);
1096 if (ret == KEY_CODE_YES) {
1097 if (wch == KEY_ENTER) {
1098 curs_set(FALSE);
1099 return CONFIRM;
1100 } else if (wch == KEY_LEFT) {
1101 if (EDIT_CAN_LEFT(fm.edit))
1102 EDIT_LEFT(fm.edit);
1103 } else if (wch == KEY_RIGHT) {
1104 if (EDIT_CAN_RIGHT(fm.edit))
1105 EDIT_RIGHT(fm.edit);
1106 } else if (wch == KEY_UP) {
1107 while (EDIT_CAN_LEFT(fm.edit))
1108 EDIT_LEFT(fm.edit);
1109 } else if (wch == KEY_DOWN) {
1110 while (EDIT_CAN_RIGHT(fm.edit))
1111 EDIT_RIGHT(fm.edit);
1112 } else if (wch == KEY_BACKSPACE) {
1113 if (EDIT_CAN_LEFT(fm.edit))
1114 EDIT_BACKSPACE(fm.edit);
1115 } else if (wch == KEY_DC) {
1116 if (EDIT_CAN_RIGHT(fm.edit))
1117 EDIT_DELETE(fm.edit);
1119 } else {
1120 if (wch == L'\r' || wch == L'\n') {
1121 curs_set(FALSE);
1122 return CONFIRM;
1123 } else if (wch == L'\t') {
1124 curs_set(FALSE);
1125 return CANCEL;
1126 } else if (wch == eraser) {
1127 if (EDIT_CAN_LEFT(fm.edit))
1128 EDIT_BACKSPACE(fm.edit);
1129 } else if (wch == killer) {
1130 EDIT_CLEAR(fm.edit);
1131 clear_message();
1132 } else if (iswprint(wch)) {
1133 if (!EDIT_FULL(fm.edit))
1134 EDIT_INSERT(fm.edit, wch);
1137 /* Encode edit contents in INPUT. */
1138 fm.edit.buffer[fm.edit.left] = L'\0';
1139 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1140 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1141 BUFLEN - length);
1142 return CONTINUE;
1145 /* Update line input on the screen. */
1146 static void
1147 update_input(const char *prompt, enum color c)
1149 int plen, ilen, maxlen;
1151 plen = strlen(prompt);
1152 ilen = mbstowcs(NULL, INPUT, 0);
1153 maxlen = STATUSPOS - plen - 2;
1154 if (ilen - fm.edit_scroll < maxlen)
1155 fm.edit_scroll = MAX(ilen - maxlen, 0);
1156 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1157 fm.edit_scroll = fm.edit.left - maxlen;
1158 else if (fm.edit.left < fm.edit_scroll)
1159 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1160 color_set(RVC_PROMPT, NULL);
1161 mvaddstr(LINES - 1, 0, prompt);
1162 color_set(c, NULL);
1163 mbstowcs(WBUF, INPUT, COLS);
1164 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1165 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1166 ' ');
1167 color_set(DEFAULT, NULL);
1168 if (fm.edit_scroll)
1169 mvaddch(LINES - 1, plen - 1, '<');
1170 if (ilen > fm.edit_scroll + maxlen)
1171 mvaddch(LINES - 1, plen + maxlen, '>');
1172 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1175 static void
1176 cmd_down(void)
1178 if (fm.nfiles)
1179 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1182 static void
1183 cmd_up(void)
1185 if (fm.nfiles)
1186 ESEL = MAX(ESEL - 1, 0);
1189 static void
1190 cmd_scroll_down(void)
1192 if (!fm.nfiles)
1193 return;
1194 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1195 if (fm.nfiles > HEIGHT)
1196 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1199 static void
1200 cmd_scroll_up(void)
1202 if (!fm.nfiles)
1203 return;
1204 ESEL = MAX(ESEL - HEIGHT, 0);
1205 SCROLL = MAX(SCROLL - HEIGHT, 0);
1208 static void
1209 cmd_man(void)
1211 spawn("man", "fm", NULL);
1214 static void
1215 cmd_jump_top(void)
1217 if (fm.nfiles)
1218 ESEL = 0;
1221 static void
1222 cmd_jump_bottom(void)
1224 if (fm.nfiles)
1225 ESEL = fm.nfiles - 1;
1228 static void
1229 cmd_cd_down(void)
1231 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1232 return;
1233 if (chdir(ENAME(ESEL)) == -1) {
1234 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1235 return;
1237 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1238 cd(1);
1241 static void
1242 cmd_cd_up(void)
1244 char *dirname, first;
1246 if (!strcmp(CWD, "/"))
1247 return;
1249 /* dirname(3) basically */
1250 dirname = strrchr(CWD, '/');
1251 *dirname-- = '\0';
1252 dirname = strrchr(CWD, '/') + 1;
1254 first = dirname[0];
1255 dirname[0] = '\0';
1256 cd(1);
1257 dirname[0] = first;
1258 strlcat(dirname, "/", sizeof(dirname));
1259 try_to_sel(dirname);
1260 dirname[0] = '\0';
1261 if (fm.nfiles > HEIGHT)
1262 SCROLL = ESEL - HEIGHT / 2;
1265 static void
1266 cmd_home(void)
1268 const char *home;
1270 if ((home = getenv("HOME")) == NULL) {
1271 message(RED, "HOME is not defined!");
1272 return;
1275 strlcpy(CWD, home, sizeof(CWD));
1276 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1277 strlcat(CWD, "/", sizeof(CWD));
1278 cd(1);
1281 static void
1282 cmd_copy_path(void)
1284 const char *path;
1285 FILE *f;
1287 if ((path = getenv("CLIP")) == NULL ||
1288 (f = fopen(path, "w")) == NULL) {
1289 /* use internal clipboard */
1290 strlcpy(clipboard, CWD, sizeof(clipboard));
1291 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1292 return;
1295 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1296 fputc('\0', f);
1297 fclose(f);
1300 static void
1301 cmd_paste_path(void)
1303 ssize_t r;
1304 const char *path;
1305 char *nl;
1306 FILE *f;
1307 char p[PATH_MAX];
1309 if ((path = getenv("CLIP")) != NULL &&
1310 (f = fopen(path, "w")) != NULL) {
1311 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1312 fclose(f);
1313 if (r == -1 || r == 0)
1314 goto err;
1315 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1316 goto err;
1319 strlcpy(p, clipboard, sizeof(p));
1320 strlcpy(CWD, clipboard, sizeof(CWD));
1321 if ((nl = strrchr(CWD, '/')) != NULL) {
1322 *nl = '\0';
1323 nl = strrchr(p, '/');
1324 assert(nl != NULL);
1326 if (strcmp(CWD, "/") != 0)
1327 strlcat(CWD, "/", sizeof(CWD));
1328 cd(1);
1329 try_to_sel(nl+1);
1330 return;
1332 err:
1333 memset(clipboard, 0, sizeof(clipboard));
1336 static void
1337 cmd_reload(void)
1339 reload();
1342 static void
1343 cmd_shell(void)
1345 const char *shell;
1347 if ((shell = getenv("SHELL")) == NULL)
1348 shell = FM_SHELL;
1349 spawn(shell, NULL);
1352 static void
1353 cmd_view(void)
1355 const char *pager;
1357 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1358 return;
1360 if ((pager = getenv("PAGER")) == NULL)
1361 pager = FM_PAGER;
1362 spawn(pager, ENAME(ESEL), NULL);
1365 static void
1366 cmd_edit(void)
1368 const char *editor;
1370 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1371 return;
1373 if ((editor = getenv("VISUAL")) == NULL ||
1374 (editor = getenv("EDITOR")) == NULL)
1375 editor = FM_ED;
1377 spawn(editor, ENAME(ESEL), NULL);
1380 static void
1381 cmd_open(void)
1383 const char *opener;
1385 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1386 return;
1388 if ((opener = getenv("OPENER")) == NULL)
1389 opener = FM_OPENER;
1391 spawn(opener, ENAME(ESEL), NULL);
1394 static void
1395 cmd_mark(void)
1397 if (MARKED(ESEL))
1398 del_mark(&fm.marks, ENAME(ESEL));
1399 else
1400 add_mark(&fm.marks, CWD, ENAME(ESEL));
1402 MARKED(ESEL) = !MARKED(ESEL);
1403 ESEL = (ESEL + 1) % fm.nfiles;
1406 static void
1407 cmd_toggle_mark(void)
1409 int i;
1411 for (i = 0; i < fm.nfiles; ++i) {
1412 if (MARKED(i))
1413 del_mark(&fm.marks, ENAME(i));
1414 else
1415 add_mark(&fm.marks, CWD, ENAME(ESEL));
1416 MARKED(i) = !MARKED(i);
1420 static void
1421 cmd_mark_all(void)
1423 int i;
1425 for (i = 0; i < fm.nfiles; ++i)
1426 if (!MARKED(i)) {
1427 add_mark(&fm.marks, CWD, ENAME(ESEL));
1428 MARKED(i) = 1;
1432 static void
1433 loop(void)
1435 int meta, ch, c;
1436 struct binding {
1437 int ch;
1438 #define K_META 1
1439 #define K_CTRL 2
1440 int chflags;
1441 void (*fn)(void);
1442 #define X_UPDV 1
1443 #define X_QUIT 2
1444 int flags;
1445 } bindings[] = {
1446 {'<', K_META, cmd_jump_top, X_UPDV},
1447 {'>', K_META, cmd_jump_bottom, X_UPDV},
1448 {'?', 0, cmd_man, 0},
1449 {'G', 0, cmd_jump_bottom, X_UPDV},
1450 {'H', 0, cmd_home, X_UPDV},
1451 {'J', 0, cmd_scroll_down, X_UPDV},
1452 {'K', 0, cmd_scroll_up, X_UPDV},
1453 {'M', 0, cmd_mark_all, X_UPDV},
1454 {'P', 0, cmd_paste_path, X_UPDV},
1455 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1456 {'Y', 0, cmd_copy_path, X_UPDV},
1457 {'^', 0, cmd_cd_up, X_UPDV},
1458 {'b', 0, cmd_cd_up, X_UPDV},
1459 {'e', 0, cmd_edit, X_UPDV},
1460 {'f', 0, cmd_cd_down, X_UPDV},
1461 {'g', 0, cmd_jump_top, X_UPDV},
1462 {'g', K_CTRL, NULL, X_UPDV},
1463 {'h', 0, cmd_cd_up, X_UPDV},
1464 {'j', 0, cmd_down, X_UPDV},
1465 {'k', 0, cmd_up, X_UPDV},
1466 {'l', 0, cmd_cd_down, X_UPDV},
1467 {'l', K_CTRL, cmd_reload, X_UPDV},
1468 {'n', 0, cmd_down, X_UPDV},
1469 {'n', K_CTRL, cmd_down, X_UPDV},
1470 {'m', 0, cmd_mark, X_UPDV},
1471 {'m', K_CTRL, cmd_shell, X_UPDV},
1472 {'o', 0, cmd_open, X_UPDV},
1473 {'p', 0, cmd_up, X_UPDV},
1474 {'p', K_CTRL, cmd_up, X_UPDV},
1475 {'q', 0, NULL, X_QUIT},
1476 {'t', 0, cmd_toggle_mark, X_UPDV},
1477 {'v', 0, cmd_view, X_UPDV},
1478 {'v', K_META, cmd_scroll_up, X_UPDV},
1479 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1480 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1481 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1482 {KEY_RESIZE, 0, NULL, X_UPDV},
1483 {KEY_RESIZE, K_META, NULL, X_UPDV},
1484 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1485 }, *b;
1486 size_t i;
1488 for (;;) {
1489 again:
1490 meta = 0;
1491 ch = fm_getch();
1492 if (ch == '\e') {
1493 meta = 1;
1494 if ((ch = fm_getch()) == '\e') {
1495 meta = 0;
1496 ch = '\e';
1500 clear_message();
1502 for (i = 0; i < nitems(bindings); ++i) {
1503 b = &bindings[i];
1504 c = b->ch;
1505 if (b->chflags & K_CTRL)
1506 c = CTRL(c);
1507 if ((!meta && b->chflags & K_META) || ch != c)
1508 continue;
1510 if (b->flags & X_QUIT)
1511 return;
1512 if (b->fn != NULL)
1513 b->fn();
1514 if (b->flags & X_UPDV)
1515 update_view();
1517 goto again;
1520 message(RED, "%s%s is undefined",
1521 meta ? "M-": "", keyname(ch));
1522 refresh();
1526 int
1527 main(int argc, char *argv[])
1529 int i, ch;
1530 char *program;
1531 char *entry;
1532 const char *key;
1533 const char *clip_path;
1534 DIR *d;
1535 enum editstate edit_stat;
1536 FILE *save_cwd_file = NULL;
1537 FILE *save_marks_file = NULL;
1538 FILE *clip_file;
1540 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1541 switch (ch) {
1542 case 'd':
1543 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1544 err(1, "open %s", optarg);
1545 break;
1546 case 'h':
1547 printf(""
1548 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1549 "Browse current directory or the ones specified.\n"
1550 "\n"
1551 "See fm(1) for more information.\n"
1552 "fm homepage <https://github.com/omar-polo/fm>\n");
1553 return 0;
1554 case 'm':
1555 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1556 err(1, "open %s", optarg);
1557 break;
1558 case 'v':
1559 printf("version: fm %s\n", RV_VERSION);
1560 return 0;
1564 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1565 err(1, "pledge");
1567 get_user_programs();
1568 init_term();
1569 fm.nfiles = 0;
1570 for (i = 0; i < 10; i++) {
1571 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1572 fm.tabs[i].flags = RV_FLAGS;
1574 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1575 for (i = 1; i < argc && i < 10; i++) {
1576 if ((d = opendir(argv[i]))) {
1577 realpath(argv[i], fm.tabs[i].cwd);
1578 closedir(d);
1579 } else
1580 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1582 getcwd(fm.tabs[i].cwd, PATH_MAX);
1583 for (i++; i < 10; i++)
1584 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1585 for (i = 0; i < 10; i++)
1586 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1587 strcat(fm.tabs[i].cwd, "/");
1588 fm.tab = 1;
1589 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1590 init_marks(&fm.marks);
1591 cd(1);
1592 strlcpy(clipboard, CWD, sizeof(clipboard));
1593 if (fm.nfiles > 0)
1594 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1596 loop();
1598 if (fm.nfiles)
1599 free_rows(&fm.rows, fm.nfiles);
1600 delwin(fm.window);
1601 if (save_cwd_file != NULL) {
1602 fputs(CWD, save_cwd_file);
1603 fclose(save_cwd_file);
1605 if (save_marks_file != NULL) {
1606 for (i = 0; i < fm.marks.bulk; i++) {
1607 entry = fm.marks.entries[i];
1608 if (entry)
1609 fprintf(save_marks_file, "%s%s\n",
1610 fm.marks.dirpath, entry);
1612 fclose(save_marks_file);
1614 free_marks(&fm.marks);
1615 return 0;