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 inline int
216 xasprintf(char **ret, const char *fmt, ...)
218 va_list ap;
219 int r;
221 va_start(ap, fmt);
222 r = vasprintf(ret, fmt, ap);
223 va_end(ap);
225 if (r == -1)
226 quit("asprintf");
227 return r;
230 static inline char *
231 xstrdup(char *str)
233 char *s;
235 if ((s = strdup(str)) == NULL)
236 quit("strdup");
237 return s;
240 static void
241 init_marks(struct marks *marks)
243 strlcpy(marks->dirpath, "", sizeof(marks->dirpath));
244 marks->bulk = BULK_INIT;
245 marks->nentries = 0;
246 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
249 /* Unmark all entries. */
250 static void
251 mark_none(struct marks *marks)
253 int i;
255 strlcpy(marks->dirpath, "", sizeof(marks->dirpath));
256 for (i = 0; i < marks->bulk && marks->nentries; i++)
257 if (marks->entries[i]) {
258 free(marks->entries[i]);
259 marks->entries[i] = NULL;
260 marks->nentries--;
262 if (marks->bulk > BULK_THRESH) {
263 /* Reset bulk to free some memory. */
264 free(marks->entries);
265 marks->bulk = BULK_INIT;
266 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
270 static void
271 add_mark(struct marks *marks, char *dirpath, char *entry)
273 int i;
275 if (!strcmp(marks->dirpath, dirpath)) {
276 /* Append mark to directory. */
277 if (marks->nentries == marks->bulk) {
278 /* Expand bulk to accomodate new entry. */
279 int extra = marks->bulk / 2;
280 marks->bulk += extra; /* bulk *= 1.5; */
281 marks->entries = xrealloc(marks->entries,
282 marks->bulk * sizeof(*marks->entries));
283 memset(&marks->entries[marks->nentries], 0,
284 extra * sizeof(*marks->entries));
285 i = marks->nentries;
286 } else {
287 /* Search for empty slot (there must be one). */
288 for (i = 0; i < marks->bulk; i++)
289 if (!marks->entries[i])
290 break;
292 } else {
293 /* Directory changed. Discard old marks. */
294 mark_none(marks);
295 strlcpy(marks->dirpath, dirpath, sizeof(marks->dirpath));
296 i = 0;
298 marks->entries[i] = xstrdup(entry);
299 marks->nentries++;
302 static void
303 del_mark(struct marks *marks, char *entry)
305 int i;
307 if (marks->nentries > 1) {
308 for (i = 0; i < marks->bulk; i++)
309 if (marks->entries[i] &&
310 !strcmp(marks->entries[i], entry))
311 break;
312 free(marks->entries[i]);
313 marks->entries[i] = NULL;
314 marks->nentries--;
315 } else
316 mark_none(marks);
319 static void
320 free_marks(struct marks *marks)
322 int i;
324 for (i = 0; i < marks->bulk && marks->nentries; i++)
325 if (marks->entries[i]) {
326 free(marks->entries[i]);
327 marks->nentries--;
329 free(marks->entries);
332 static void
333 handle_usr1(int sig)
335 fm.pending_usr1 = 1;
338 static void
339 handle_winch(int sig)
341 fm.pending_winch = 1;
344 static void
345 enable_handlers(void)
347 struct sigaction sa;
349 memset(&sa, 0, sizeof(struct sigaction));
350 sa.sa_handler = handle_usr1;
351 sigaction(SIGUSR1, &sa, NULL);
352 sa.sa_handler = handle_winch;
353 sigaction(SIGWINCH, &sa, NULL);
356 static void
357 disable_handlers(void)
359 struct sigaction sa;
361 memset(&sa, 0, sizeof(struct sigaction));
362 sa.sa_handler = SIG_DFL;
363 sigaction(SIGUSR1, &sa, NULL);
364 sigaction(SIGWINCH, &sa, NULL);
367 static void reload(void);
368 static void update_view(void);
370 /* Handle any signals received since last call. */
371 static void
372 sync_signals(void)
374 if (fm.pending_usr1) {
375 /* SIGUSR1 received: refresh directory listing. */
376 reload();
377 fm.pending_usr1 = 0;
379 if (fm.pending_winch) {
380 /* SIGWINCH received: resize application accordingly. */
381 delwin(fm.window);
382 endwin();
383 refresh();
384 clear();
385 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
386 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
387 SCROLL = ESEL - HEIGHT;
388 update_view();
389 fm.pending_winch = 0;
393 /*
394 * This function must be used in place of getch(). It handles signals
395 * while waiting for user input.
396 */
397 static int
398 fm_getch()
400 int ch;
402 while ((ch = getch()) == ERR)
403 sync_signals();
404 return ch;
407 /*
408 * This function must be used in place of get_wch(). It handles
409 * signals while waiting for user input.
410 */
411 static int
412 fm_get_wch(wint_t *wch)
414 wint_t ret;
416 while ((ret = get_wch(wch)) == (wint_t)ERR)
417 sync_signals();
418 return ret;
421 /* Get user programs from the environment. */
423 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
424 dst = getenv(#src);
426 static void
427 get_user_programs()
429 FM_ENV(user_shell, SHELL);
430 FM_ENV(user_pager, PAGER);
431 FM_ENV(user_editor, VISUAL);
432 if (!user_editor)
433 FM_ENV(user_editor, EDITOR);
434 FM_ENV(user_open, OPEN);
437 /* Do a fork-exec to external program (e.g. $EDITOR). */
438 static void
439 spawn(const char *argv0, ...)
441 pid_t pid;
442 int status;
443 size_t i;
444 const char *argv[16], *last;
445 va_list ap;
447 memset(argv, 0, sizeof(argv));
449 va_start(ap, argv0);
450 argv[0] = argv0;
451 for (i = 1; i < nitems(argv); ++i) {
452 last = va_arg(ap, const char *);
453 if (last == NULL)
454 break;
455 argv[i] = last;
457 va_end(ap);
459 if (last != NULL)
460 abort();
462 disable_handlers();
463 endwin();
465 switch (pid = fork()) {
466 case -1:
467 quit("fork");
468 case 0: /* child */
469 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
470 execvp(argv[0], (char *const *)argv);
471 quit("execvp");
472 default:
473 waitpid(pid, &status, 0);
474 enable_handlers();
475 kill(getpid(), SIGWINCH);
479 static void
480 shell_escaped_cat(char *buf, char *str, size_t n)
482 char *p = buf + strlen(buf);
483 *p++ = '\'';
484 for (n--; n; n--, str++) {
485 switch (*str) {
486 case '\'':
487 if (n < 4)
488 goto done;
489 strlcpy(p, "'\\''", n);
490 n -= 4;
491 p += 4;
492 break;
493 case '\0':
494 goto done;
495 default:
496 *p = *str;
497 p++;
500 done:
501 strncat(p, "'", n);
504 static int
505 open_with_env(char *program, char *path)
507 if (program) {
508 #ifdef RV_SHELL
509 strncpy(BUF1, program, BUFLEN - 1);
510 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
511 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
512 spawn(RV_SHELL, "-c", BUF1, NULL );
513 #else
514 spawn(program, path, NULL);
515 #endif
516 return 1;
518 return 0;
521 /* Curses setup. */
522 static void
523 init_term()
525 setlocale(LC_ALL, "");
526 initscr();
527 raw();
528 timeout(100); /* For getch(). */
529 noecho();
530 nonl(); /* No NL->CR/NL on output. */
531 intrflush(stdscr, FALSE);
532 keypad(stdscr, TRUE);
533 curs_set(FALSE); /* Hide blinking cursor. */
534 if (has_colors()) {
535 short bg;
536 start_color();
537 #ifdef NCURSES_EXT_FUNCS
538 use_default_colors();
539 bg = -1;
540 #else
541 bg = COLOR_BLACK;
542 #endif
543 init_pair(RED, COLOR_RED, bg);
544 init_pair(GREEN, COLOR_GREEN, bg);
545 init_pair(YELLOW, COLOR_YELLOW, bg);
546 init_pair(BLUE, COLOR_BLUE, bg);
547 init_pair(CYAN, COLOR_CYAN, bg);
548 init_pair(MAGENTA, COLOR_MAGENTA, bg);
549 init_pair(WHITE, COLOR_WHITE, bg);
550 init_pair(BLACK, COLOR_BLACK, bg);
552 atexit((void (*)(void))endwin);
553 enable_handlers();
556 /* Update the listing view. */
557 static void
558 update_view()
560 int i, j;
561 int numsize;
562 int ishidden;
563 int marking;
565 mvhline(0, 0, ' ', COLS);
566 attr_on(A_BOLD, NULL);
567 color_set(RVC_TABNUM, NULL);
568 mvaddch(0, COLS - 2, fm.tab + '0');
569 attr_off(A_BOLD, NULL);
570 if (fm.marks.nentries) {
571 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
572 color_set(RVC_MARKS, NULL);
573 mvaddstr(0, COLS - 3 - numsize, BUF1);
574 } else
575 numsize = -1;
576 color_set(RVC_CWD, NULL);
577 mbstowcs(WBUF, CWD, PATH_MAX);
578 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
579 wcolor_set(fm.window, RVC_BORDER, NULL);
580 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
581 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
583 /*
584 * Selection might not be visible, due to cursor wrapping or
585 * window shrinking. In that case, the scroll must be moved to
586 * make it visible.
587 */
588 if (fm.nfiles > HEIGHT) {
589 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
590 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
591 } else
592 SCROLL = 0;
593 marking = !strcmp(CWD, fm.marks.dirpath);
594 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
595 ishidden = ENAME(j)[0] == '.';
596 if (j == ESEL)
597 wattr_on(fm.window, A_REVERSE, NULL);
598 if (ISLINK(j))
599 wcolor_set(fm.window, RVC_LINK, NULL);
600 else if (ishidden)
601 wcolor_set(fm.window, RVC_HIDDEN, NULL);
602 else if (S_ISREG(EMODE(j))) {
603 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
604 wcolor_set(fm.window, RVC_EXEC, NULL);
605 else
606 wcolor_set(fm.window, RVC_REG, NULL);
607 } else if (S_ISDIR(EMODE(j)))
608 wcolor_set(fm.window, RVC_DIR, NULL);
609 else if (S_ISCHR(EMODE(j)))
610 wcolor_set(fm.window, RVC_CHR, NULL);
611 else if (S_ISBLK(EMODE(j)))
612 wcolor_set(fm.window, RVC_BLK, NULL);
613 else if (S_ISFIFO(EMODE(j)))
614 wcolor_set(fm.window, RVC_FIFO, NULL);
615 else if (S_ISSOCK(EMODE(j)))
616 wcolor_set(fm.window, RVC_SOCK, NULL);
617 if (S_ISDIR(EMODE(j))) {
618 mbstowcs(WBUF, ENAME(j), PATH_MAX);
619 if (ISLINK(j))
620 wcslcat(WBUF, L"/", sizeof(WBUF));
621 } else {
622 const char *suffix, *suffixes = "BKMGTPEZY";
623 off_t human_size = ESIZE(j) * 10;
624 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
625 int namecols = wcswidth(WBUF, length);
626 for (suffix = suffixes; human_size >= 10240; suffix++)
627 human_size = (human_size + 512) / 1024;
628 if (*suffix == 'B')
629 swprintf(WBUF + length, PATH_MAX - length,
630 L"%*d %c",
631 (int)(COLS - namecols - 6),
632 (int)human_size / 10, *suffix);
633 else
634 swprintf(WBUF + length, PATH_MAX - length,
635 L"%*d.%d %c",
636 (int)(COLS - namecols - 8),
637 (int)human_size / 10,
638 (int)human_size % 10, *suffix);
640 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
641 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
642 if (marking && MARKED(j)) {
643 wcolor_set(fm.window, RVC_MARKS, NULL);
644 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
645 } else
646 mvwaddch(fm.window, i + 1, 1, ' ');
647 if (j == ESEL)
648 wattr_off(fm.window, A_REVERSE, NULL);
650 for (; i < HEIGHT; i++)
651 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
652 if (fm.nfiles > HEIGHT) {
653 int center, height;
654 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
655 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
656 if (!height)
657 height = 1;
658 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
659 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
660 RVS_SCROLLBAR, height);
662 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
663 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
664 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
665 if (!fm.nfiles)
666 strlcpy(BUF2, "0/0", sizeof(BUF2));
667 else
668 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
669 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
670 color_set(RVC_STATUS, NULL);
671 mvaddstr(LINES - 1, STATUSPOS, BUF1);
672 wrefresh(fm.window);
675 /* Show a message on the status bar. */
676 static void __attribute__((format(printf, 2, 3)))
677 message(enum color c, const char *fmt, ...)
679 int len, pos;
680 va_list args;
682 va_start(args, fmt);
683 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
684 va_end(args);
685 len = strlen(BUF1);
686 pos = (STATUSPOS - len) / 2;
687 attr_on(A_BOLD, NULL);
688 color_set(c, NULL);
689 mvaddstr(LINES - 1, pos, BUF1);
690 color_set(DEFAULT, NULL);
691 attr_off(A_BOLD, NULL);
694 /* Clear message area, leaving only status info. */
695 static void
696 clear_message()
698 mvhline(LINES - 1, 0, ' ', STATUSPOS);
701 /* Comparison used to sort listing entries. */
702 static int
703 rowcmp(const void *a, const void *b)
705 int isdir1, isdir2, cmpdir;
706 const struct row *r1 = a;
707 const struct row *r2 = b;
708 isdir1 = S_ISDIR(r1->mode);
709 isdir2 = S_ISDIR(r2->mode);
710 cmpdir = isdir2 - isdir1;
711 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
714 /* Get all entries in current working directory. */
715 static int
716 ls(struct row **rowsp, uint8_t flags)
718 DIR *dp;
719 struct dirent *ep;
720 struct stat statbuf;
721 struct row *rows;
722 int i, n;
724 if (!(dp = opendir(".")))
725 return -1;
726 n = -2; /* We don't want the entries "." and "..". */
727 while (readdir(dp))
728 n++;
729 if (n == 0) {
730 closedir(dp);
731 return 0;
733 rewinddir(dp);
734 rows = xcalloc(n, sizeof(*rows));
735 i = 0;
736 while ((ep = readdir(dp))) {
737 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
738 continue;
739 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
740 continue;
741 lstat(ep->d_name, &statbuf);
742 rows[i].islink = S_ISLNK(statbuf.st_mode);
743 stat(ep->d_name, &statbuf);
744 if (S_ISDIR(statbuf.st_mode)) {
745 if (flags & SHOW_DIRS) {
746 xasprintf(&rows[i].name, "%s%s",
747 ep->d_name, rows[i].islink ? "" : "/");
748 rows[i].mode = statbuf.st_mode;
749 i++;
751 } else if (flags & SHOW_FILES) {
752 rows[i].name = xstrdup(ep->d_name);
753 rows[i].size = statbuf.st_size;
754 rows[i].mode = statbuf.st_mode;
755 i++;
758 n = i; /* Ignore unused space in array caused by filters. */
759 qsort(rows, n, sizeof(*rows), rowcmp);
760 closedir(dp);
761 *rowsp = rows;
762 return n;
765 static void
766 free_rows(struct row **rowsp, int nfiles)
768 int i;
770 for (i = 0; i < nfiles; i++)
771 free((*rowsp)[i].name);
772 free(*rowsp);
773 *rowsp = NULL;
776 /* Change working directory to the path in CWD. */
777 static void
778 cd(int reset)
780 int i, j;
782 message(CYAN, "Loading \"%s\"...", CWD);
783 refresh();
784 if (chdir(CWD) == -1) {
785 getcwd(CWD, PATH_MAX - 1);
786 if (CWD[strlen(CWD) - 1] != '/')
787 strlcat(CWD, "/", sizeof(CWD));
788 goto done;
790 if (reset)
791 ESEL = SCROLL = 0;
792 if (fm.nfiles)
793 free_rows(&fm.rows, fm.nfiles);
794 fm.nfiles = ls(&fm.rows, FLAGS);
795 if (!strcmp(CWD, fm.marks.dirpath)) {
796 for (i = 0; i < fm.nfiles; i++) {
797 for (j = 0; j < fm.marks.bulk; j++)
798 if (fm.marks.entries[j] &&
799 !strcmp(fm.marks.entries[j], ENAME(i)))
800 break;
801 MARKED(i) = j < fm.marks.bulk;
803 } else
804 for (i = 0; i < fm.nfiles; i++)
805 MARKED(i) = 0;
806 done:
807 clear_message();
808 update_view();
811 /* Select a target entry, if it is present. */
812 static void
813 try_to_sel(const char *target)
815 ESEL = 0;
816 if (!ISDIR(target))
817 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
818 ESEL++;
819 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
820 ESEL++;
823 /* Reload CWD, but try to keep selection. */
824 static void
825 reload()
827 if (fm.nfiles) {
828 strlcpy(INPUT, ENAME(ESEL), sizeof(INPUT));
829 cd(0);
830 try_to_sel(INPUT);
831 update_view();
832 } else
833 cd(1);
836 static off_t
837 count_dir(const char *path)
839 DIR *dp;
840 struct dirent *ep;
841 struct stat statbuf;
842 char subpath[PATH_MAX];
843 off_t total;
845 if (!(dp = opendir(path)))
846 return 0;
847 total = 0;
848 while ((ep = readdir(dp))) {
849 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
850 continue;
851 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
852 lstat(subpath, &statbuf);
853 if (S_ISDIR(statbuf.st_mode)) {
854 strlcat(subpath, "/", sizeof(subpath));
855 total += count_dir(subpath);
856 } else
857 total += statbuf.st_size;
859 closedir(dp);
860 return total;
863 static off_t
864 count_marked()
866 int i;
867 char *entry;
868 off_t total;
869 struct stat statbuf;
871 total = 0;
872 chdir(fm.marks.dirpath);
873 for (i = 0; i < fm.marks.bulk; i++) {
874 entry = fm.marks.entries[i];
875 if (entry) {
876 if (ISDIR(entry)) {
877 total += count_dir(entry);
878 } else {
879 lstat(entry, &statbuf);
880 total += statbuf.st_size;
884 chdir(CWD);
885 return total;
888 /*
889 * Recursively process a source directory using CWD as destination
890 * root. For each node (i.e. directory), do the following:
892 * 1. call pre(destination);
893 * 2. call proc() on every child leaf (i.e. files);
894 * 3. recurse into every child node;
895 * 4. call pos(source).
897 * E.g. to move directory /src/ (and all its contents) inside /dst/:
898 * strlcpy(CWD, "/dst/", sizeof(CWD));
899 * process_dir(adddir, movfile, deldir, "/src/");
900 */
901 static int
902 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
904 int ret;
905 DIR *dp;
906 struct dirent *ep;
907 struct stat statbuf;
908 char subpath[PATH_MAX];
910 ret = 0;
911 if (pre) {
912 char dstpath[PATH_MAX];
913 strlcpy(dstpath, CWD, sizeof(dstpath));
914 strlcat(dstpath, path + strlen(fm.marks.dirpath),
915 sizeof(dstpath));
916 ret |= pre(dstpath);
918 if (!(dp = opendir(path)))
919 return -1;
920 while ((ep = readdir(dp))) {
921 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
922 continue;
923 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
924 lstat(subpath, &statbuf);
925 if (S_ISDIR(statbuf.st_mode)) {
926 strcat(subpath, "/");
927 ret |= process_dir(pre, proc, pos, subpath);
928 } else
929 ret |= proc(subpath);
931 closedir(dp);
932 if (pos)
933 ret |= pos(path);
934 return ret;
937 /*
938 * Process all marked entries using CWD as destination root. All
939 * marked entries that are directories will be recursively processed.
940 * See process_dir() for details on the parameters.
941 */
942 static void
943 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
944 const char *msg_done)
946 int i, ret;
947 char *entry;
948 char path[PATH_MAX];
950 clear_message();
951 message(CYAN, "%s...", msg_doing);
952 refresh();
953 fm.prog = (struct prog){0, count_marked(), msg_doing};
954 for (i = 0; i < fm.marks.bulk; i++) {
955 entry = fm.marks.entries[i];
956 if (entry) {
957 ret = 0;
958 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
959 entry);
960 if (ISDIR(entry)) {
961 if (!strncmp(path, CWD, strlen(path)))
962 ret = -1;
963 else
964 ret = process_dir(pre, proc, pos, path);
965 } else
966 ret = proc(path);
967 if (!ret) {
968 del_mark(&fm.marks, entry);
969 reload();
973 fm.prog.total = 0;
974 reload();
975 if (!fm.marks.nentries)
976 message(GREEN, "%s all marked entries.", msg_done);
977 else
978 message(RED, "Some errors occured while %s.", msg_doing);
979 RV_ALERT();
982 static void
983 update_progress(off_t delta)
985 int percent;
987 if (!fm.prog.total)
988 return;
989 fm.prog.partial += delta;
990 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
991 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
992 refresh();
995 /* Wrappers for file operations. */
996 static int
997 delfile(const char *path)
999 int ret;
1000 struct stat st;
1002 ret = lstat(path, &st);
1003 if (ret < 0)
1004 return ret;
1005 update_progress(st.st_size);
1006 return unlink(path);
1009 static int
1010 addfile(const char *path)
1012 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
1013 int ret;
1015 ret = creat(path, 0644);
1016 if (ret < 0)
1017 return ret;
1018 return close(ret);
1021 static int
1022 cpyfile(const char *srcpath)
1024 int src, dst, ret;
1025 size_t size;
1026 struct stat st;
1027 char buf[BUFSIZ];
1028 char dstpath[PATH_MAX];
1030 strlcpy(dstpath, CWD, sizeof(dstpath));
1031 strlcat(dstpath, srcpath + strlen(fm.marks.dirpath), sizeof(dstpath));
1032 ret = lstat(srcpath, &st);
1033 if (ret < 0)
1034 return ret;
1035 if (S_ISLNK(st.st_mode)) {
1036 ret = readlink(srcpath, BUF1, BUFLEN - 1);
1037 if (ret < 0)
1038 return ret;
1039 BUF1[ret] = '\0';
1040 ret = symlink(BUF1, dstpath);
1041 } else {
1042 ret = src = open(srcpath, O_RDONLY);
1043 if (ret < 0)
1044 return ret;
1045 ret = dst = creat(dstpath, st.st_mode);
1046 if (ret < 0)
1047 return ret;
1048 while ((size = read(src, buf, BUFSIZ)) > 0) {
1049 write(dst, buf, size);
1050 update_progress(size);
1051 sync_signals();
1053 close(src);
1054 close(dst);
1055 ret = 0;
1057 return ret;
1060 static int
1061 adddir(const char *path)
1063 int ret;
1064 struct stat st;
1066 ret = stat(CWD, &st);
1067 if (ret < 0)
1068 return ret;
1069 return mkdir(path, st.st_mode);
1072 static int
1073 movfile(const char *srcpath)
1075 int ret;
1076 struct stat st;
1077 char dstpath[PATH_MAX];
1079 strlcpy(dstpath, CWD, sizeof(dstpath));
1080 strlcat(dstpath, srcpath + strlen(fm.marks.dirpath), sizeof(dstpath));
1081 ret = rename(srcpath, dstpath);
1082 if (ret == 0) {
1083 ret = lstat(dstpath, &st);
1084 if (ret < 0)
1085 return ret;
1086 update_progress(st.st_size);
1087 } else if (errno == EXDEV) {
1088 ret = cpyfile(srcpath);
1089 if (ret < 0)
1090 return ret;
1091 ret = unlink(srcpath);
1093 return ret;
1096 static void
1097 start_line_edit(const char *init_input)
1099 curs_set(TRUE);
1100 strncpy(INPUT, init_input, BUFLEN);
1101 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1102 fm.edit.right = BUFLEN - 1;
1103 fm.edit.buffer[BUFLEN] = L'\0';
1104 fm.edit_scroll = 0;
1107 /* Read input and change editing state accordingly. */
1108 static enum editstate
1109 get_line_edit()
1111 wchar_t eraser, killer, wch;
1112 int ret, length;
1114 ret = fm_get_wch((wint_t *)&wch);
1115 erasewchar(&eraser);
1116 killwchar(&killer);
1117 if (ret == KEY_CODE_YES) {
1118 if (wch == KEY_ENTER) {
1119 curs_set(FALSE);
1120 return CONFIRM;
1121 } else if (wch == KEY_LEFT) {
1122 if (EDIT_CAN_LEFT(fm.edit))
1123 EDIT_LEFT(fm.edit);
1124 } else if (wch == KEY_RIGHT) {
1125 if (EDIT_CAN_RIGHT(fm.edit))
1126 EDIT_RIGHT(fm.edit);
1127 } else if (wch == KEY_UP) {
1128 while (EDIT_CAN_LEFT(fm.edit))
1129 EDIT_LEFT(fm.edit);
1130 } else if (wch == KEY_DOWN) {
1131 while (EDIT_CAN_RIGHT(fm.edit))
1132 EDIT_RIGHT(fm.edit);
1133 } else if (wch == KEY_BACKSPACE) {
1134 if (EDIT_CAN_LEFT(fm.edit))
1135 EDIT_BACKSPACE(fm.edit);
1136 } else if (wch == KEY_DC) {
1137 if (EDIT_CAN_RIGHT(fm.edit))
1138 EDIT_DELETE(fm.edit);
1140 } else {
1141 if (wch == L'\r' || wch == L'\n') {
1142 curs_set(FALSE);
1143 return CONFIRM;
1144 } else if (wch == L'\t') {
1145 curs_set(FALSE);
1146 return CANCEL;
1147 } else if (wch == eraser) {
1148 if (EDIT_CAN_LEFT(fm.edit))
1149 EDIT_BACKSPACE(fm.edit);
1150 } else if (wch == killer) {
1151 EDIT_CLEAR(fm.edit);
1152 clear_message();
1153 } else if (iswprint(wch)) {
1154 if (!EDIT_FULL(fm.edit))
1155 EDIT_INSERT(fm.edit, wch);
1158 /* Encode edit contents in INPUT. */
1159 fm.edit.buffer[fm.edit.left] = L'\0';
1160 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1161 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1162 BUFLEN - length);
1163 return CONTINUE;
1166 /* Update line input on the screen. */
1167 static void
1168 update_input(const char *prompt, enum color c)
1170 int plen, ilen, maxlen;
1172 plen = strlen(prompt);
1173 ilen = mbstowcs(NULL, INPUT, 0);
1174 maxlen = STATUSPOS - plen - 2;
1175 if (ilen - fm.edit_scroll < maxlen)
1176 fm.edit_scroll = MAX(ilen - maxlen, 0);
1177 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1178 fm.edit_scroll = fm.edit.left - maxlen;
1179 else if (fm.edit.left < fm.edit_scroll)
1180 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1181 color_set(RVC_PROMPT, NULL);
1182 mvaddstr(LINES - 1, 0, prompt);
1183 color_set(c, NULL);
1184 mbstowcs(WBUF, INPUT, COLS);
1185 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1186 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1187 ' ');
1188 color_set(DEFAULT, NULL);
1189 if (fm.edit_scroll)
1190 mvaddch(LINES - 1, plen - 1, '<');
1191 if (ilen > fm.edit_scroll + maxlen)
1192 mvaddch(LINES - 1, plen + maxlen, '>');
1193 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1196 static void
1197 cmd_down(void)
1199 if (fm.nfiles)
1200 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1203 static void
1204 cmd_up(void)
1206 if (fm.nfiles)
1207 ESEL = MAX(ESEL - 1, 0);
1210 static void
1211 cmd_scroll_down(void)
1213 if (!fm.nfiles)
1214 return;
1215 ESEL = MIN(ESEL + HEIGHT, fm.nfiles - 1);
1216 if (fm.nfiles > HEIGHT)
1217 SCROLL = MIN(SCROLL + HEIGHT, fm.nfiles - HEIGHT);
1220 static void
1221 cmd_scroll_up(void)
1223 if (!fm.nfiles)
1224 return;
1225 ESEL = MAX(ESEL - HEIGHT, 0);
1226 SCROLL = MAX(SCROLL - HEIGHT, 0);
1229 static void
1230 cmd_man(void)
1232 spawn("man", "fm", NULL);
1235 static void
1236 cmd_jump_top(void)
1238 if (fm.nfiles)
1239 ESEL = 0;
1242 static void
1243 cmd_jump_bottom(void)
1245 if (fm.nfiles)
1246 ESEL = fm.nfiles - 1;
1249 static void
1250 cmd_cd_down(void)
1252 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1253 return;
1254 if (chdir(ENAME(ESEL)) == -1) {
1255 message(RED, "cd: %s: %s", ENAME(ESEL), strerror(errno));
1256 return;
1258 strlcat(CWD, ENAME(ESEL), sizeof(CWD));
1259 cd(1);
1262 static void
1263 cmd_cd_up(void)
1265 char *dirname, first;
1267 if (!strcmp(CWD, "/"))
1268 return;
1270 /* dirname(3) basically */
1271 dirname = strrchr(CWD, '/');
1272 *dirname-- = '\0';
1273 dirname = strrchr(CWD, '/') + 1;
1275 first = dirname[0];
1276 dirname[0] = '\0';
1277 cd(1);
1278 dirname[0] = first;
1279 strlcat(dirname, "/", sizeof(dirname));
1280 try_to_sel(dirname);
1281 dirname[0] = '\0';
1282 if (fm.nfiles > HEIGHT)
1283 SCROLL = ESEL - HEIGHT / 2;
1286 static void
1287 cmd_home(void)
1289 const char *home;
1291 if ((home = getenv("HOME")) == NULL) {
1292 message(RED, "HOME is not defined!");
1293 return;
1296 strlcpy(CWD, home, sizeof(CWD));
1297 if (*CWD != '\0' && CWD[strlen(CWD) - 1] != '/')
1298 strlcat(CWD, "/", sizeof(CWD));
1299 cd(1);
1302 static void
1303 cmd_copy_path(void)
1305 const char *path;
1306 FILE *f;
1308 if ((path = getenv("CLIP")) == NULL ||
1309 (f = fopen(path, "w")) == NULL) {
1310 /* use internal clipboard */
1311 strlcpy(clipboard, CWD, sizeof(clipboard));
1312 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1313 return;
1316 fprintf(f, "%s%s", CWD, ENAME(ESEL));
1317 fputc('\0', f);
1318 fclose(f);
1321 static void
1322 cmd_paste_path(void)
1324 ssize_t r;
1325 const char *path;
1326 char *nl;
1327 FILE *f;
1328 char p[PATH_MAX];
1330 if ((path = getenv("CLIP")) != NULL &&
1331 (f = fopen(path, "w")) != NULL) {
1332 r = fread(clipboard, 1, sizeof(clipboard)-1, f);
1333 fclose(f);
1334 if (r == -1 || r == 0)
1335 goto err;
1336 if ((nl = memmem(clipboard, r, "", 1)) == NULL)
1337 goto err;
1340 strlcpy(p, clipboard, sizeof(p));
1341 strlcpy(CWD, clipboard, sizeof(CWD));
1342 if ((nl = strrchr(CWD, '/')) != NULL) {
1343 *nl = '\0';
1344 nl = strrchr(p, '/');
1345 assert(nl != NULL);
1347 if (strcmp(CWD, "/") != 0)
1348 strlcat(CWD, "/", sizeof(CWD));
1349 cd(1);
1350 try_to_sel(nl+1);
1351 return;
1353 err:
1354 memset(clipboard, 0, sizeof(clipboard));
1357 static void
1358 cmd_reload(void)
1360 reload();
1363 static void
1364 cmd_shell(void)
1366 const char *shell;
1368 if ((shell = getenv("SHELL")) == NULL)
1369 shell = FM_SHELL;
1370 spawn(shell, NULL);
1373 static void
1374 cmd_view(void)
1376 const char *pager;
1378 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1379 return;
1381 if ((pager = getenv("PAGER")) == NULL)
1382 pager = FM_PAGER;
1383 spawn(pager, ENAME(ESEL), NULL);
1386 static void
1387 cmd_edit(void)
1389 const char *editor;
1391 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1392 return;
1394 if ((editor = getenv("VISUAL")) == NULL ||
1395 (editor = getenv("EDITOR")) == NULL)
1396 editor = FM_ED;
1398 spawn(editor, ENAME(ESEL), NULL);
1401 static void
1402 cmd_open(void)
1404 const char *opener;
1406 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1407 return;
1409 if ((opener = getenv("OPENER")) == NULL)
1410 opener = FM_OPENER;
1412 spawn(opener, ENAME(ESEL), NULL);
1415 static void
1416 cmd_mark(void)
1418 if (MARKED(ESEL))
1419 del_mark(&fm.marks, ENAME(ESEL));
1420 else
1421 add_mark(&fm.marks, CWD, ENAME(ESEL));
1423 MARKED(ESEL) = !MARKED(ESEL);
1424 ESEL = (ESEL + 1) % fm.nfiles;
1427 static void
1428 cmd_toggle_mark(void)
1430 int i;
1432 for (i = 0; i < fm.nfiles; ++i) {
1433 if (MARKED(i))
1434 del_mark(&fm.marks, ENAME(i));
1435 else
1436 add_mark(&fm.marks, CWD, ENAME(ESEL));
1437 MARKED(i) = !MARKED(i);
1441 static void
1442 cmd_mark_all(void)
1444 int i;
1446 for (i = 0; i < fm.nfiles; ++i)
1447 if (!MARKED(i)) {
1448 add_mark(&fm.marks, CWD, ENAME(ESEL));
1449 MARKED(i) = 1;
1453 static void
1454 loop(void)
1456 int meta, ch, c;
1457 struct binding {
1458 int ch;
1459 #define K_META 1
1460 #define K_CTRL 2
1461 int chflags;
1462 void (*fn)(void);
1463 #define X_UPDV 1
1464 #define X_QUIT 2
1465 int flags;
1466 } bindings[] = {
1467 {'<', K_META, cmd_jump_top, X_UPDV},
1468 {'>', K_META, cmd_jump_bottom, X_UPDV},
1469 {'?', 0, cmd_man, 0},
1470 {'G', 0, cmd_jump_bottom, X_UPDV},
1471 {'H', 0, cmd_home, X_UPDV},
1472 {'J', 0, cmd_scroll_down, X_UPDV},
1473 {'K', 0, cmd_scroll_up, X_UPDV},
1474 {'M', 0, cmd_mark_all, X_UPDV},
1475 {'P', 0, cmd_paste_path, X_UPDV},
1476 {'V', K_CTRL, cmd_scroll_down, X_UPDV},
1477 {'Y', 0, cmd_copy_path, X_UPDV},
1478 {'^', 0, cmd_cd_up, X_UPDV},
1479 {'b', 0, cmd_cd_up, X_UPDV},
1480 {'e', 0, cmd_edit, X_UPDV},
1481 {'f', 0, cmd_cd_down, X_UPDV},
1482 {'g', 0, cmd_jump_top, X_UPDV},
1483 {'g', K_CTRL, NULL, X_UPDV},
1484 {'h', 0, cmd_cd_up, X_UPDV},
1485 {'j', 0, cmd_down, X_UPDV},
1486 {'k', 0, cmd_up, X_UPDV},
1487 {'l', 0, cmd_cd_down, X_UPDV},
1488 {'l', K_CTRL, cmd_reload, X_UPDV},
1489 {'n', 0, cmd_down, X_UPDV},
1490 {'n', K_CTRL, cmd_down, X_UPDV},
1491 {'m', 0, cmd_mark, X_UPDV},
1492 {'m', K_CTRL, cmd_shell, X_UPDV},
1493 {'o', 0, cmd_open, X_UPDV},
1494 {'p', 0, cmd_up, X_UPDV},
1495 {'p', K_CTRL, cmd_up, X_UPDV},
1496 {'q', 0, NULL, X_QUIT},
1497 {'t', 0, cmd_toggle_mark, X_UPDV},
1498 {'v', 0, cmd_view, X_UPDV},
1499 {'v', K_META, cmd_scroll_up, X_UPDV},
1500 {KEY_DOWN, 0, cmd_scroll_down, X_UPDV},
1501 {KEY_NPAGE, 0, cmd_scroll_down, X_UPDV},
1502 {KEY_PPAGE, 0, cmd_scroll_up, X_UPDV},
1503 {KEY_RESIZE, 0, NULL, X_UPDV},
1504 {KEY_RESIZE, K_META, NULL, X_UPDV},
1505 {KEY_UP, 0, cmd_scroll_up, X_UPDV},
1506 }, *b;
1507 size_t i;
1509 for (;;) {
1510 again:
1511 meta = 0;
1512 ch = fm_getch();
1513 if (ch == '\e') {
1514 meta = 1;
1515 if ((ch = fm_getch()) == '\e') {
1516 meta = 0;
1517 ch = '\e';
1521 clear_message();
1523 for (i = 0; i < nitems(bindings); ++i) {
1524 b = &bindings[i];
1525 c = b->ch;
1526 if (b->chflags & K_CTRL)
1527 c = CTRL(c);
1528 if ((!meta && b->chflags & K_META) || ch != c)
1529 continue;
1531 if (b->flags & X_QUIT)
1532 return;
1533 if (b->fn != NULL)
1534 b->fn();
1535 if (b->flags & X_UPDV)
1536 update_view();
1538 goto again;
1541 message(RED, "%s%s is undefined",
1542 meta ? "M-": "", keyname(ch));
1543 refresh();
1547 static __dead void
1548 usage(void)
1550 fprintf(stderr, "usage: %s [-hv] [-d file] [-m file] [dirs ...]\n",
1551 getprogname());
1552 fprintf(stderr, "version: %s\n", RV_VERSION);
1553 exit(1);
1556 int
1557 main(int argc, char *argv[])
1559 int i, ch;
1560 char *entry;
1561 DIR *d;
1562 FILE *save_cwd_file = NULL;
1563 FILE *save_marks_file = NULL;
1565 if (pledge("stdio rpath wpath cpath tty proc exec", NULL) == -1)
1566 err(1, "pledge");
1568 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1569 switch (ch) {
1570 case 'd':
1571 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1572 err(1, "open %s", optarg);
1573 break;
1574 case 'h':
1575 usage();
1576 break;
1577 case 'm':
1578 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1579 err(1, "open %s", optarg);
1580 break;
1581 case 'v':
1582 printf("version: fm %s\n", RV_VERSION);
1583 return 0;
1584 default:
1585 usage();
1589 get_user_programs();
1590 init_term();
1591 fm.nfiles = 0;
1592 for (i = 0; i < 10; i++) {
1593 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1594 fm.tabs[i].flags = RV_FLAGS;
1596 strlcpy(fm.tabs[0].cwd, getenv("HOME"), sizeof(fm.tabs[0].cwd));
1597 for (i = 1; i < argc && i < 10; i++) {
1598 if ((d = opendir(argv[i]))) {
1599 realpath(argv[i], fm.tabs[i].cwd);
1600 closedir(d);
1601 } else {
1602 strlcpy(fm.tabs[i].cwd, fm.tabs[0].cwd,
1603 sizeof(fm.tabs[i].cwd));
1606 getcwd(fm.tabs[i].cwd, PATH_MAX);
1607 for (i++; i < 10; i++)
1608 strlcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd,
1609 sizeof(fm.tabs[i].cwd));
1610 for (i = 0; i < 10; i++)
1611 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1612 strlcat(fm.tabs[i].cwd, "/", sizeof(fm.tabs[i].cwd));
1613 fm.tab = 1;
1614 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1615 init_marks(&fm.marks);
1616 cd(1);
1617 strlcpy(clipboard, CWD, sizeof(clipboard));
1618 if (fm.nfiles > 0)
1619 strlcat(clipboard, ENAME(ESEL), sizeof(clipboard));
1621 loop();
1623 if (fm.nfiles)
1624 free_rows(&fm.rows, fm.nfiles);
1625 delwin(fm.window);
1626 if (save_cwd_file != NULL) {
1627 fputs(CWD, save_cwd_file);
1628 fclose(save_cwd_file);
1630 if (save_marks_file != NULL) {
1631 for (i = 0; i < fm.marks.bulk; i++) {
1632 entry = fm.marks.entries[i];
1633 if (entry)
1634 fprintf(save_marks_file, "%s%s\n",
1635 fm.marks.dirpath, entry);
1637 fclose(save_marks_file);
1639 free_marks(&fm.marks);
1640 return 0;