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 <ctype.h>
10 #include <curses.h>
11 #include <dirent.h>
12 #include <err.h>
13 #include <errno.h>
14 #include <fcntl.h>
15 #include <getopt.h>
16 #include <libgen.h>
17 #include <limits.h>
18 #include <locale.h>
19 #include <signal.h>
20 #include <stdarg.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #include <wchar.h>
27 #include <wctype.h>
29 #include "config.h"
31 struct option opts[] = {
32 {"help", no_argument, NULL, 'h'},
33 {"version", no_argument, NULL, 'v'},
34 {NULL, 0, NULL, 0}
35 };
37 /* String buffers. */
38 #define BUFLEN PATH_MAX
39 static char BUF1[BUFLEN];
40 static char BUF2[BUFLEN];
41 static char INPUT[BUFLEN];
42 static char CLIPBOARD[BUFLEN];
43 static wchar_t WBUF[BUFLEN];
45 /* Paths to external programs. */
46 static char *user_shell;
47 static char *user_pager;
48 static char *user_editor;
49 static char *user_open;
51 /* Listing view parameters. */
52 #define HEIGHT (LINES-4)
53 #define STATUSPOS (COLS-16)
55 /* Listing view flags. */
56 #define SHOW_FILES 0x01u
57 #define SHOW_DIRS 0x02u
58 #define SHOW_HIDDEN 0x04u
60 /* Marks parameters. */
61 #define BULK_INIT 5
62 #define BULK_THRESH 256
64 /* Information associated to each entry in listing. */
65 struct row {
66 char *name;
67 off_t size;
68 mode_t mode;
69 int islink;
70 int marked;
71 };
73 /* Dynamic array of marked entries. */
74 struct marks {
75 char dirpath[PATH_MAX];
76 int bulk;
77 int nentries;
78 char **entries;
79 };
81 /* Line editing state. */
82 struct edit {
83 wchar_t buffer[BUFLEN + 1];
84 int left, right;
85 };
87 /* Each tab only stores the following information. */
88 struct tab {
89 int scroll;
90 int esel;
91 uint8_t flags;
92 char cwd[PATH_MAX];
93 };
95 struct prog {
96 off_t partial;
97 off_t total;
98 const char *msg;
99 };
101 /* Global state. */
102 static struct state {
103 int tab;
104 int nfiles;
105 struct row *rows;
106 WINDOW *window;
107 struct marks marks;
108 struct edit edit;
109 int edit_scroll;
110 volatile sig_atomic_t pending_usr1;
111 volatile sig_atomic_t pending_winch;
112 struct prog prog;
113 struct tab tabs[10];
114 } fm;
116 /* Macros for accessing global state. */
117 #define ENAME(I) fm.rows[I].name
118 #define ESIZE(I) fm.rows[I].size
119 #define EMODE(I) fm.rows[I].mode
120 #define ISLINK(I) fm.rows[I].islink
121 #define MARKED(I) fm.rows[I].marked
122 #define SCROLL fm.tabs[fm.tab].scroll
123 #define ESEL fm.tabs[fm.tab].esel
124 #define FLAGS fm.tabs[fm.tab].flags
125 #define CWD fm.tabs[fm.tab].cwd
127 /* Helpers. */
128 #define MIN(A, B) ((A) < (B) ? (A) : (B))
129 #define MAX(A, B) ((A) > (B) ? (A) : (B))
130 #define ISDIR(E) (strchr((E), '/') != NULL)
132 /* Line Editing Macros. */
133 #define EDIT_FULL(E) ((E).left == (E).right)
134 #define EDIT_CAN_LEFT(E) ((E).left)
135 #define EDIT_CAN_RIGHT(E) ((E).right < BUFLEN-1)
136 #define EDIT_LEFT(E) (E).buffer[(E).right--] = (E).buffer[--(E).left]
137 #define EDIT_RIGHT(E) (E).buffer[(E).left++] = (E).buffer[++(E).right]
138 #define EDIT_INSERT(E, C) (E).buffer[(E).left++] = (C)
139 #define EDIT_BACKSPACE(E) (E).left--
140 #define EDIT_DELETE(E) (E).right++
141 #define EDIT_CLEAR(E) do { (E).left = 0; (E).right = BUFLEN-1; } while(0)
143 enum editstate { CONTINUE, CONFIRM, CANCEL };
144 enum color { DEFAULT, RED, GREEN, YELLOW, BLUE, CYAN, MAGENTA, WHITE, BLACK };
146 typedef int (*PROCESS)(const char *path);
148 #ifndef __dead
149 #define __dead __attribute__((noreturn))
150 #endif
152 static inline __dead void *
153 quit(const char *reason)
155 int saved_errno;
157 saved_errno = errno;
158 endwin();
159 nocbreak();
160 fflush(stderr);
161 errno = saved_errno;
162 err(1, "%s", reason);
165 static inline void *
166 xmalloc(size_t size)
168 void *d;
170 if ((d = malloc(size)) == NULL)
171 quit("malloc");
172 return d;
175 static inline void *
176 xcalloc(size_t nmemb, size_t size)
178 void *d;
180 if ((d = calloc(nmemb, size)) == NULL)
181 quit("calloc");
182 return d;
185 static inline void *
186 xrealloc(void *p, size_t size)
188 void *d;
190 if ((d = realloc(d, size)) == NULL)
191 quit("realloc");
192 return d;
195 static void
196 init_marks(struct marks *marks)
198 strcpy(marks->dirpath, "");
199 marks->bulk = BULK_INIT;
200 marks->nentries = 0;
201 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
204 /* Unmark all entries. */
205 static void
206 mark_none(struct marks *marks)
208 int i;
210 strcpy(marks->dirpath, "");
211 for (i = 0; i < marks->bulk && marks->nentries; i++)
212 if (marks->entries[i]) {
213 free(marks->entries[i]);
214 marks->entries[i] = NULL;
215 marks->nentries--;
217 if (marks->bulk > BULK_THRESH) {
218 /* Reset bulk to free some memory. */
219 free(marks->entries);
220 marks->bulk = BULK_INIT;
221 marks->entries = xcalloc(marks->bulk, sizeof(*marks->entries));
225 static void
226 add_mark(struct marks *marks, char *dirpath, char *entry)
228 int i;
230 if (!strcmp(marks->dirpath, dirpath)) {
231 /* Append mark to directory. */
232 if (marks->nentries == marks->bulk) {
233 /* Expand bulk to accomodate new entry. */
234 int extra = marks->bulk / 2;
235 marks->bulk += extra; /* bulk *= 1.5; */
236 marks->entries = xrealloc(marks->entries,
237 marks->bulk * sizeof(*marks->entries));
238 memset(&marks->entries[marks->nentries], 0,
239 extra * sizeof(*marks->entries));
240 i = marks->nentries;
241 } else {
242 /* Search for empty slot (there must be one). */
243 for (i = 0; i < marks->bulk; i++)
244 if (!marks->entries[i])
245 break;
247 } else {
248 /* Directory changed. Discard old marks. */
249 mark_none(marks);
250 strcpy(marks->dirpath, dirpath);
251 i = 0;
253 marks->entries[i] = xmalloc(strlen(entry) + 1);
254 strcpy(marks->entries[i], entry);
255 marks->nentries++;
258 static void
259 del_mark(struct marks *marks, char *entry)
261 int i;
263 if (marks->nentries > 1) {
264 for (i = 0; i < marks->bulk; i++)
265 if (marks->entries[i] &&
266 !strcmp(marks->entries[i], entry))
267 break;
268 free(marks->entries[i]);
269 marks->entries[i] = NULL;
270 marks->nentries--;
271 } else
272 mark_none(marks);
275 static void
276 free_marks(struct marks *marks)
278 int i;
280 for (i = 0; i < marks->bulk && marks->nentries; i++)
281 if (marks->entries[i]) {
282 free(marks->entries[i]);
283 marks->nentries--;
285 free(marks->entries);
288 static void
289 handle_usr1(int sig)
291 fm.pending_usr1 = 1;
294 static void
295 handle_winch(int sig)
297 fm.pending_winch = 1;
300 static void
301 enable_handlers()
303 struct sigaction sa;
305 memset(&sa, 0, sizeof(struct sigaction));
306 sa.sa_handler = handle_usr1;
307 sigaction(SIGUSR1, &sa, NULL);
308 sa.sa_handler = handle_winch;
309 sigaction(SIGWINCH, &sa, NULL);
312 static void
313 disable_handlers()
315 struct sigaction sa;
317 memset(&sa, 0, sizeof(struct sigaction));
318 sa.sa_handler = SIG_DFL;
319 sigaction(SIGUSR1, &sa, NULL);
320 sigaction(SIGWINCH, &sa, NULL);
323 static void reload();
324 static void update_view();
326 /* Handle any signals received since last call. */
327 static void
328 sync_signals()
330 if (fm.pending_usr1) {
331 /* SIGUSR1 received: refresh directory listing. */
332 reload();
333 fm.pending_usr1 = 0;
335 if (fm.pending_winch) {
336 /* SIGWINCH received: resize application accordingly. */
337 delwin(fm.window);
338 endwin();
339 refresh();
340 clear();
341 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
342 if (HEIGHT < fm.nfiles && SCROLL + HEIGHT > fm.nfiles)
343 SCROLL = ESEL - HEIGHT;
344 update_view();
345 fm.pending_winch = 0;
349 /*
350 * This function must be used in place of getch(). It handles signals
351 * while waiting for user input.
352 */
353 static int
354 fm_getch()
356 int ch;
358 while ((ch = getch()) == ERR)
359 sync_signals();
360 return ch;
363 /*
364 * This function must be used in place of get_wch(). It handles
365 * signals while waiting for user input.
366 */
367 static int
368 fm_get_wch(wint_t *wch)
370 wint_t ret;
372 while ((ret = get_wch(wch)) == (wint_t)ERR)
373 sync_signals();
374 return ret;
377 /* Get user programs from the environment. */
379 #define FM_ENV(dst, src) if ((dst = getenv("FM_" #src)) == NULL) \
380 dst = getenv(#src);
382 static void
383 get_user_programs()
385 FM_ENV(user_shell, SHELL);
386 FM_ENV(user_pager, PAGER);
387 FM_ENV(user_editor, VISUAL);
388 if (!user_editor)
389 FM_ENV(user_editor, EDITOR);
390 FM_ENV(user_open, OPEN);
393 /* Do a fork-exec to external program (e.g. $EDITOR). */
394 static void
395 spawn(char **args)
397 pid_t pid;
398 int status;
400 setenv("RVSEL", fm.nfiles ? ENAME(ESEL) : "", 1);
401 pid = fork();
402 if (pid > 0) {
403 /* fork() succeeded. */
404 disable_handlers();
405 endwin();
406 waitpid(pid, &status, 0);
407 enable_handlers();
408 kill(getpid(), SIGWINCH);
409 } else if (pid == 0) {
410 /* Child process. */
411 execvp(args[0], args);
415 static void
416 shell_escaped_cat(char *buf, char *str, size_t n)
418 char *p = buf + strlen(buf);
419 *p++ = '\'';
420 for (n--; n; n--, str++) {
421 switch (*str) {
422 case '\'':
423 if (n < 4)
424 goto done;
425 strcpy(p, "'\\''");
426 n -= 4;
427 p += 4;
428 break;
429 case '\0':
430 goto done;
431 default:
432 *p = *str;
433 p++;
436 done:
437 strncat(p, "'", n);
440 static int
441 open_with_env(char *program, char *path)
443 if (program) {
444 #ifdef RV_SHELL
445 strncpy(BUF1, program, BUFLEN - 1);
446 strncat(BUF1, " ", BUFLEN - strlen(program) - 1);
447 shell_escaped_cat(BUF1, path, BUFLEN - strlen(program) - 2);
448 spawn((char *[]) { RV_SHELL, "-c", BUF1, NULL });
449 #else
450 spawn((char *[]) { program, path, NULL });
451 #endif
452 return 1;
454 return 0;
457 /* Curses setup. */
458 static void
459 init_term()
461 setlocale(LC_ALL, "");
462 initscr();
463 cbreak(); /* Get one character at a time. */
464 timeout(100); /* For getch(). */
465 noecho();
466 nonl(); /* No NL->CR/NL on output. */
467 intrflush(stdscr, FALSE);
468 keypad(stdscr, TRUE);
469 curs_set(FALSE); /* Hide blinking cursor. */
470 if (has_colors()) {
471 short bg;
472 start_color();
473 #ifdef NCURSES_EXT_FUNCS
474 use_default_colors();
475 bg = -1;
476 #else
477 bg = COLOR_BLACK;
478 #endif
479 init_pair(RED, COLOR_RED, bg);
480 init_pair(GREEN, COLOR_GREEN, bg);
481 init_pair(YELLOW, COLOR_YELLOW, bg);
482 init_pair(BLUE, COLOR_BLUE, bg);
483 init_pair(CYAN, COLOR_CYAN, bg);
484 init_pair(MAGENTA, COLOR_MAGENTA, bg);
485 init_pair(WHITE, COLOR_WHITE, bg);
486 init_pair(BLACK, COLOR_BLACK, bg);
488 atexit((void (*)(void))endwin);
489 enable_handlers();
492 /* Update the listing view. */
493 static void
494 update_view()
496 int i, j;
497 int numsize;
498 int ishidden;
499 int marking;
501 mvhline(0, 0, ' ', COLS);
502 attr_on(A_BOLD, NULL);
503 color_set(RVC_TABNUM, NULL);
504 mvaddch(0, COLS - 2, fm.tab + '0');
505 attr_off(A_BOLD, NULL);
506 if (fm.marks.nentries) {
507 numsize = snprintf(BUF1, BUFLEN, "%d", fm.marks.nentries);
508 color_set(RVC_MARKS, NULL);
509 mvaddstr(0, COLS - 3 - numsize, BUF1);
510 } else
511 numsize = -1;
512 color_set(RVC_CWD, NULL);
513 mbstowcs(WBUF, CWD, PATH_MAX);
514 mvaddnwstr(0, 0, WBUF, COLS - 4 - numsize);
515 wcolor_set(fm.window, RVC_BORDER, NULL);
516 wborder(fm.window, 0, 0, 0, 0, 0, 0, 0, 0);
517 ESEL = MAX(MIN(ESEL, fm.nfiles - 1), 0);
519 /*
520 * Selection might not be visible, due to cursor wrapping or
521 * window shrinking. In that case, the scroll must be moved to
522 * make it visible.
523 */
524 if (fm.nfiles > HEIGHT) {
525 SCROLL = MAX(MIN(SCROLL, ESEL), ESEL - HEIGHT + 1);
526 SCROLL = MIN(MAX(SCROLL, 0), fm.nfiles - HEIGHT);
527 } else
528 SCROLL = 0;
529 marking = !strcmp(CWD, fm.marks.dirpath);
530 for (i = 0, j = SCROLL; i < HEIGHT && j < fm.nfiles; i++, j++) {
531 ishidden = ENAME(j)[0] == '.';
532 if (j == ESEL)
533 wattr_on(fm.window, A_REVERSE, NULL);
534 if (ISLINK(j))
535 wcolor_set(fm.window, RVC_LINK, NULL);
536 else if (ishidden)
537 wcolor_set(fm.window, RVC_HIDDEN, NULL);
538 else if (S_ISREG(EMODE(j))) {
539 if (EMODE(j) & (S_IXUSR | S_IXGRP | S_IXOTH))
540 wcolor_set(fm.window, RVC_EXEC, NULL);
541 else
542 wcolor_set(fm.window, RVC_REG, NULL);
543 } else if (S_ISDIR(EMODE(j)))
544 wcolor_set(fm.window, RVC_DIR, NULL);
545 else if (S_ISCHR(EMODE(j)))
546 wcolor_set(fm.window, RVC_CHR, NULL);
547 else if (S_ISBLK(EMODE(j)))
548 wcolor_set(fm.window, RVC_BLK, NULL);
549 else if (S_ISFIFO(EMODE(j)))
550 wcolor_set(fm.window, RVC_FIFO, NULL);
551 else if (S_ISSOCK(EMODE(j)))
552 wcolor_set(fm.window, RVC_SOCK, NULL);
553 if (S_ISDIR(EMODE(j))) {
554 mbstowcs(WBUF, ENAME(j), PATH_MAX);
555 if (ISLINK(j))
556 wcscat(WBUF, L"/");
557 } else {
558 char *suffix, *suffixes = "BKMGTPEZY";
559 off_t human_size = ESIZE(j) * 10;
560 int length = mbstowcs(WBUF, ENAME(j), PATH_MAX);
561 int namecols = wcswidth(WBUF, length);
562 for (suffix = suffixes; human_size >= 10240; suffix++)
563 human_size = (human_size + 512) / 1024;
564 if (*suffix == 'B')
565 swprintf(WBUF + length, PATH_MAX - length,
566 L"%*d %c",
567 (int)(COLS - namecols - 6),
568 (int)human_size / 10, *suffix);
569 else
570 swprintf(WBUF + length, PATH_MAX - length,
571 L"%*d.%d %c",
572 (int)(COLS - namecols - 8),
573 (int)human_size / 10,
574 (int)human_size % 10, *suffix);
576 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
577 mvwaddnwstr(fm.window, i + 1, 2, WBUF, COLS - 4);
578 if (marking && MARKED(j)) {
579 wcolor_set(fm.window, RVC_MARKS, NULL);
580 mvwaddch(fm.window, i + 1, 1, RVS_MARK);
581 } else
582 mvwaddch(fm.window, i + 1, 1, ' ');
583 if (j == ESEL)
584 wattr_off(fm.window, A_REVERSE, NULL);
586 for (; i < HEIGHT; i++)
587 mvwhline(fm.window, i + 1, 1, ' ', COLS - 2);
588 if (fm.nfiles > HEIGHT) {
589 int center, height;
590 center = (SCROLL + HEIGHT / 2) * HEIGHT / fm.nfiles;
591 height = (HEIGHT - 1) * HEIGHT / fm.nfiles;
592 if (!height)
593 height = 1;
594 wcolor_set(fm.window, RVC_SCROLLBAR, NULL);
595 mvwvline(fm.window, center - height/2 + 1, COLS - 1,
596 RVS_SCROLLBAR, height);
598 BUF1[0] = FLAGS & SHOW_FILES ? 'F' : ' ';
599 BUF1[1] = FLAGS & SHOW_DIRS ? 'D' : ' ';
600 BUF1[2] = FLAGS & SHOW_HIDDEN ? 'H' : ' ';
601 if (!fm.nfiles)
602 strcpy(BUF2, "0/0");
603 else
604 snprintf(BUF2, BUFLEN, "%d/%d", ESEL + 1, fm.nfiles);
605 snprintf(BUF1 + 3, BUFLEN - 3, "%12s", BUF2);
606 color_set(RVC_STATUS, NULL);
607 mvaddstr(LINES - 1, STATUSPOS, BUF1);
608 wrefresh(fm.window);
611 /* Show a message on the status bar. */
612 static void
613 message(enum color c, char *fmt, ...)
615 int len, pos;
616 va_list args;
618 va_start(args, fmt);
619 vsnprintf(BUF1, MIN(BUFLEN, STATUSPOS), fmt, args);
620 va_end(args);
621 len = strlen(BUF1);
622 pos = (STATUSPOS - len) / 2;
623 attr_on(A_BOLD, NULL);
624 color_set(c, NULL);
625 mvaddstr(LINES - 1, pos, BUF1);
626 color_set(DEFAULT, NULL);
627 attr_off(A_BOLD, NULL);
630 /* Clear message area, leaving only status info. */
631 static void
632 clear_message()
634 mvhline(LINES - 1, 0, ' ', STATUSPOS);
637 /* Comparison used to sort listing entries. */
638 static int
639 rowcmp(const void *a, const void *b)
641 int isdir1, isdir2, cmpdir;
642 const struct row *r1 = a;
643 const struct row *r2 = b;
644 isdir1 = S_ISDIR(r1->mode);
645 isdir2 = S_ISDIR(r2->mode);
646 cmpdir = isdir2 - isdir1;
647 return cmpdir ? cmpdir : strcoll(r1->name, r2->name);
650 /* Get all entries in current working directory. */
651 static int
652 ls(struct row **rowsp, uint8_t flags)
654 DIR *dp;
655 struct dirent *ep;
656 struct stat statbuf;
657 struct row *rows;
658 int i, n;
660 if (!(dp = opendir(".")))
661 return -1;
662 n = -2; /* We don't want the entries "." and "..". */
663 while (readdir(dp))
664 n++;
665 if (n == 0) {
666 closedir(dp);
667 return 0;
669 rewinddir(dp);
670 rows = xmalloc(n * sizeof(*rows));
671 i = 0;
672 while ((ep = readdir(dp))) {
673 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
674 continue;
675 if (!(flags & SHOW_HIDDEN) && ep->d_name[0] == '.')
676 continue;
677 lstat(ep->d_name, &statbuf);
678 rows[i].islink = S_ISLNK(statbuf.st_mode);
679 stat(ep->d_name, &statbuf);
680 if (S_ISDIR(statbuf.st_mode)) {
681 if (flags & SHOW_DIRS) {
682 rows[i].name = xmalloc(strlen(ep->d_name) + 2);
683 strcpy(rows[i].name, ep->d_name);
684 if (!rows[i].islink)
685 strcat(rows[i].name, "/");
686 rows[i].mode = statbuf.st_mode;
687 i++;
689 } else if (flags & SHOW_FILES) {
690 rows[i].name = xmalloc(strlen(ep->d_name) + 1);
691 strcpy(rows[i].name, ep->d_name);
692 rows[i].size = statbuf.st_size;
693 rows[i].mode = statbuf.st_mode;
694 i++;
697 n = i; /* Ignore unused space in array caused by filters. */
698 qsort(rows, n, sizeof(*rows), rowcmp);
699 closedir(dp);
700 *rowsp = rows;
701 return n;
704 static void
705 free_rows(struct row **rowsp, int nfiles)
707 int i;
709 for (i = 0; i < nfiles; i++)
710 free((*rowsp)[i].name);
711 free(*rowsp);
712 *rowsp = NULL;
715 /* Change working directory to the path in CWD. */
716 static void
717 cd(int reset)
719 int i, j;
721 message(CYAN, "Loading \"%s\"...", CWD);
722 refresh();
723 if (chdir(CWD) == -1) {
724 getcwd(CWD, PATH_MAX - 1);
725 if (CWD[strlen(CWD) - 1] != '/')
726 strcat(CWD, "/");
727 goto done;
729 if (reset)
730 ESEL = SCROLL = 0;
731 if (fm.nfiles)
732 free_rows(&fm.rows, fm.nfiles);
733 fm.nfiles = ls(&fm.rows, FLAGS);
734 if (!strcmp(CWD, fm.marks.dirpath)) {
735 for (i = 0; i < fm.nfiles; i++) {
736 for (j = 0; j < fm.marks.bulk; j++)
737 if (fm.marks.entries[j] &&
738 !strcmp(fm.marks.entries[j], ENAME(i)))
739 break;
740 MARKED(i) = j < fm.marks.bulk;
742 } else
743 for (i = 0; i < fm.nfiles; i++)
744 MARKED(i) = 0;
745 done:
746 clear_message();
747 update_view();
750 /* Select a target entry, if it is present. */
751 static void
752 try_to_sel(const char *target)
754 ESEL = 0;
755 if (!ISDIR(target))
756 while ((ESEL + 1) < fm.nfiles && S_ISDIR(EMODE(ESEL)))
757 ESEL++;
758 while ((ESEL + 1) < fm.nfiles && strcoll(ENAME(ESEL), target) < 0)
759 ESEL++;
762 /* Reload CWD, but try to keep selection. */
763 static void
764 reload()
766 if (fm.nfiles) {
767 strcpy(INPUT, ENAME(ESEL));
768 cd(0);
769 try_to_sel(INPUT);
770 update_view();
771 } else
772 cd(1);
775 static off_t
776 count_dir(const char *path)
778 DIR *dp;
779 struct dirent *ep;
780 struct stat statbuf;
781 char subpath[PATH_MAX];
782 off_t total;
784 if (!(dp = opendir(path)))
785 return 0;
786 total = 0;
787 while ((ep = readdir(dp))) {
788 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
789 continue;
790 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
791 lstat(subpath, &statbuf);
792 if (S_ISDIR(statbuf.st_mode)) {
793 strcat(subpath, "/");
794 total += count_dir(subpath);
795 } else
796 total += statbuf.st_size;
798 closedir(dp);
799 return total;
802 static off_t
803 count_marked()
805 int i;
806 char *entry;
807 off_t total;
808 struct stat statbuf;
810 total = 0;
811 chdir(fm.marks.dirpath);
812 for (i = 0; i < fm.marks.bulk; i++) {
813 entry = fm.marks.entries[i];
814 if (entry) {
815 if (ISDIR(entry)) {
816 total += count_dir(entry);
817 } else {
818 lstat(entry, &statbuf);
819 total += statbuf.st_size;
823 chdir(CWD);
824 return total;
827 /*
828 * Recursively process a source directory using CWD as destination
829 * root. For each node (i.e. directory), do the following:
831 * 1. call pre(destination);
832 * 2. call proc() on every child leaf (i.e. files);
833 * 3. recurse into every child node;
834 * 4. call pos(source).
836 * E.g. to move directory /src/ (and all its contents) inside /dst/:
837 * strcpy(CWD, "/dst/");
838 * process_dir(adddir, movfile, deldir, "/src/");
839 */
840 static int
841 process_dir(PROCESS pre, PROCESS proc, PROCESS pos, const char *path)
843 int ret;
844 DIR *dp;
845 struct dirent *ep;
846 struct stat statbuf;
847 char subpath[PATH_MAX];
849 ret = 0;
850 if (pre) {
851 char dstpath[PATH_MAX];
852 strcpy(dstpath, CWD);
853 strcat(dstpath, path + strlen(fm . marks . dirpath));
854 ret |= pre(dstpath);
856 if (!(dp = opendir(path)))
857 return -1;
858 while ((ep = readdir(dp))) {
859 if (!strcmp(ep->d_name, ".") || !strcmp(ep->d_name, ".."))
860 continue;
861 snprintf(subpath, PATH_MAX, "%s%s", path, ep->d_name);
862 lstat(subpath, &statbuf);
863 if (S_ISDIR(statbuf.st_mode)) {
864 strcat(subpath, "/");
865 ret |= process_dir(pre, proc, pos, subpath);
866 } else
867 ret |= proc(subpath);
869 closedir(dp);
870 if (pos)
871 ret |= pos(path);
872 return ret;
875 /*
876 * Process all marked entries using CWD as destination root. All
877 * marked entries that are directories will be recursively processed.
878 * See process_dir() for details on the parameters.
879 */
880 static void
881 process_marked(PROCESS pre, PROCESS proc, PROCESS pos, const char *msg_doing,
882 const char *msg_done)
884 int i, ret;
885 char *entry;
886 char path[PATH_MAX];
888 clear_message();
889 message(CYAN, "%s...", msg_doing);
890 refresh();
891 fm.prog = (struct prog){0, count_marked(), msg_doing};
892 for (i = 0; i < fm.marks.bulk; i++) {
893 entry = fm.marks.entries[i];
894 if (entry) {
895 ret = 0;
896 snprintf(path, PATH_MAX, "%s%s", fm.marks.dirpath,
897 entry);
898 if (ISDIR(entry)) {
899 if (!strncmp(path, CWD, strlen(path)))
900 ret = -1;
901 else
902 ret = process_dir(pre, proc, pos, path);
903 } else
904 ret = proc(path);
905 if (!ret) {
906 del_mark(&fm.marks, entry);
907 reload();
911 fm.prog.total = 0;
912 reload();
913 if (!fm.marks.nentries)
914 message(GREEN, "%s all marked entries.", msg_done);
915 else
916 message(RED, "Some errors occured while %s.", msg_doing);
917 RV_ALERT();
920 static void
921 update_progress(off_t delta)
923 int percent;
925 if (!fm.prog.total)
926 return;
927 fm.prog.partial += delta;
928 percent = (int)(fm.prog.partial * 100 / fm.prog.total);
929 message(CYAN, "%s...%d%%", fm.prog.msg, percent);
930 refresh();
933 /* Wrappers for file operations. */
934 static int
935 delfile(const char *path)
937 int ret;
938 struct stat st;
940 ret = lstat(path, &st);
941 if (ret < 0)
942 return ret;
943 update_progress(st.st_size);
944 return unlink(path);
947 static PROCESS deldir = rmdir;
948 static int
949 addfile(const char *path)
951 /* Using creat(2) because mknod(2) doesn't seem to be portable. */
952 int ret;
954 ret = creat(path, 0644);
955 if (ret < 0)
956 return ret;
957 return close(ret);
960 static int
961 cpyfile(const char *srcpath)
963 int src, dst, ret;
964 size_t size;
965 struct stat st;
966 char buf[BUFSIZ];
967 char dstpath[PATH_MAX];
969 strcpy(dstpath, CWD);
970 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
971 ret = lstat(srcpath, &st);
972 if (ret < 0)
973 return ret;
974 if (S_ISLNK(st.st_mode)) {
975 ret = readlink(srcpath, BUF1, BUFLEN - 1);
976 if (ret < 0)
977 return ret;
978 BUF1[ret] = '\0';
979 ret = symlink(BUF1, dstpath);
980 } else {
981 ret = src = open(srcpath, O_RDONLY);
982 if (ret < 0)
983 return ret;
984 ret = dst = creat(dstpath, st.st_mode);
985 if (ret < 0)
986 return ret;
987 while ((size = read(src, buf, BUFSIZ)) > 0) {
988 write(dst, buf, size);
989 update_progress(size);
990 sync_signals();
992 close(src);
993 close(dst);
994 ret = 0;
996 return ret;
999 static int
1000 adddir(const char *path)
1002 int ret;
1003 struct stat st;
1005 ret = stat(CWD, &st);
1006 if (ret < 0)
1007 return ret;
1008 return mkdir(path, st.st_mode);
1011 static int
1012 movfile(const char *srcpath)
1014 int ret;
1015 struct stat st;
1016 char dstpath[PATH_MAX];
1018 strcpy(dstpath, CWD);
1019 strcat(dstpath, srcpath + strlen(fm.marks.dirpath));
1020 ret = rename(srcpath, dstpath);
1021 if (ret == 0) {
1022 ret = lstat(dstpath, &st);
1023 if (ret < 0)
1024 return ret;
1025 update_progress(st.st_size);
1026 } else if (errno == EXDEV) {
1027 ret = cpyfile(srcpath);
1028 if (ret < 0)
1029 return ret;
1030 ret = unlink(srcpath);
1032 return ret;
1035 static void
1036 start_line_edit(const char *init_input)
1038 curs_set(TRUE);
1039 strncpy(INPUT, init_input, BUFLEN);
1040 fm.edit.left = mbstowcs(fm.edit.buffer, init_input, BUFLEN);
1041 fm.edit.right = BUFLEN - 1;
1042 fm.edit.buffer[BUFLEN] = L'\0';
1043 fm.edit_scroll = 0;
1046 /* Read input and change editing state accordingly. */
1047 static enum editstate
1048 get_line_edit()
1050 wchar_t eraser, killer, wch;
1051 int ret, length;
1053 ret = fm_get_wch((wint_t *)&wch);
1054 erasewchar(&eraser);
1055 killwchar(&killer);
1056 if (ret == KEY_CODE_YES) {
1057 if (wch == KEY_ENTER) {
1058 curs_set(FALSE);
1059 return CONFIRM;
1060 } else if (wch == KEY_LEFT) {
1061 if (EDIT_CAN_LEFT(fm.edit))
1062 EDIT_LEFT(fm.edit);
1063 } else if (wch == KEY_RIGHT) {
1064 if (EDIT_CAN_RIGHT(fm.edit))
1065 EDIT_RIGHT(fm.edit);
1066 } else if (wch == KEY_UP) {
1067 while (EDIT_CAN_LEFT(fm.edit))
1068 EDIT_LEFT(fm.edit);
1069 } else if (wch == KEY_DOWN) {
1070 while (EDIT_CAN_RIGHT(fm.edit))
1071 EDIT_RIGHT(fm.edit);
1072 } else if (wch == KEY_BACKSPACE) {
1073 if (EDIT_CAN_LEFT(fm.edit))
1074 EDIT_BACKSPACE(fm.edit);
1075 } else if (wch == KEY_DC) {
1076 if (EDIT_CAN_RIGHT(fm.edit))
1077 EDIT_DELETE(fm.edit);
1079 } else {
1080 if (wch == L'\r' || wch == L'\n') {
1081 curs_set(FALSE);
1082 return CONFIRM;
1083 } else if (wch == L'\t') {
1084 curs_set(FALSE);
1085 return CANCEL;
1086 } else if (wch == eraser) {
1087 if (EDIT_CAN_LEFT(fm.edit))
1088 EDIT_BACKSPACE(fm.edit);
1089 } else if (wch == killer) {
1090 EDIT_CLEAR(fm.edit);
1091 clear_message();
1092 } else if (iswprint(wch)) {
1093 if (!EDIT_FULL(fm.edit))
1094 EDIT_INSERT(fm.edit, wch);
1097 /* Encode edit contents in INPUT. */
1098 fm.edit.buffer[fm.edit.left] = L'\0';
1099 length = wcstombs(INPUT, fm.edit.buffer, BUFLEN);
1100 wcstombs(&INPUT[length], &fm.edit.buffer[fm.edit.right + 1],
1101 BUFLEN - length);
1102 return CONTINUE;
1105 /* Update line input on the screen. */
1106 static void
1107 update_input(const char *prompt, enum color c)
1109 int plen, ilen, maxlen;
1111 plen = strlen(prompt);
1112 ilen = mbstowcs(NULL, INPUT, 0);
1113 maxlen = STATUSPOS - plen - 2;
1114 if (ilen - fm.edit_scroll < maxlen)
1115 fm.edit_scroll = MAX(ilen - maxlen, 0);
1116 else if (fm.edit.left > fm.edit_scroll + maxlen - 1)
1117 fm.edit_scroll = fm.edit.left - maxlen;
1118 else if (fm.edit.left < fm.edit_scroll)
1119 fm.edit_scroll = MAX(fm.edit.left - maxlen, 0);
1120 color_set(RVC_PROMPT, NULL);
1121 mvaddstr(LINES - 1, 0, prompt);
1122 color_set(c, NULL);
1123 mbstowcs(WBUF, INPUT, COLS);
1124 mvaddnwstr(LINES - 1, plen, &WBUF[fm.edit_scroll], maxlen);
1125 mvaddch(LINES - 1, plen + MIN(ilen - fm.edit_scroll, maxlen + 1),
1126 ' ');
1127 color_set(DEFAULT, NULL);
1128 if (fm.edit_scroll)
1129 mvaddch(LINES - 1, plen - 1, '<');
1130 if (ilen > fm.edit_scroll + maxlen)
1131 mvaddch(LINES - 1, plen + maxlen, '>');
1132 move(LINES - 1, plen + fm.edit.left - fm.edit_scroll);
1135 int
1136 main(int argc, char *argv[])
1138 int i, ch;
1139 char *program;
1140 char *entry;
1141 const char *key;
1142 const char *clip_path;
1143 DIR *d;
1144 enum editstate edit_stat;
1145 FILE *save_cwd_file = NULL;
1146 FILE *save_marks_file = NULL;
1147 FILE *clip_file;
1149 while ((ch = getopt_long(argc, argv, "d:hm:v", opts, NULL)) != -1) {
1150 switch (ch) {
1151 case 'd':
1152 if ((save_cwd_file = fopen(optarg, "w")) == NULL)
1153 err(1, "open %s", optarg);
1154 break;
1155 case 'h':
1156 printf(""
1157 "Usage: fm [-hv] [-d file] [-m file] [dirs...]\n"
1158 "Browse current directory or the ones specified.\n"
1159 "\n"
1160 "See fm(1) for more information.\n"
1161 "fm homepage <https://github.com/omar-polo/fm>\n");
1162 return 0;
1163 case 'm':
1164 if ((save_marks_file = fopen(optarg, "a")) == NULL)
1165 err(1, "open %s", optarg);
1166 break;
1167 case 'v':
1168 printf("version: fm %s\n", RV_VERSION);
1169 return 0;
1173 get_user_programs();
1174 init_term();
1175 fm.nfiles = 0;
1176 for (i = 0; i < 10; i++) {
1177 fm.tabs[i].esel = fm.tabs[i].scroll = 0;
1178 fm.tabs[i].flags = RV_FLAGS;
1180 strcpy(fm.tabs[0].cwd, getenv("HOME"));
1181 for (i = 1; i < argc && i < 10; i++) {
1182 if ((d = opendir(argv[i]))) {
1183 realpath(argv[i], fm.tabs[i].cwd);
1184 closedir(d);
1185 } else
1186 strcpy(fm.tabs[i].cwd, fm.tabs[0].cwd);
1188 getcwd(fm.tabs[i].cwd, PATH_MAX);
1189 for (i++; i < 10; i++)
1190 strcpy(fm.tabs[i].cwd, fm.tabs[i - 1].cwd);
1191 for (i = 0; i < 10; i++)
1192 if (fm.tabs[i].cwd[strlen(fm.tabs[i].cwd) - 1] != '/')
1193 strcat(fm.tabs[i].cwd, "/");
1194 fm.tab = 1;
1195 fm.window = subwin(stdscr, LINES - 2, COLS, 1, 0);
1196 init_marks(&fm.marks);
1197 cd(1);
1198 strcpy(CLIPBOARD, CWD);
1199 if (fm.nfiles > 0)
1200 strcat(CLIPBOARD, ENAME(ESEL));
1201 while (1) {
1202 ch = fm_getch();
1203 key = keyname(ch);
1204 clear_message();
1205 if (!strcmp(key, RVK_QUIT))
1206 break;
1207 else if (ch >= '0' && ch <= '9') {
1208 fm.tab = ch - '0';
1209 cd(0);
1210 } else if (!strcmp(key, RVK_HELP)) {
1211 spawn((char *[]) { "man", "fm", NULL });
1212 } else if (!strcmp(key, RVK_DOWN)) {
1213 if (!fm.nfiles)
1214 continue;
1215 ESEL = MIN(ESEL + 1, fm.nfiles - 1);
1216 update_view();
1217 } else if (!strcmp(key, RVK_UP)) {
1218 if (!fm.nfiles)
1219 continue;
1220 ESEL = MAX(ESEL - 1, 0);
1221 update_view();
1222 } else if (!strcmp(key, RVK_JUMP_DOWN)) {
1223 if (!fm.nfiles)
1224 continue;
1225 ESEL = MIN(ESEL + RV_JUMP, fm.nfiles - 1);
1226 if (fm.nfiles > HEIGHT)
1227 SCROLL = MIN(SCROLL + RV_JUMP,
1228 fm.nfiles - HEIGHT);
1229 update_view();
1230 } else if (!strcmp(key, RVK_JUMP_UP)) {
1231 if (!fm.nfiles)
1232 continue;
1233 ESEL = MAX(ESEL - RV_JUMP, 0);
1234 SCROLL = MAX(SCROLL - RV_JUMP, 0);
1235 update_view();
1236 } else if (!strcmp(key, RVK_JUMP_TOP)) {
1237 if (!fm.nfiles)
1238 continue;
1239 ESEL = 0;
1240 update_view();
1241 } else if (!strcmp(key, RVK_JUMP_BOTTOM)) {
1242 if (!fm.nfiles)
1243 continue;
1244 ESEL = fm.nfiles - 1;
1245 update_view();
1246 } else if (!strcmp(key, RVK_CD_DOWN)) {
1247 if (!fm.nfiles || !S_ISDIR(EMODE(ESEL)))
1248 continue;
1249 if (chdir(ENAME(ESEL)) == -1) {
1250 message(RED, "Cannot access \"%s\".",
1251 ENAME(ESEL));
1252 continue;
1254 strcat(CWD, ENAME(ESEL));
1255 cd(1);
1256 } else if (!strcmp(key, RVK_CD_UP)) {
1257 char *dirname, first;
1258 if (!strcmp(CWD, "/"))
1259 continue;
1260 CWD[strlen(CWD) - 1] = '\0';
1261 dirname = strrchr(CWD, '/') + 1;
1262 first = dirname[0];
1263 dirname[0] = '\0';
1264 cd(1);
1265 dirname[0] = first;
1266 dirname[strlen(dirname)] = '/';
1267 try_to_sel(dirname);
1268 dirname[0] = '\0';
1269 if (fm.nfiles > HEIGHT)
1270 SCROLL = ESEL - HEIGHT / 2;
1271 update_view();
1272 } else if (!strcmp(key, RVK_HOME)) {
1273 strcpy(CWD, getenv("HOME"));
1274 if (CWD[strlen(CWD) - 1] != '/')
1275 strcat(CWD, "/");
1276 cd(1);
1277 } else if (!strcmp(key, RVK_TARGET)) {
1278 char *bname, first;
1279 int is_dir = S_ISDIR(EMODE(ESEL));
1280 ssize_t len = readlink(ENAME(ESEL), BUF1, BUFLEN - 1);
1281 if (len == -1)
1282 continue;
1283 BUF1[len] = '\0';
1284 if (access(BUF1, F_OK) == -1) {
1285 char *msg;
1286 switch (errno) {
1287 case EACCES:
1288 msg = "Cannot access \"%s\".";
1289 break;
1290 case ENOENT:
1291 msg = "\"%s\" does not exist.";
1292 break;
1293 default:
1294 msg = "Cannot navigate to \"%s\".";
1296 strcpy(BUF2, BUF1); /* message() uses BUF1. */
1297 message(RED, msg, BUF2);
1298 continue;
1300 realpath(BUF1, CWD);
1301 len = strlen(CWD);
1302 if (CWD[len - 1] == '/')
1303 CWD[len - 1] = '\0';
1304 bname = strrchr(CWD, '/') + 1;
1305 first = *bname;
1306 *bname = '\0';
1307 cd(1);
1308 *bname = first;
1309 if (is_dir)
1310 strcat(CWD, "/");
1311 try_to_sel(bname);
1312 *bname = '\0';
1313 update_view();
1314 } else if (!strcmp(key, RVK_COPY_PATH)) {
1315 clip_path = getenv("CLIP");
1316 if (!clip_path)
1317 goto copy_path_fail;
1318 clip_file = fopen(clip_path, "w");
1319 if (!clip_file)
1320 goto copy_path_fail;
1321 fprintf(clip_file, "%s%s\n", CWD, ENAME(ESEL));
1322 fclose(clip_file);
1323 goto copy_path_done;
1324 copy_path_fail:
1325 strcpy(CLIPBOARD, CWD);
1326 strcat(CLIPBOARD, ENAME(ESEL));
1327 copy_path_done:
1329 } else if (!strcmp(key, RVK_PASTE_PATH)) {
1330 clip_path = getenv("CLIP");
1331 if (!clip_path)
1332 goto paste_path_fail;
1333 clip_file = fopen(clip_path, "r");
1334 if (!clip_file)
1335 goto paste_path_fail;
1336 fscanf(clip_file, "%s\n", CLIPBOARD);
1337 fclose(clip_file);
1338 paste_path_fail:
1339 strcpy(BUF1, CLIPBOARD);
1340 strcpy(CWD, dirname(BUF1));
1341 if (strcmp(CWD, "/"))
1342 strcat(CWD, "/");
1343 cd(1);
1344 strcpy(BUF1, CLIPBOARD);
1345 try_to_sel(strstr(CLIPBOARD, basename(BUF1)));
1346 update_view();
1347 } else if (!strcmp(key, RVK_REFRESH)) {
1348 reload();
1349 } else if (!strcmp(key, RVK_SHELL)) {
1350 program = user_shell;
1351 if (program) {
1352 #ifdef RV_SHELL
1353 spawn((char *[]) { RV_SHELL, "-c", program,
1354 NULL});
1355 #else
1356 spawn((char *[]) { program, NULL });
1357 #endif
1358 reload();
1360 } else if (!strcmp(key, RVK_VIEW)) {
1361 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1362 continue;
1363 if (open_with_env(user_pager, ENAME(ESEL)))
1364 cd(0);
1365 } else if (!strcmp(key, RVK_EDIT)) {
1366 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1367 continue;
1368 if (open_with_env(user_editor, ENAME(ESEL)))
1369 cd(0);
1370 } else if (!strcmp(key, RVK_OPEN)) {
1371 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1372 continue;
1373 if (open_with_env(user_open, ENAME(ESEL)))
1374 cd(0);
1375 } else if (!strcmp(key, RVK_SEARCH)) {
1376 int oldsel, oldscroll, length;
1377 if (!fm.nfiles)
1378 continue;
1379 oldsel = ESEL;
1380 oldscroll = SCROLL;
1381 start_line_edit("");
1382 update_input(RVP_SEARCH, RED);
1383 while ((edit_stat = get_line_edit()) == CONTINUE) {
1384 int sel;
1385 enum color c = RED;
1386 length = strlen(INPUT);
1387 if (length) {
1388 for (sel = 0; sel < fm.nfiles; sel++)
1389 if (!strncmp(ENAME(sel), INPUT,
1390 length))
1391 break;
1392 if (sel < fm.nfiles) {
1393 c = GREEN;
1394 ESEL = sel;
1395 if (fm.nfiles > HEIGHT) {
1396 if (sel < 3)
1397 SCROLL = 0;
1398 else if (sel - 3 >
1399 fm.nfiles -
1400 HEIGHT)
1401 SCROLL = fm.nfiles -
1402 HEIGHT;
1403 else
1404 SCROLL = sel -
1408 } else {
1409 ESEL = oldsel;
1410 SCROLL = oldscroll;
1412 update_view();
1413 update_input(RVP_SEARCH, c);
1415 if (edit_stat == CANCEL) {
1416 ESEL = oldsel;
1417 SCROLL = oldscroll;
1419 clear_message();
1420 update_view();
1421 } else if (!strcmp(key, RVK_TG_FILES)) {
1422 FLAGS ^= SHOW_FILES;
1423 reload();
1424 } else if (!strcmp(key, RVK_TG_DIRS)) {
1425 FLAGS ^= SHOW_DIRS;
1426 reload();
1427 } else if (!strcmp(key, RVK_TG_HIDDEN)) {
1428 FLAGS ^= SHOW_HIDDEN;
1429 reload();
1430 } else if (!strcmp(key, RVK_NEW_FILE)) {
1431 int ok = 0;
1432 start_line_edit("");
1433 update_input(RVP_NEW_FILE, RED);
1434 while ((edit_stat = get_line_edit()) == CONTINUE) {
1435 int length = strlen(INPUT);
1436 ok = length;
1437 for (i = 0; i < fm.nfiles; i++) {
1438 if (
1439 !strncmp(ENAME(i), INPUT, length) &&
1440 (!strcmp(ENAME(i) + length, "") ||
1441 !strcmp(ENAME(i) + length, "/"))
1442 ) {
1443 ok = 0;
1444 break;
1447 update_input(RVP_NEW_FILE, ok ? GREEN : RED);
1449 clear_message();
1450 if (edit_stat == CONFIRM) {
1451 if (ok) {
1452 if (addfile(INPUT) == 0) {
1453 cd(1);
1454 try_to_sel(INPUT);
1455 update_view();
1456 } else
1457 message(RED,
1458 "Could not create \"%s\".",
1459 INPUT);
1460 } else
1461 message(RED, "\"%s\" already exists.",
1462 INPUT);
1464 } else if (!strcmp(key, RVK_NEW_DIR)) {
1465 int ok = 0;
1466 start_line_edit("");
1467 update_input(RVP_NEW_DIR, RED);
1468 while ((edit_stat = get_line_edit()) == CONTINUE) {
1469 int length = strlen(INPUT);
1470 ok = length;
1471 for (i = 0; i < fm.nfiles; i++) {
1472 if (
1473 !strncmp(ENAME(i), INPUT, length) &&
1474 (!strcmp(ENAME(i) + length, "") ||
1475 !strcmp(ENAME(i) + length, "/"))
1476 ) {
1477 ok = 0;
1478 break;
1481 update_input(RVP_NEW_DIR, ok ? GREEN : RED);
1483 clear_message();
1484 if (edit_stat == CONFIRM) {
1485 if (ok) {
1486 if (adddir(INPUT) == 0) {
1487 cd(1);
1488 strcat(INPUT, "/");
1489 try_to_sel(INPUT);
1490 update_view();
1491 } else
1492 message(RED,
1493 "Could not create \"%s/\".",
1494 INPUT);
1495 } else
1496 message(RED, "\"%s\" already exists.",
1497 INPUT);
1499 } else if (!strcmp(key, RVK_RENAME)) {
1500 int ok = 0;
1501 char *last;
1502 int isdir;
1503 strcpy(INPUT, ENAME(ESEL));
1504 last = INPUT + strlen(INPUT) - 1;
1505 if ((isdir = *last == '/'))
1506 *last = '\0';
1507 start_line_edit(INPUT);
1508 update_input(RVP_RENAME, RED);
1509 while ((edit_stat = get_line_edit()) == CONTINUE) {
1510 int length = strlen(INPUT);
1511 ok = length;
1512 for (i = 0; i < fm.nfiles; i++)
1513 if (
1514 !strncmp(ENAME(i), INPUT, length) &&
1515 (!strcmp(ENAME(i) + length, "") ||
1516 !strcmp(ENAME(i) + length, "/"))
1517 ) {
1518 ok = 0;
1519 break;
1521 update_input(RVP_RENAME, ok ? GREEN : RED);
1523 clear_message();
1524 if (edit_stat == CONFIRM) {
1525 if (isdir)
1526 strcat(INPUT, "/");
1527 if (ok) {
1528 if (!rename(ENAME(ESEL), INPUT) &&
1529 MARKED(ESEL)) {
1530 del_mark(&fm.marks,
1531 ENAME(ESEL));
1532 add_mark(&fm.marks, CWD,
1533 INPUT);
1535 cd(1);
1536 try_to_sel(INPUT);
1537 update_view();
1538 } else
1539 message(RED, "\"%s\" already exists.",
1540 INPUT);
1542 } else if (!strcmp(key, RVK_TG_EXEC)) {
1543 if (!fm.nfiles || S_ISDIR(EMODE(ESEL)))
1544 continue;
1545 if (S_IXUSR & EMODE(ESEL))
1546 EMODE(ESEL) &= ~(S_IXUSR | S_IXGRP | S_IXOTH);
1547 else
1548 EMODE(ESEL) |= S_IXUSR | S_IXGRP | S_IXOTH;
1549 if (chmod(ENAME(ESEL), EMODE(ESEL))) {
1550 message(RED,
1551 "Failed to change mode of \"%s\".",
1552 ENAME(ESEL));
1553 } else {
1554 message(GREEN, "Changed mode of \"%s\".",
1555 ENAME(ESEL));
1556 update_view();
1558 } else if (!strcmp(key, RVK_DELETE)) {
1559 if (fm.nfiles) {
1560 message(YELLOW, "Delete \"%s\"? (Y/n)",
1561 ENAME(ESEL));
1562 if (fm_getch() == 'Y') {
1563 const char *name = ENAME(ESEL);
1564 int ret = ISDIR(ENAME(ESEL)) ?
1565 deldir(name) : delfile(name);
1566 reload();
1567 if (ret)
1568 message(RED,
1569 "Could not delete \"%s\".",
1570 ENAME(ESEL));
1571 } else
1572 clear_message();
1573 } else
1574 message(RED, "No entry selected for deletion.");
1575 } else if (!strcmp(key, RVK_TG_MARK)) {
1576 if (MARKED(ESEL))
1577 del_mark(&fm.marks, ENAME(ESEL));
1578 else
1579 add_mark(&fm.marks, CWD, ENAME(ESEL));
1580 MARKED(ESEL) = !MARKED(ESEL);
1581 ESEL = (ESEL + 1) % fm.nfiles;
1582 update_view();
1583 } else if (!strcmp(key, RVK_INVMARK)) {
1584 for (i = 0; i < fm.nfiles; i++) {
1585 if (MARKED(i))
1586 del_mark(&fm.marks, ENAME(i));
1587 else
1588 add_mark(&fm.marks, CWD, ENAME(i));
1589 MARKED(i) = !MARKED(i);
1591 update_view();
1592 } else if (!strcmp(key, RVK_MARKALL)) {
1593 for (i = 0; i < fm.nfiles; i++)
1594 if (!MARKED(i)) {
1595 add_mark(&fm.marks, CWD, ENAME(i));
1596 MARKED(i) = 1;
1598 update_view();
1599 } else if (!strcmp(key, RVK_MARK_DELETE)) {
1600 if (fm.marks.nentries) {
1601 message(YELLOW,
1602 "Delete all marked entries? (Y/n)");
1603 if (fm_getch() == 'Y')
1604 process_marked(NULL, delfile, deldir,
1605 "Deleting", "Deleted");
1606 else
1607 clear_message();
1608 } else
1609 message(RED, "No entries marked for deletion.");
1610 } else if (!strcmp(key, RVK_MARK_COPY)) {
1611 if (fm.marks.nentries) {
1612 if (strcmp(CWD, fm.marks.dirpath))
1613 process_marked(adddir, cpyfile, NULL,
1614 "Copying", "Copied");
1615 else
1616 message(RED,
1617 "Cannot copy to the same path.");
1618 } else
1619 message(RED, "No entries marked for copying.");
1620 } else if (!strcmp(key, RVK_MARK_MOVE)) {
1621 if (fm.marks.nentries) {
1622 if (strcmp(CWD, fm.marks.dirpath))
1623 process_marked(adddir, movfile, deldir,
1624 "Moving", "Moved");
1625 else
1626 message(RED,
1627 "Cannot move to the same path.");
1628 } else
1629 message(RED, "No entries marked for moving.");
1632 if (fm.nfiles)
1633 free_rows(&fm.rows, fm.nfiles);
1634 delwin(fm.window);
1635 if (save_cwd_file != NULL) {
1636 fputs(CWD, save_cwd_file);
1637 fclose(save_cwd_file);
1639 if (save_marks_file != NULL) {
1640 for (i = 0; i < fm.marks.bulk; i++) {
1641 entry = fm.marks.entries[i];
1642 if (entry)
1643 fprintf(save_marks_file, "%s%s\n",
1644 fm.marks.dirpath, entry);
1646 fclose(save_marks_file);
1648 free_marks(&fm.marks);
1649 return 0;