My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

2729 行
57 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. #ifdef __linux__
  3. #include <sys/inotify.h>
  4. #define LINUX_INOTIFY
  5. #endif
  6. #include <sys/resource.h>
  7. #include <sys/stat.h>
  8. #include <sys/statvfs.h>
  9. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  10. # include <sys/types.h>
  11. #include <sys/event.h>
  12. #include <sys/time.h>
  13. #define BSD_KQUEUE
  14. #else
  15. # include <sys/sysmacros.h>
  16. #endif
  17. #include <sys/wait.h>
  18. #include <ctype.h>
  19. #include <curses.h>
  20. #include <dirent.h>
  21. #include <errno.h>
  22. #include <fcntl.h>
  23. #include <grp.h>
  24. #include <libgen.h>
  25. #include <limits.h>
  26. #ifdef __gnu_hurd__
  27. #define PATH_MAX 4096
  28. #endif
  29. #include <locale.h>
  30. #include <pwd.h>
  31. #include <regex.h>
  32. #include <signal.h>
  33. #include <stdarg.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <time.h>
  38. #include <unistd.h>
  39. #include <wchar.h>
  40. #include <readline/readline.h>
  41. #ifndef __USE_XOPEN_EXTENDED
  42. #define __USE_XOPEN_EXTENDED 1
  43. #endif
  44. #include <ftw.h>
  45. #include "config.h"
  46. #ifdef DEBUGMODE
  47. static int DEBUG_FD;
  48. static int
  49. xprintf(int fd, const char *fmt, ...)
  50. {
  51. char buf[BUFSIZ];
  52. int r;
  53. va_list ap;
  54. va_start(ap, fmt);
  55. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  56. if (r > 0)
  57. r = write(fd, buf, r);
  58. va_end(ap);
  59. return r;
  60. }
  61. static int
  62. enabledbg()
  63. {
  64. FILE *fp = fopen("/tmp/nnn_debug", "w");
  65. if (!fp) {
  66. fprintf(stderr, "Cannot open debug file\n");
  67. return -1;
  68. }
  69. DEBUG_FD = fileno(fp);
  70. if (DEBUG_FD == -1) {
  71. fprintf(stderr, "Cannot open debug file descriptor\n");
  72. return -1;
  73. }
  74. return 0;
  75. }
  76. static void
  77. disabledbg()
  78. {
  79. close(DEBUG_FD);
  80. }
  81. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  82. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  83. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  84. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=0x%p\n", x)
  85. #else
  86. #define DPRINTF_D(x)
  87. #define DPRINTF_U(x)
  88. #define DPRINTF_S(x)
  89. #define DPRINTF_P(x)
  90. #endif /* DEBUGMODE */
  91. /* Macro definitions */
  92. #define VERSION "1.3"
  93. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  94. #undef MIN
  95. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  96. #define ISODD(x) ((x) & 1)
  97. #define TOUPPER(ch) \
  98. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  99. #define MAX_CMD_LEN 5120
  100. #define CWD "cwd: "
  101. #define CURSR " > "
  102. #define EMPTY " "
  103. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  104. #define FILTER '/'
  105. #define MAX_BM 10
  106. /* Macros to define process spawn behaviour as flags */
  107. #define F_NONE 0x00 /* no flag set */
  108. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  109. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  110. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  111. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  112. #define F_NORMAL 0x80 /* spawn child process in non-curses regular mode */
  113. #define exitcurses() endwin()
  114. #define clearprompt() printmsg("")
  115. #define printwarn() printmsg(strerror(errno))
  116. #define istopdir(path) (path[1] == '\0' && path[0] == '/')
  117. #ifdef LINUX_INOTIFY
  118. #define EVENT_SIZE (sizeof(struct inotify_event))
  119. #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
  120. #elif defined(BSD_KQUEUE)
  121. #define NUM_EVENT_SLOTS 1
  122. #define NUM_EVENT_FDS 1
  123. #endif
  124. typedef unsigned long ulong;
  125. typedef unsigned int uint;
  126. typedef unsigned char uchar;
  127. /* Directory entry */
  128. typedef struct entry {
  129. char name[NAME_MAX];
  130. mode_t mode;
  131. time_t t;
  132. off_t size;
  133. blkcnt_t blocks; /* number of 512B blocks allocated */
  134. } *pEntry;
  135. /* Bookmark */
  136. typedef struct {
  137. char *key;
  138. char *loc;
  139. } bm;
  140. /* Settings */
  141. typedef struct {
  142. uchar filtermode : 1; /* Set to enter filter mode */
  143. uchar mtimeorder : 1; /* Set to sort by time modified */
  144. uchar sizeorder : 1; /* Set to sort by file size */
  145. uchar blkorder : 1; /* Set to sort by blocks used (disk usage) */
  146. uchar showhidden : 1; /* Set to show hidden files */
  147. uchar showdetail : 1; /* Clear to show fewer file info */
  148. uchar showcolor : 1; /* Set to show dirs in blue */
  149. uchar dircolor : 1; /* Current status of dir color */
  150. } settings;
  151. /* Externs */
  152. #ifdef __APPLE__
  153. extern int add_history(const char *string);
  154. #else
  155. extern void add_history(const char *string);
  156. #endif
  157. extern int wget_wch(WINDOW *win, wint_t *wch);
  158. /* Globals */
  159. /* Configuration */
  160. static settings cfg = {0, 0, 0, 0, 0, 1, 1, 0};
  161. static struct entry *dents;
  162. static int ndents, cur, total_dents;
  163. static uint idle;
  164. static uint idletimeout;
  165. static char *player;
  166. static char *copier;
  167. static char *editor;
  168. static char *desktop_manager;
  169. static blkcnt_t ent_blocks;
  170. static blkcnt_t dir_blocks;
  171. static ulong num_files;
  172. static size_t fs_free;
  173. static uint open_max;
  174. static bm bookmark[MAX_BM];
  175. static const double div_2_pow_10 = 1.0 / 1024.0;
  176. static uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  177. static uchar color = 4;
  178. #ifdef LINUX_INOTIFY
  179. static int inotify_fd, inotify_wd = -1;
  180. static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  181. #elif defined(BSD_KQUEUE)
  182. static int kq, event_fd = -1;
  183. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  184. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  185. static struct timespec gtimeout;
  186. #endif
  187. /* Utilities to open files, run actions */
  188. static char * const utils[] = {
  189. #ifdef __APPLE__
  190. "/usr/bin/open",
  191. #else
  192. "/usr/bin/xdg-open",
  193. #endif
  194. "nlay",
  195. "mediainfo",
  196. "exiftool"
  197. };
  198. static char *metaviewer;
  199. /* For use in functions which are isolated and don't return the buffer */
  200. static char g_buf[MAX_CMD_LEN];
  201. /* Common message strings */
  202. static char *STR_NFTWFAIL = "nftw(3) failed";
  203. static char *STR_ATROOT = "You are at /";
  204. static char *STR_NOHOME = "HOME not set";
  205. /*
  206. * Layout:
  207. * .---------
  208. * | cwd: /mnt/path
  209. * |
  210. * | file0
  211. * | file1
  212. * | > file2
  213. * | file3
  214. * | file4
  215. * ...
  216. * | filen
  217. * |
  218. * | Permission denied
  219. * '------
  220. */
  221. /* Forward declarations */
  222. static void printmsg(char *);
  223. static void printerr(int, char *);
  224. static void redraw(char *path);
  225. /* Functions */
  226. /* Increase the limit on open file descriptors, if possible */
  227. static rlim_t
  228. max_openfds()
  229. {
  230. struct rlimit rl;
  231. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  232. if (limit != 0)
  233. return 32;
  234. limit = rl.rlim_cur;
  235. rl.rlim_cur = rl.rlim_max;
  236. /* Return ~75% of max possible */
  237. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  238. limit = rl.rlim_max - (rl.rlim_max >> 2);
  239. /*
  240. * 20K is arbitrary> If the limit is set to max possible
  241. * value, the memory usage increases to more than double.
  242. */
  243. return limit > 20480 ? 20480 : limit;
  244. }
  245. return limit;
  246. }
  247. /*
  248. * Custom xstrlen()
  249. */
  250. static size_t
  251. xstrlen(const char *s)
  252. {
  253. static size_t len;
  254. if (!s)
  255. return 0;
  256. len = 0;
  257. while (*s)
  258. ++len, ++s;
  259. return len;
  260. }
  261. /*
  262. * Just a safe strncpy(3)
  263. * Always null ('\0') terminates if both src and dest are valid pointers.
  264. * Returns the number of bytes copied including terminating null byte.
  265. */
  266. static size_t
  267. xstrlcpy(char *dest, const char *src, size_t n)
  268. {
  269. static size_t len, blocks;
  270. if (!src || !dest)
  271. return 0;
  272. len = xstrlen(src) + 1;
  273. if (n > len)
  274. n = len;
  275. else if (len > n)
  276. /* Save total number of bytes to copy in len */
  277. len = n;
  278. blocks = n >> _WSHIFT;
  279. n -= (blocks << _WSHIFT);
  280. if (blocks) {
  281. static ulong *s, *d;
  282. s = (ulong *)src;
  283. d = (ulong *)dest;
  284. while (blocks) {
  285. *d = *s;
  286. ++d, ++s;
  287. --blocks;
  288. }
  289. if (!n) {
  290. dest = (char *)d;
  291. *--dest = '\0';
  292. return len;
  293. }
  294. src = (char *)s;
  295. dest = (char *)d;
  296. }
  297. while (--n && (*dest = *src))
  298. ++dest, ++src;
  299. if (!n)
  300. *dest = '\0';
  301. return len;
  302. }
  303. /*
  304. * Custom strcmp(), just what we need.
  305. * Returns 0 if same, else -1
  306. */
  307. static int
  308. xstrcmp(const char *s1, const char *s2)
  309. {
  310. if (!s1 || !s2)
  311. return -1;
  312. while (*s1 && *s1 == *s2)
  313. ++s1, ++s2;
  314. if (*s1 != *s2)
  315. return -1;
  316. return 0;
  317. }
  318. /*
  319. * The poor man's implementation of memrchr(3).
  320. * We are only looking for '/' in this program.
  321. * Ideally 0 < n <= strlen(s).
  322. */
  323. static void *
  324. xmemrchr(uchar *s, uchar ch, size_t n)
  325. {
  326. if (!s || !n)
  327. return NULL;
  328. s = s + n - 1;
  329. while (n) {
  330. if (*s == ch)
  331. return s;
  332. --n, --s;
  333. }
  334. return NULL;
  335. }
  336. /*
  337. * The following dirname(3) implementation does not
  338. * modify the input. We use a copy of the original.
  339. *
  340. * Modified from the glibc (GNU LGPL) version.
  341. */
  342. static char *
  343. xdirname(const char *path)
  344. {
  345. static char *buf = g_buf;
  346. static char *last_slash;
  347. xstrlcpy(buf, path, PATH_MAX);
  348. /* Find last '/'. */
  349. last_slash = xmemrchr((uchar *)buf, '/', strlen(buf));
  350. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  351. /* Determine whether all remaining characters are slashes. */
  352. char *runp;
  353. for (runp = last_slash; runp != buf; --runp)
  354. if (runp[-1] != '/')
  355. break;
  356. /* The '/' is the last character, we have to look further. */
  357. if (runp != buf)
  358. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  359. }
  360. if (last_slash != NULL) {
  361. /* Determine whether all remaining characters are slashes. */
  362. char *runp;
  363. for (runp = last_slash; runp != buf; --runp)
  364. if (runp[-1] != '/')
  365. break;
  366. /* Terminate the buffer. */
  367. if (runp == buf) {
  368. /* The last slash is the first character in the string.
  369. * We have to return "/". As a special case we have to
  370. * return "//" if there are exactly two slashes at the
  371. * beginning of the string. See XBD 4.10 Path Name
  372. * Resolution for more information.
  373. */
  374. if (last_slash == buf + 1)
  375. ++last_slash;
  376. else
  377. last_slash = buf + 1;
  378. } else
  379. last_slash = runp;
  380. last_slash[0] = '\0';
  381. } else {
  382. /* This assignment is ill-designed but the XPG specs require to
  383. * return a string containing "." in any case no directory part
  384. * is found and so a static and constant string is required.
  385. */
  386. buf[0] = '.';
  387. buf[1] = '\0';
  388. }
  389. return buf;
  390. }
  391. /*
  392. * Return number of dots if all chars in a string are dots, else 0
  393. */
  394. static int
  395. all_dots(const char *path)
  396. {
  397. if (!path)
  398. return FALSE;
  399. int count = 0;
  400. while (*path == '.')
  401. ++count, ++path;
  402. if (*path)
  403. return 0;
  404. return count;
  405. }
  406. /* Initialize curses mode */
  407. static void
  408. initcurses(void)
  409. {
  410. if (initscr() == NULL) {
  411. char *term = getenv("TERM");
  412. if (term != NULL)
  413. fprintf(stderr, "error opening TERM: %s\n", term);
  414. else
  415. fprintf(stderr, "initscr() failed\n");
  416. exit(1);
  417. }
  418. cbreak();
  419. noecho();
  420. nonl();
  421. intrflush(stdscr, FALSE);
  422. keypad(stdscr, TRUE);
  423. curs_set(FALSE); /* Hide cursor */
  424. start_color();
  425. use_default_colors();
  426. if (cfg.showcolor)
  427. init_pair(1, color, -1);
  428. timeout(1000); /* One second */
  429. }
  430. /*
  431. * Spawns a child process. Behaviour can be controlled using flag.
  432. * Limited to 2 arguments to a program, flag works on bit set.
  433. */
  434. static void
  435. spawn(char *file, char *arg1, char *arg2, char *dir, uchar flag)
  436. {
  437. pid_t pid;
  438. int status;
  439. if (flag & F_NORMAL)
  440. exitcurses();
  441. pid = fork();
  442. if (pid == 0) {
  443. if (dir != NULL)
  444. status = chdir(dir);
  445. /* Show a marker (to indicate nnn spawned shell) */
  446. if (flag & F_MARKER) {
  447. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  448. printf("Spawned shell level: %d\n", atoi(getenv("SHLVL")) + 1);
  449. }
  450. /* Suppress stdout and stderr */
  451. if (flag & F_NOTRACE) {
  452. int fd = open("/dev/null", O_WRONLY, 0200);
  453. dup2(fd, 1);
  454. dup2(fd, 2);
  455. close(fd);
  456. }
  457. if (flag & F_SIGINT)
  458. signal(SIGINT, SIG_DFL);
  459. execlp(file, file, arg1, arg2, NULL);
  460. _exit(1);
  461. } else {
  462. if (!(flag & F_NOWAIT))
  463. /* Ignore interruptions */
  464. while (waitpid(pid, &status, 0) == -1)
  465. DPRINTF_D(status);
  466. DPRINTF_D(pid);
  467. if (flag & F_NORMAL)
  468. initcurses();
  469. }
  470. }
  471. /* Get program name from env var, else return fallback program */
  472. static char *
  473. xgetenv(char *name, char *fallback)
  474. {
  475. if (name == NULL)
  476. return fallback;
  477. char *value = getenv(name);
  478. return value && value[0] ? value : fallback;
  479. }
  480. /*
  481. * We assume none of the strings are NULL.
  482. *
  483. * Let's have the logic to sort numeric names in numeric order.
  484. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  485. *
  486. * If the absolute numeric values are same, we fallback to alphasort.
  487. */
  488. static int
  489. xstricmp(char *s1, char *s2)
  490. {
  491. static char *c1, *c2;
  492. c1 = s1;
  493. while (isspace(*c1))
  494. ++c1;
  495. if (*c1 == '-' || *c1 == '+')
  496. ++c1;
  497. while (*c1 >= '0' && *c1 <= '9')
  498. ++c1;
  499. c2 = s2;
  500. while (isspace(*c2))
  501. ++c2;
  502. if (*c2 == '-' || *c2 == '+')
  503. ++c2;
  504. while (*c2 >= '0' && *c2 <= '9')
  505. ++c2;
  506. if (*c1 == '\0' && *c2 == '\0') {
  507. static long long num1, num2;
  508. num1 = strtoll(s1, &c1, 10);
  509. num2 = strtoll(s2, &c2, 10);
  510. if (num1 != num2) {
  511. if (num1 > num2)
  512. return 1;
  513. else
  514. return -1;
  515. }
  516. } else if (*c1 == '\0' && *c2 != '\0')
  517. return -1;
  518. else if (*c1 != '\0' && *c2 == '\0')
  519. return 1;
  520. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  521. ++s1, ++s2;
  522. /* In case of alphabetically same names, make sure
  523. * lower case one comes before upper case one
  524. */
  525. if (!*s1 && !*s2)
  526. return 1;
  527. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  528. }
  529. /* Return the integer value of a char representing HEX */
  530. static char
  531. xchartohex(char c)
  532. {
  533. if (c >= '0' && c <= '9')
  534. return c - '0';
  535. c = TOUPPER(c);
  536. if (c >= 'A' && c <= 'F')
  537. return c - 'A' + 10;
  538. return c;
  539. }
  540. /* Trim all whitespace from both ends, / from end */
  541. static char *
  542. strstrip(char *s)
  543. {
  544. if (!s || !*s)
  545. return s;
  546. size_t len = xstrlen(s) - 1;
  547. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  548. --len;
  549. s[len + 1] = '\0';
  550. while (*s && isspace(*s))
  551. ++s;
  552. return s;
  553. }
  554. static char *
  555. getmime(char *file)
  556. {
  557. regex_t regex;
  558. uint i;
  559. static uint len = LEN(assocs);
  560. for (i = 0; i < len; ++i) {
  561. if (regcomp(&regex, assocs[i].regex, REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  562. continue;
  563. if (regexec(&regex, file, 0, NULL, 0) == 0)
  564. return assocs[i].mime;
  565. }
  566. return NULL;
  567. }
  568. static int
  569. setfilter(regex_t *regex, char *filter)
  570. {
  571. static size_t len;
  572. static int r;
  573. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  574. if (r != 0 && filter && filter[0] != '\0') {
  575. len = COLS;
  576. if (len > LINE_MAX)
  577. len = LINE_MAX;
  578. regerror(r, regex, g_buf, len);
  579. printmsg(g_buf);
  580. }
  581. return r;
  582. }
  583. static void
  584. initfilter(int dot, char **ifilter)
  585. {
  586. *ifilter = dot ? "." : "^[^.]";
  587. }
  588. static int
  589. visible(regex_t *regex, char *file)
  590. {
  591. return regexec(regex, file, 0, NULL, 0) == 0;
  592. }
  593. static int
  594. entrycmp(const void *va, const void *vb)
  595. {
  596. static pEntry pa, pb;
  597. pa = (pEntry)va;
  598. pb = (pEntry)vb;
  599. /* Sort directories first */
  600. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  601. return 1;
  602. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  603. return -1;
  604. /* Do the actual sorting */
  605. if (cfg.mtimeorder)
  606. return pb->t - pa->t;
  607. if (cfg.sizeorder) {
  608. if (pb->size > pa->size)
  609. return 1;
  610. else if (pb->size < pa->size)
  611. return -1;
  612. }
  613. if (cfg.blkorder) {
  614. if (pb->blocks > pa->blocks)
  615. return 1;
  616. else if (pb->blocks < pa->blocks)
  617. return -1;
  618. }
  619. return xstricmp(pa->name, pb->name);
  620. }
  621. /* Messages show up at the bottom */
  622. static void
  623. printmsg(char *msg)
  624. {
  625. mvprintw(LINES - 1, 0, "%s\n", msg);
  626. }
  627. /* Kill curses and display error before exiting */
  628. static void
  629. printerr(int ret, char *prefix)
  630. {
  631. exitcurses();
  632. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  633. exit(ret);
  634. }
  635. /* Print prompt on the last line */
  636. static void
  637. printprompt(char *str)
  638. {
  639. clearprompt();
  640. printw(str);
  641. }
  642. /*
  643. * Returns SEL_* if key is bound and 0 otherwise.
  644. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  645. * The next keyboard input can be simulated by presel.
  646. */
  647. static int
  648. nextsel(char **run, char **env, int *presel)
  649. {
  650. static int c;
  651. static uchar i;
  652. static uint len = LEN(bindings);
  653. #ifdef LINUX_INOTIFY
  654. static char inotify_buf[EVENT_BUF_LEN];
  655. #elif defined(BSD_KQUEUE)
  656. static struct kevent event_data[NUM_EVENT_SLOTS];
  657. #endif
  658. c = *presel;
  659. if (c == 0)
  660. c = getch();
  661. else {
  662. *presel = 0;
  663. /* Unwatch dir if we are still in a filtered view */
  664. #ifdef LINUX_INOTIFY
  665. if (inotify_wd >= 0) {
  666. inotify_rm_watch(inotify_fd, inotify_wd);
  667. inotify_wd = -1;
  668. }
  669. #elif defined(BSD_KQUEUE)
  670. if (event_fd >= 0) {
  671. close(event_fd);
  672. event_fd = -1;
  673. }
  674. #endif
  675. }
  676. if (c == -1) {
  677. ++idle;
  678. /* Do not check for directory changes in du
  679. * mode. A redraw forces du calculation.
  680. * Check for changes every odd second.
  681. */
  682. #ifdef LINUX_INOTIFY
  683. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1 && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  684. #elif defined(BSD_KQUEUE)
  685. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  686. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS, event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  687. #endif
  688. c = CONTROL('L');
  689. } else
  690. idle = 0;
  691. for (i = 0; i < len; ++i)
  692. if (c == bindings[i].sym) {
  693. *run = bindings[i].run;
  694. *env = bindings[i].env;
  695. return bindings[i].act;
  696. }
  697. return 0;
  698. }
  699. /*
  700. * Move non-matching entries to the end
  701. */
  702. static void
  703. fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  704. {
  705. static int count;
  706. for (count = 0; count < ndents; ++count) {
  707. if (filter(re, (*dents)[count].name) == 0) {
  708. if (count != --ndents) {
  709. static struct entry _dent, *dentp1, *dentp2;
  710. dentp1 = &(*dents)[count];
  711. dentp2 = &(*dents)[ndents];
  712. /* Copy count to tmp */
  713. xstrlcpy(_dent.name, dentp1->name, NAME_MAX);
  714. _dent.mode = dentp1->mode;
  715. _dent.t = dentp1->t;
  716. _dent.size = dentp1->size;
  717. _dent.blocks = dentp1->blocks;
  718. /* Copy ndents - 1 to count */
  719. xstrlcpy(dentp1->name, dentp2->name, NAME_MAX);
  720. dentp1->mode = dentp2->mode;
  721. dentp1->t = dentp2->t;
  722. dentp1->size = dentp2->size;
  723. dentp1->blocks = dentp2->blocks;
  724. /* Copy tmp to ndents - 1 */
  725. xstrlcpy(dentp2->name, _dent.name, NAME_MAX);
  726. dentp2->mode = _dent.mode;
  727. dentp2->t = _dent.t;
  728. dentp2->size = _dent.size;
  729. dentp2->blocks = _dent.blocks;
  730. --count;
  731. }
  732. continue;
  733. }
  734. }
  735. }
  736. static int
  737. matches(char *fltr)
  738. {
  739. static regex_t re;
  740. /* Search filter */
  741. if (setfilter(&re, fltr) != 0)
  742. return -1;
  743. fill(&dents, visible, &re);
  744. qsort(dents, ndents, sizeof(*dents), entrycmp);
  745. return 0;
  746. }
  747. static int
  748. readln(char *path)
  749. {
  750. static char ln[LINE_MAX << 2];
  751. static wchar_t wln[LINE_MAX];
  752. static wint_t ch[2] = {0};
  753. int r, total = ndents;
  754. int oldcur = cur;
  755. int len = 1;
  756. char *pln = ln + 1;
  757. memset(wln, 0, LINE_MAX << 2);
  758. wln[0] = FILTER;
  759. ln[0] = FILTER;
  760. ln[1] = '\0';
  761. cur = 0;
  762. timeout(-1);
  763. echo();
  764. curs_set(TRUE);
  765. printprompt(ln);
  766. while ((r = wget_wch(stdscr, ch)) != ERR)
  767. if (r == OK)
  768. switch (*ch) {
  769. case '\r': // with nonl(), this is ENTER key value
  770. if (len == 1) {
  771. cur = oldcur;
  772. goto end;
  773. }
  774. if (matches(pln) == -1)
  775. goto end;
  776. redraw(path);
  777. goto end;
  778. case 127: // handle DEL
  779. if (len == 1) {
  780. cur = oldcur;
  781. *ch = CONTROL('L');
  782. goto end;
  783. }
  784. wln[--len] = '\0';
  785. if (len == 1)
  786. cur = oldcur;
  787. wcstombs(ln, wln, LINE_MAX << 2);
  788. ndents = total;
  789. if (matches(pln) == -1) {
  790. printprompt(ln);
  791. continue;
  792. }
  793. redraw(path);
  794. printprompt(ln);
  795. break;
  796. case CONTROL('L'):
  797. if (len == 1)
  798. cur = oldcur; // fallthrough
  799. case CONTROL('Q'):
  800. goto end;
  801. default:
  802. /* Reset cur in case it's a repeat search */
  803. if (len == 1)
  804. cur = 0;
  805. wln[len] = (wchar_t)*ch;
  806. wln[++len] = '\0';
  807. wcstombs(ln, wln, LINE_MAX << 2);
  808. ndents = total;
  809. if (matches(pln) == -1)
  810. continue;
  811. redraw(path);
  812. printprompt(ln);
  813. }
  814. else
  815. switch (*ch) {
  816. case KEY_DC: // fallthrough
  817. case KEY_BACKSPACE:
  818. if (len == 1) {
  819. cur = oldcur;
  820. *ch = CONTROL('L');
  821. goto end;
  822. }
  823. wln[--len] = '\0';
  824. if (len == 1)
  825. cur = oldcur;
  826. wcstombs(ln, wln, LINE_MAX << 2);
  827. ndents = total;
  828. if (matches(pln) == -1)
  829. continue;
  830. redraw(path);
  831. printprompt(ln);
  832. break;
  833. default:
  834. if (len == 1)
  835. cur = oldcur;
  836. goto end;
  837. }
  838. end:
  839. noecho();
  840. curs_set(FALSE);
  841. timeout(1000);
  842. /* Return keys for navigation etc. */
  843. return *ch;
  844. }
  845. /*
  846. * Returns "dir/name or "/name"
  847. */
  848. static char *
  849. mkpath(char *dir, char *name, char *out, size_t n)
  850. {
  851. /* Handle absolute path */
  852. if (name[0] == '/')
  853. xstrlcpy(out, name, n);
  854. else {
  855. /* Handle root case */
  856. if (istopdir(dir))
  857. snprintf(out, n, "/%s", name);
  858. else
  859. snprintf(out, n, "%s/%s", dir, name);
  860. }
  861. return out;
  862. }
  863. static void
  864. parsebmstr(char *bms)
  865. {
  866. int i = 0;
  867. while (*bms && i < MAX_BM) {
  868. bookmark[i].key = bms;
  869. ++bms;
  870. while (*bms && *bms != ':')
  871. ++bms;
  872. if (!*bms) {
  873. bookmark[i].key = NULL;
  874. break;
  875. }
  876. *bms = '\0';
  877. bookmark[i].loc = ++bms;
  878. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  879. bookmark[i].key = NULL;
  880. break;
  881. }
  882. while (*bms && *bms != ';')
  883. ++bms;
  884. if (*bms)
  885. *bms = '\0';
  886. else
  887. break;
  888. ++bms;
  889. ++i;
  890. }
  891. }
  892. static char *
  893. readinput(void)
  894. {
  895. timeout(-1);
  896. echo();
  897. curs_set(TRUE);
  898. memset(g_buf, 0, LINE_MAX);
  899. wgetnstr(stdscr, g_buf, LINE_MAX - 1);
  900. noecho();
  901. curs_set(FALSE);
  902. timeout(1000);
  903. return g_buf[0] ? g_buf : NULL;
  904. }
  905. /*
  906. * Replace escape characters in a string with '?'
  907. */
  908. static char *
  909. unescape(const char *str)
  910. {
  911. static char buffer[PATH_MAX];
  912. static wchar_t wbuf[PATH_MAX];
  913. static wchar_t *buf;
  914. buffer[0] = '\0';
  915. buf = wbuf;
  916. /* Convert multi-byte to wide char */
  917. mbstowcs(wbuf, str, PATH_MAX);
  918. while (*buf) {
  919. if (*buf <= '\x1f' || *buf == '\x7f')
  920. *buf = '\?';
  921. ++buf;
  922. }
  923. /* Convert wide char to multi-byte */
  924. wcstombs(buffer, wbuf, PATH_MAX);
  925. return buffer;
  926. }
  927. static void
  928. printent(struct entry *ent, int sel)
  929. {
  930. static int ncols;
  931. if (PATH_MAX + 16 < COLS)
  932. ncols = PATH_MAX + 16;
  933. else
  934. ncols = COLS;
  935. if (S_ISDIR(ent->mode))
  936. snprintf(g_buf, ncols, "%s%s/", CURSYM(sel), unescape(ent->name));
  937. else if (S_ISLNK(ent->mode))
  938. snprintf(g_buf, ncols, "%s%s@", CURSYM(sel), unescape(ent->name));
  939. else if (S_ISSOCK(ent->mode))
  940. snprintf(g_buf, ncols, "%s%s=", CURSYM(sel), unescape(ent->name));
  941. else if (S_ISFIFO(ent->mode))
  942. snprintf(g_buf, ncols, "%s%s|", CURSYM(sel), unescape(ent->name));
  943. else if (ent->mode & 0100)
  944. snprintf(g_buf, ncols, "%s%s*", CURSYM(sel), unescape(ent->name));
  945. else
  946. snprintf(g_buf, ncols, "%s%s", CURSYM(sel), unescape(ent->name));
  947. /* Dirs are always shown on top */
  948. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  949. attroff(COLOR_PAIR(1) | A_BOLD);
  950. cfg.dircolor = 0;
  951. }
  952. printw("%s\n", g_buf);
  953. }
  954. static char *
  955. coolsize(off_t size)
  956. {
  957. static const char * const U = "BKMGTPEZY";
  958. static char size_buf[12]; /* Buffer to hold human readable size */
  959. static int i;
  960. static off_t tmp;
  961. static long double rem;
  962. i = 0;
  963. rem = 0;
  964. while (size > 1024) {
  965. tmp = size;
  966. size >>= 10;
  967. rem = tmp - (size << 10);
  968. ++i;
  969. }
  970. snprintf(size_buf, 12, "%.*Lf%c", i, size + rem * div_2_pow_10, U[i]);
  971. return size_buf;
  972. }
  973. static void
  974. printent_long(struct entry *ent, int sel)
  975. {
  976. static int ncols;
  977. static char buf[18];
  978. if (PATH_MAX + 32 < COLS)
  979. ncols = PATH_MAX + 32;
  980. else
  981. ncols = COLS;
  982. strftime(buf, 18, "%d-%m-%Y %H:%M", localtime(&ent->t));
  983. if (sel)
  984. attron(A_REVERSE);
  985. if (!cfg.blkorder) {
  986. if (S_ISDIR(ent->mode))
  987. snprintf(g_buf, ncols, "%s%-16.16s / %s/", CURSYM(sel), buf, unescape(ent->name));
  988. else if (S_ISLNK(ent->mode))
  989. snprintf(g_buf, ncols, "%s%-16.16s @ %s@", CURSYM(sel), buf, unescape(ent->name));
  990. else if (S_ISSOCK(ent->mode))
  991. snprintf(g_buf, ncols, "%s%-16.16s = %s=", CURSYM(sel), buf, unescape(ent->name));
  992. else if (S_ISFIFO(ent->mode))
  993. snprintf(g_buf, ncols, "%s%-16.16s | %s|", CURSYM(sel), buf, unescape(ent->name));
  994. else if (S_ISBLK(ent->mode))
  995. snprintf(g_buf, ncols, "%s%-16.16s b %s", CURSYM(sel), buf, unescape(ent->name));
  996. else if (S_ISCHR(ent->mode))
  997. snprintf(g_buf, ncols, "%s%-16.16s c %s", CURSYM(sel), buf, unescape(ent->name));
  998. else if (ent->mode & 0100)
  999. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*", CURSYM(sel), buf, coolsize(ent->size), unescape(ent->name));
  1000. else
  1001. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s", CURSYM(sel), buf, coolsize(ent->size), unescape(ent->name));
  1002. } else {
  1003. if (S_ISDIR(ent->mode))
  1004. snprintf(g_buf, ncols, "%s%-16.16s %8.8s/ %s/", CURSYM(sel), buf, coolsize(ent->blocks << 9), unescape(ent->name));
  1005. else if (S_ISLNK(ent->mode))
  1006. snprintf(g_buf, ncols, "%s%-16.16s @ %s@", CURSYM(sel), buf, unescape(ent->name));
  1007. else if (S_ISSOCK(ent->mode))
  1008. snprintf(g_buf, ncols, "%s%-16.16s = %s=", CURSYM(sel), buf, unescape(ent->name));
  1009. else if (S_ISFIFO(ent->mode))
  1010. snprintf(g_buf, ncols, "%s%-16.16s | %s|", CURSYM(sel), buf, unescape(ent->name));
  1011. else if (S_ISBLK(ent->mode))
  1012. snprintf(g_buf, ncols, "%s%-16.16s b %s", CURSYM(sel), buf, unescape(ent->name));
  1013. else if (S_ISCHR(ent->mode))
  1014. snprintf(g_buf, ncols, "%s%-16.16s c %s", CURSYM(sel), buf, unescape(ent->name));
  1015. else if (ent->mode & 0100)
  1016. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*", CURSYM(sel), buf, coolsize(ent->blocks << 9), unescape(ent->name));
  1017. else
  1018. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s", CURSYM(sel), buf, coolsize(ent->blocks << 9), unescape(ent->name));
  1019. }
  1020. /* Dirs are always shown on top */
  1021. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  1022. attroff(COLOR_PAIR(1) | A_BOLD);
  1023. cfg.dircolor = 0;
  1024. }
  1025. printw("%s\n", g_buf);
  1026. if (sel)
  1027. attroff(A_REVERSE);
  1028. }
  1029. static void (*printptr)(struct entry *ent, int sel) = &printent_long;
  1030. static char
  1031. get_fileind(mode_t mode, char *desc)
  1032. {
  1033. static char c;
  1034. if (S_ISREG(mode)) {
  1035. c = '-';
  1036. sprintf(desc, "%s", "regular file");
  1037. if (mode & 0100)
  1038. strcat(desc, ", executable");
  1039. } else if (S_ISDIR(mode)) {
  1040. c = 'd';
  1041. sprintf(desc, "%s", "directory");
  1042. } else if (S_ISBLK(mode)) {
  1043. c = 'b';
  1044. sprintf(desc, "%s", "block special device");
  1045. } else if (S_ISCHR(mode)) {
  1046. c = 'c';
  1047. sprintf(desc, "%s", "character special device");
  1048. #ifdef S_ISFIFO
  1049. } else if (S_ISFIFO(mode)) {
  1050. c = 'p';
  1051. sprintf(desc, "%s", "FIFO");
  1052. #endif /* S_ISFIFO */
  1053. #ifdef S_ISLNK
  1054. } else if (S_ISLNK(mode)) {
  1055. c = 'l';
  1056. sprintf(desc, "%s", "symbolic link");
  1057. #endif /* S_ISLNK */
  1058. #ifdef S_ISSOCK
  1059. } else if (S_ISSOCK(mode)) {
  1060. c = 's';
  1061. sprintf(desc, "%s", "socket");
  1062. #endif /* S_ISSOCK */
  1063. #ifdef S_ISDOOR
  1064. /* Solaris 2.6, etc. */
  1065. } else if (S_ISDOOR(mode)) {
  1066. c = 'D';
  1067. desc[0] = '\0';
  1068. #endif /* S_ISDOOR */
  1069. } else {
  1070. /* Unknown type -- possibly a regular file? */
  1071. c = '?';
  1072. desc[0] = '\0';
  1073. }
  1074. return c;
  1075. }
  1076. /* Convert a mode field into "ls -l" type perms field. */
  1077. static char *
  1078. get_lsperms(mode_t mode, char *desc)
  1079. {
  1080. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1081. static char bits[11];
  1082. bits[0] = get_fileind(mode, desc);
  1083. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  1084. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  1085. strcpy(&bits[7], rwx[(mode & 7)]);
  1086. if (mode & S_ISUID)
  1087. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1088. if (mode & S_ISGID)
  1089. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1090. if (mode & S_ISVTX)
  1091. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1092. bits[10] = '\0';
  1093. return bits;
  1094. }
  1095. /*
  1096. * Gets only a single line (that's what we need
  1097. * for now) or shows full command output in pager.
  1098. *
  1099. * If pager is valid, returns NULL
  1100. */
  1101. static char *
  1102. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2,
  1103. int pager)
  1104. {
  1105. pid_t pid;
  1106. int pipefd[2];
  1107. FILE *pf;
  1108. int tmp, flags;
  1109. char *ret = NULL;
  1110. if (pipe(pipefd) == -1)
  1111. printerr(1, "pipe(2)");
  1112. for (tmp = 0; tmp < 2; ++tmp) {
  1113. /* Get previous flags */
  1114. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1115. /* Set bit for non-blocking flag */
  1116. flags |= O_NONBLOCK;
  1117. /* Change flags on fd */
  1118. fcntl(pipefd[tmp], F_SETFL, flags);
  1119. }
  1120. pid = fork();
  1121. if (pid == 0) {
  1122. /* In child */
  1123. close(pipefd[0]);
  1124. dup2(pipefd[1], STDOUT_FILENO);
  1125. dup2(pipefd[1], STDERR_FILENO);
  1126. close(pipefd[1]);
  1127. execlp(file, file, arg1, arg2, NULL);
  1128. _exit(1);
  1129. }
  1130. /* In parent */
  1131. waitpid(pid, &tmp, 0);
  1132. close(pipefd[1]);
  1133. if (!pager) {
  1134. pf = fdopen(pipefd[0], "r");
  1135. if (pf) {
  1136. ret = fgets(buf, bytes, pf);
  1137. close(pipefd[0]);
  1138. }
  1139. return ret;
  1140. }
  1141. pid = fork();
  1142. if (pid == 0) {
  1143. /* Show in pager in child */
  1144. dup2(pipefd[0], STDIN_FILENO);
  1145. close(pipefd[0]);
  1146. execlp("less", "less", NULL);
  1147. _exit(1);
  1148. }
  1149. /* In parent */
  1150. waitpid(pid, &tmp, 0);
  1151. close(pipefd[0]);
  1152. return NULL;
  1153. }
  1154. /*
  1155. * Follows the stat(1) output closely
  1156. */
  1157. static int
  1158. show_stats(char *fpath, char *fname, struct stat *sb)
  1159. {
  1160. char *perms = get_lsperms(sb->st_mode, g_buf);
  1161. char *p, *begin = g_buf;
  1162. char tmp[] = "/tmp/nnnXXXXXX";
  1163. int fd = mkstemp(tmp);
  1164. if (fd == -1)
  1165. return -1;
  1166. /* Show file name or 'symlink' -> 'target' */
  1167. if (perms[0] == 'l') {
  1168. /* Note that MAX_CMD_LEN > PATH_MAX */
  1169. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1170. if (len != -1) {
  1171. g_buf[len] = '\0';
  1172. dprintf(fd, " File: '%s' -> ", unescape(fname));
  1173. dprintf(fd, "'%s'", unescape(g_buf));
  1174. xstrlcpy(g_buf, "symbolic link", MAX_CMD_LEN);
  1175. }
  1176. } else
  1177. dprintf(fd, " File: '%s'", unescape(fname));
  1178. /* Show size, blocks, file type */
  1179. #ifdef __APPLE__
  1180. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1181. #else
  1182. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1183. #endif
  1184. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1185. /* Show containing device, inode, hardlink count */
  1186. #ifdef __APPLE__
  1187. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1188. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1189. #else
  1190. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1191. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1192. #endif
  1193. g_buf, sb->st_ino, sb->st_nlink);
  1194. /* Show major, minor number for block or char device */
  1195. if (perms[0] == 'b' || perms[0] == 'c')
  1196. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1197. /* Show permissions, owner, group */
  1198. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)", (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7,
  1199. sb->st_mode & 7, perms, sb->st_uid, (getpwuid(sb->st_uid))->pw_name, sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1200. /* Show last access time */
  1201. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1202. dprintf(fd, "\n\n Access: %s", g_buf);
  1203. /* Show last modification time */
  1204. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1205. dprintf(fd, "\n Modify: %s", g_buf);
  1206. /* Show last status change time */
  1207. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1208. dprintf(fd, "\n Change: %s", g_buf);
  1209. if (S_ISREG(sb->st_mode)) {
  1210. /* Show file(1) output */
  1211. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1212. if (p) {
  1213. dprintf(fd, "\n\n ");
  1214. while (*p) {
  1215. if (*p == ',') {
  1216. *p = '\0';
  1217. dprintf(fd, " %s\n", begin);
  1218. begin = p + 1;
  1219. }
  1220. ++p;
  1221. }
  1222. dprintf(fd, " %s", begin);
  1223. }
  1224. dprintf(fd, "\n\n");
  1225. } else
  1226. dprintf(fd, "\n\n\n");
  1227. close(fd);
  1228. exitcurses();
  1229. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1230. unlink(tmp);
  1231. initcurses();
  1232. return 0;
  1233. }
  1234. static int
  1235. getorder(size_t size)
  1236. {
  1237. switch (size) {
  1238. case 4096:
  1239. return 12;
  1240. case 512:
  1241. return 9;
  1242. case 8192:
  1243. return 13;
  1244. case 16384:
  1245. return 14;
  1246. case 32768:
  1247. return 15;
  1248. case 65536:
  1249. return 16;
  1250. case 131072:
  1251. return 17;
  1252. case 262144:
  1253. return 18;
  1254. case 524288:
  1255. return 19;
  1256. case 1048576:
  1257. return 20;
  1258. case 2048:
  1259. return 11;
  1260. case 1024:
  1261. return 10;
  1262. default:
  1263. return 0;
  1264. }
  1265. }
  1266. static void
  1267. update_fs_free(char *path)
  1268. {
  1269. static struct statvfs svb;
  1270. if (statvfs(path, &svb) == -1)
  1271. fs_free = 0;
  1272. else
  1273. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1274. }
  1275. static int
  1276. show_mediainfo(char *fpath, char *arg)
  1277. {
  1278. if (!get_output(g_buf, MAX_CMD_LEN, "which", metaviewer, NULL, 0))
  1279. return -1;
  1280. exitcurses();
  1281. get_output(NULL, 0, metaviewer, fpath, arg, 1);
  1282. initcurses();
  1283. return 0;
  1284. }
  1285. /*
  1286. * The help string tokens (each line) start with a HEX value
  1287. * which indicates the number of spaces to print before the
  1288. * particular token. This method was chosen instead of a flat
  1289. * string because the number of bytes in help was increasing
  1290. * the binary size by around a hundred bytes. This would only
  1291. * have increased as we keep adding new options.
  1292. */
  1293. static int
  1294. show_help(char *path)
  1295. {
  1296. char tmp[] = "/tmp/nnnXXXXXX";
  1297. int i = 0, fd = mkstemp(tmp);
  1298. char *start, *end;
  1299. static char helpstr[] = (
  1300. "cKey | Function\n"
  1301. "e- + -\n"
  1302. "7↑, k, ^P | Previous entry\n"
  1303. "7↓, j, ^N | Next entry\n"
  1304. "7PgUp, ^U | Scroll half page up\n"
  1305. "7PgDn, ^D | Scroll half page down\n"
  1306. "1Home, g, ^, ^A | Jump to first entry\n"
  1307. "2End, G, $, ^E | Jump to last entry\n"
  1308. "4→, ↵, l, ^M | Open file or enter dir\n"
  1309. "1←, Bksp, h, ^H | Go to parent dir\n"
  1310. "9Insert | Toggle navigate-as-you-type\n"
  1311. "e~ | Jump to HOME dir\n"
  1312. "e& | Jump to initial dir\n"
  1313. "e- | Jump to last visited dir\n"
  1314. "e/ | Filter dir contents\n"
  1315. "d^/ | Open desktop search tool\n"
  1316. "e. | Toggle hide .dot files\n"
  1317. "eb | Show bookmark key prompt\n"
  1318. "d^B | Mark current dir\n"
  1319. "d^V | Visit marked dir\n"
  1320. "ec | Show change dir prompt\n"
  1321. "ed | Toggle detail view\n"
  1322. "eD | Show current file details\n"
  1323. "em | Show concise media info\n"
  1324. "eM | Show full media info\n"
  1325. "d^R | Rename selected entry\n"
  1326. "es | Toggle sort by file size\n"
  1327. "eS | Toggle disk usage mode\n"
  1328. "et | Toggle sort by mtime\n"
  1329. "e! | Spawn SHELL in current dir\n"
  1330. "ee | Edit entry in EDITOR\n"
  1331. "eo | Open dir in file manager\n"
  1332. "ep | Open entry in PAGER\n"
  1333. "d^K | Invoke file path copier\n"
  1334. "d^L | Force a redraw, unfilter\n"
  1335. "e? | Show help, settings\n"
  1336. "eQ | Quit and change dir\n"
  1337. "aq, ^Q | Quit\n\n");
  1338. if (fd == -1)
  1339. return -1;
  1340. start = end = helpstr;
  1341. while (*end) {
  1342. while (*end != '\n')
  1343. ++end;
  1344. if (start == end) {
  1345. ++end;
  1346. continue;
  1347. }
  1348. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1349. start = ++end;
  1350. }
  1351. dprintf(fd, "\n");
  1352. if (getenv("NNN_BMS")) {
  1353. dprintf(fd, "BOOKMARKS\n");
  1354. for (; i < MAX_BM; ++i)
  1355. if (bookmark[i].key)
  1356. dprintf(fd, " %s: %s\n",
  1357. bookmark[i].key, bookmark[i].loc);
  1358. else
  1359. break;
  1360. dprintf(fd, "\n");
  1361. }
  1362. if (editor)
  1363. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1364. if (desktop_manager)
  1365. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1366. if (idletimeout)
  1367. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1368. if (copier)
  1369. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1370. update_fs_free(path);
  1371. dprintf(fd, "\nVolume: %s free\n", coolsize(fs_free));
  1372. dprintf(fd, "\n");
  1373. close(fd);
  1374. exitcurses();
  1375. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1376. unlink(tmp);
  1377. initcurses();
  1378. return 0;
  1379. }
  1380. static int
  1381. sum_bsizes(const char *fpath, const struct stat *sb,
  1382. int typeflag, struct FTW *ftwbuf)
  1383. {
  1384. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1385. ent_blocks += sb->st_blocks;
  1386. ++num_files;
  1387. return 0;
  1388. }
  1389. static int
  1390. dentfill(char *path, struct entry **dents,
  1391. int (*filter)(regex_t *, char *), regex_t *re)
  1392. {
  1393. static DIR *dirp;
  1394. static struct dirent *dp;
  1395. static struct stat sb_path, sb;
  1396. static int fd, n;
  1397. static char *namep;
  1398. static ulong num_saved;
  1399. static struct entry *dentp;
  1400. dirp = opendir(path);
  1401. if (dirp == NULL)
  1402. return 0;
  1403. fd = dirfd(dirp);
  1404. n = 0;
  1405. if (cfg.blkorder) {
  1406. num_files = 0;
  1407. dir_blocks = 0;
  1408. update_fs_free(path);
  1409. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1410. printwarn();
  1411. return 0;
  1412. }
  1413. }
  1414. while ((dp = readdir(dirp)) != NULL) {
  1415. namep = dp->d_name;
  1416. if (filter(re, namep) == 0) {
  1417. if (!cfg.blkorder)
  1418. continue;
  1419. /* Skip self and parent */
  1420. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1421. continue;
  1422. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW)
  1423. == -1)
  1424. continue;
  1425. if (S_ISDIR(sb.st_mode)) {
  1426. if (sb_path.st_dev == sb.st_dev) {
  1427. ent_blocks = 0;
  1428. mkpath(path, namep, g_buf, PATH_MAX);
  1429. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1430. printmsg(STR_NFTWFAIL);
  1431. dir_blocks += sb.st_blocks;
  1432. } else
  1433. dir_blocks += ent_blocks;
  1434. }
  1435. } else {
  1436. if (sb.st_blocks)
  1437. dir_blocks += sb.st_blocks;
  1438. ++num_files;
  1439. }
  1440. continue;
  1441. }
  1442. /* Skip self and parent */
  1443. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1444. (namep[1] == '.' && namep[2] == '\0'))))
  1445. continue;
  1446. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1447. if (*dents)
  1448. free(*dents);
  1449. printerr(1, "fstatat");
  1450. }
  1451. if (n == total_dents) {
  1452. total_dents += 64;
  1453. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1454. if (*dents == NULL)
  1455. printerr(1, "realloc");
  1456. }
  1457. dentp = &(*dents)[n];
  1458. xstrlcpy(dentp->name, namep, NAME_MAX);
  1459. dentp->mode = sb.st_mode;
  1460. dentp->t = sb.st_mtime;
  1461. dentp->size = sb.st_size;
  1462. if (cfg.blkorder) {
  1463. if (S_ISDIR(sb.st_mode)) {
  1464. ent_blocks = 0;
  1465. num_saved = num_files + 1;
  1466. mkpath(path, namep, g_buf, PATH_MAX);
  1467. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1468. printmsg(STR_NFTWFAIL);
  1469. dentp->blocks = sb.st_blocks;
  1470. } else
  1471. dentp->blocks = ent_blocks;
  1472. if (sb_path.st_dev == sb.st_dev)
  1473. dir_blocks += dentp->blocks;
  1474. else
  1475. num_files = num_saved;
  1476. } else {
  1477. dentp->blocks = sb.st_blocks;
  1478. dir_blocks += dentp->blocks;
  1479. ++num_files;
  1480. }
  1481. }
  1482. ++n;
  1483. }
  1484. /* Should never be null */
  1485. if (closedir(dirp) == -1) {
  1486. if (*dents)
  1487. free(*dents);
  1488. printerr(1, "closedir");
  1489. }
  1490. return n;
  1491. }
  1492. static void
  1493. dentfree(struct entry *dents)
  1494. {
  1495. free(dents);
  1496. }
  1497. /* Return the position of the matching entry or 0 otherwise */
  1498. static int
  1499. dentfind(struct entry *dents, int n, char *path)
  1500. {
  1501. if (!path)
  1502. return 0;
  1503. static int i;
  1504. static char *p;
  1505. p = basename(path);
  1506. DPRINTF_S(p);
  1507. for (i = 0; i < n; ++i)
  1508. if (xstrcmp(p, dents[i].name) == 0)
  1509. return i;
  1510. return 0;
  1511. }
  1512. static int
  1513. populate(char *path, char *oldpath, char *fltr)
  1514. {
  1515. static regex_t re;
  1516. /* Can fail when permissions change while browsing */
  1517. if (access(path, R_OK) == -1)
  1518. return -1;
  1519. /* Search filter */
  1520. if (setfilter(&re, fltr) != 0)
  1521. return -1;
  1522. if (cfg.blkorder) {
  1523. printmsg("Calculating...");
  1524. refresh();
  1525. }
  1526. ndents = dentfill(path, &dents, visible, &re);
  1527. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1528. /* Find cur from history */
  1529. cur = dentfind(dents, ndents, oldpath);
  1530. return 0;
  1531. }
  1532. static void
  1533. redraw(char *path)
  1534. {
  1535. static int nlines, i;
  1536. static size_t ncols;
  1537. nlines = MIN(LINES - 4, ndents);
  1538. /* Clean screen */
  1539. erase();
  1540. /* Strip trailing slashes */
  1541. for (i = xstrlen(path) - 1; i > 0; --i)
  1542. if (path[i] == '/')
  1543. path[i] = '\0';
  1544. else
  1545. break;
  1546. DPRINTF_D(cur);
  1547. DPRINTF_S(path);
  1548. /* No text wrapping in cwd line */
  1549. if (!realpath(path, g_buf)) {
  1550. printwarn();
  1551. return;
  1552. }
  1553. ncols = COLS;
  1554. if (ncols > PATH_MAX)
  1555. ncols = PATH_MAX;
  1556. /* - xstrlen(CWD) - 1 = 6 */
  1557. g_buf[ncols - 6] = '\0';
  1558. printw(CWD "%s\n\n", g_buf);
  1559. if (cfg.showcolor) {
  1560. attron(COLOR_PAIR(1) | A_BOLD);
  1561. cfg.dircolor = 1;
  1562. }
  1563. /* Print listing */
  1564. if (cur < (nlines >> 1)) {
  1565. for (i = 0; i < nlines; ++i)
  1566. printptr(&dents[i], i == cur);
  1567. } else if (cur >= ndents - (nlines >> 1)) {
  1568. for (i = ndents - nlines; i < ndents; ++i)
  1569. printptr(&dents[i], i == cur);
  1570. } else {
  1571. static int odd;
  1572. odd = ISODD(nlines);
  1573. nlines >>= 1;
  1574. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1575. printptr(&dents[i], i == cur);
  1576. }
  1577. /* Must reset e.g. no files in dir */
  1578. if (cfg.dircolor) {
  1579. attroff(COLOR_PAIR(1) | A_BOLD);
  1580. cfg.dircolor = 0;
  1581. }
  1582. if (cfg.showdetail) {
  1583. if (ndents) {
  1584. static char ind[2] = "\0\0";
  1585. static char sort[9];
  1586. if (cfg.mtimeorder)
  1587. sprintf(sort, "by time ");
  1588. else if (cfg.sizeorder)
  1589. sprintf(sort, "by size ");
  1590. else
  1591. sort[0] = '\0';
  1592. if (S_ISDIR(dents[cur].mode))
  1593. ind[0] = '/';
  1594. else if (S_ISLNK(dents[cur].mode))
  1595. ind[0] = '@';
  1596. else if (S_ISSOCK(dents[cur].mode))
  1597. ind[0] = '=';
  1598. else if (S_ISFIFO(dents[cur].mode))
  1599. ind[0] = '|';
  1600. else if (dents[cur].mode & 0100)
  1601. ind[0] = '*';
  1602. else
  1603. ind[0] = '\0';
  1604. /* We need to show filename as it may
  1605. * be truncated in directory listing
  1606. */
  1607. if (!cfg.blkorder)
  1608. sprintf(g_buf, "total %d %s[%s%s]", ndents, sort, unescape(dents[cur].name), ind);
  1609. else {
  1610. i = sprintf(g_buf, "du: %s (%lu files) ", coolsize(dir_blocks << 9), num_files);
  1611. sprintf(g_buf + i, "vol: %s free [%s%s]", coolsize(fs_free), unescape(dents[cur].name), ind);
  1612. }
  1613. printmsg(g_buf);
  1614. } else
  1615. printmsg("0 items");
  1616. }
  1617. }
  1618. static void
  1619. browse(char *ipath, char *ifilter)
  1620. {
  1621. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX], lastdir[PATH_MAX], mark[PATH_MAX];
  1622. static char fltr[LINE_MAX];
  1623. char *dir, *tmp, *run, *env, *tgt = NULL;
  1624. struct stat sb;
  1625. int r, fd, presel;
  1626. enum action sel = SEL_RUNARG + 1;
  1627. xstrlcpy(path, ipath, PATH_MAX);
  1628. xstrlcpy(fltr, ifilter, LINE_MAX);
  1629. oldpath[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  1630. if (cfg.filtermode)
  1631. presel = FILTER;
  1632. else
  1633. presel = 0;
  1634. begin:
  1635. #ifdef LINUX_INOTIFY
  1636. if (inotify_wd >= 0)
  1637. inotify_rm_watch(inotify_fd, inotify_wd);
  1638. #elif defined(BSD_KQUEUE)
  1639. if (event_fd >= 0)
  1640. close(event_fd);
  1641. #endif
  1642. if (populate(path, oldpath, fltr) == -1) {
  1643. printwarn();
  1644. goto nochange;
  1645. }
  1646. #ifdef LINUX_INOTIFY
  1647. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  1648. #elif defined(BSD_KQUEUE)
  1649. event_fd = open(path, O_EVTONLY);
  1650. if (event_fd >= 0)
  1651. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  1652. #endif
  1653. for (;;) {
  1654. redraw(path);
  1655. nochange:
  1656. /* Exit if parent has exited */
  1657. if (getppid() == 1)
  1658. _exit(0);
  1659. sel = nextsel(&run, &env, &presel);
  1660. switch (sel) {
  1661. case SEL_CDQUIT:
  1662. {
  1663. char *tmpfile = "/tmp/nnn";
  1664. tmp = getenv("NNN_TMPFILE");
  1665. if (tmp)
  1666. tmpfile = tmp;
  1667. FILE *fp = fopen(tmpfile, "w");
  1668. if (fp) {
  1669. fprintf(fp, "cd \"%s\"", path);
  1670. fclose(fp);
  1671. }
  1672. /* Fall through to exit */
  1673. } // fallthrough
  1674. case SEL_QUIT:
  1675. dentfree(dents);
  1676. return;
  1677. case SEL_BACK:
  1678. /* There is no going back */
  1679. if (istopdir(path)) {
  1680. printmsg(STR_ATROOT);
  1681. goto nochange;
  1682. }
  1683. dir = xdirname(path);
  1684. if (access(dir, R_OK) == -1) {
  1685. printwarn();
  1686. goto nochange;
  1687. }
  1688. /* Save history */
  1689. xstrlcpy(oldpath, path, PATH_MAX);
  1690. /* Save last working directory */
  1691. xstrlcpy(lastdir, path, PATH_MAX);
  1692. xstrlcpy(path, dir, PATH_MAX);
  1693. /* Reset filter */
  1694. xstrlcpy(fltr, ifilter, LINE_MAX);
  1695. if (cfg.filtermode)
  1696. presel = FILTER;
  1697. goto begin;
  1698. case SEL_GOIN:
  1699. /* Cannot descend in empty directories */
  1700. if (ndents == 0)
  1701. goto begin;
  1702. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1703. DPRINTF_S(newpath);
  1704. /* Get path info */
  1705. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1706. if (fd == -1) {
  1707. printwarn();
  1708. goto nochange;
  1709. }
  1710. r = fstat(fd, &sb);
  1711. if (r == -1) {
  1712. printwarn();
  1713. close(fd);
  1714. goto nochange;
  1715. }
  1716. close(fd);
  1717. DPRINTF_U(sb.st_mode);
  1718. switch (sb.st_mode & S_IFMT) {
  1719. case S_IFDIR:
  1720. if (access(newpath, R_OK) == -1) {
  1721. printwarn();
  1722. goto nochange;
  1723. }
  1724. /* Save last working directory */
  1725. xstrlcpy(lastdir, path, PATH_MAX);
  1726. xstrlcpy(path, newpath, PATH_MAX);
  1727. oldpath[0] = '\0';
  1728. /* Reset filter */
  1729. xstrlcpy(fltr, ifilter, LINE_MAX);
  1730. if (cfg.filtermode)
  1731. presel = FILTER;
  1732. goto begin;
  1733. case S_IFREG:
  1734. {
  1735. /* If NNN_USE_EDITOR is set,
  1736. * open text in EDITOR
  1737. */
  1738. if (editor) {
  1739. if (getmime(dents[cur].name)) {
  1740. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1741. continue;
  1742. }
  1743. /* Recognize and open plain
  1744. * text files with vi
  1745. */
  1746. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  1747. continue;
  1748. if (strstr(g_buf, "text/") == g_buf) {
  1749. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1750. continue;
  1751. }
  1752. }
  1753. /* Invoke desktop opener as last resort */
  1754. spawn(utils[0], newpath, NULL, NULL, F_NOTRACE);
  1755. continue;
  1756. }
  1757. default:
  1758. printmsg("Unsupported file");
  1759. goto nochange;
  1760. }
  1761. case SEL_FLTR:
  1762. presel = readln(path);
  1763. xstrlcpy(fltr, ifilter, LINE_MAX);
  1764. DPRINTF_S(fltr);
  1765. /* Save current */
  1766. if (ndents > 0)
  1767. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1768. goto nochange;
  1769. case SEL_MFLTR:
  1770. cfg.filtermode ^= 1;
  1771. if (cfg.filtermode)
  1772. presel = FILTER;
  1773. else
  1774. printmsg("navigate-as-you-type off");
  1775. goto nochange;
  1776. case SEL_SEARCH:
  1777. spawn(player, path, "search", NULL, F_NORMAL);
  1778. break;
  1779. case SEL_NEXT:
  1780. if (cur < ndents - 1)
  1781. ++cur;
  1782. else if (ndents)
  1783. /* Roll over, set cursor to first entry */
  1784. cur = 0;
  1785. break;
  1786. case SEL_PREV:
  1787. if (cur > 0)
  1788. --cur;
  1789. else if (ndents)
  1790. /* Roll over, set cursor to last entry */
  1791. cur = ndents - 1;
  1792. break;
  1793. case SEL_PGDN:
  1794. if (cur < ndents - 1)
  1795. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1796. break;
  1797. case SEL_PGUP:
  1798. if (cur > 0)
  1799. cur -= MIN((LINES - 4) / 2, cur);
  1800. break;
  1801. case SEL_HOME:
  1802. cur = 0;
  1803. break;
  1804. case SEL_END:
  1805. cur = ndents - 1;
  1806. break;
  1807. case SEL_CD:
  1808. {
  1809. static char *input;
  1810. static int truecd;
  1811. /* Save the program start dir */
  1812. tmp = getcwd(newpath, PATH_MAX);
  1813. if (tmp == NULL) {
  1814. printwarn();
  1815. goto nochange;
  1816. }
  1817. /* Switch to current path for readline(3) */
  1818. if (chdir(path) == -1) {
  1819. printwarn();
  1820. goto nochange;
  1821. }
  1822. exitcurses();
  1823. tmp = readline("chdir: ");
  1824. initcurses();
  1825. /* Change back to program start dir */
  1826. if (chdir(newpath) == -1)
  1827. printwarn();
  1828. if (tmp[0] == '\0')
  1829. break;
  1830. /* Add to readline(3) history */
  1831. add_history(tmp);
  1832. input = tmp;
  1833. tmp = strstrip(tmp);
  1834. if (tmp[0] == '\0') {
  1835. free(input);
  1836. break;
  1837. }
  1838. truecd = 0;
  1839. if (tmp[0] == '~') {
  1840. /* Expand ~ to HOME absolute path */
  1841. char *home = getenv("HOME");
  1842. if (home)
  1843. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  1844. else {
  1845. free(input);
  1846. printmsg(STR_NOHOME);
  1847. goto nochange;
  1848. }
  1849. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1850. if (lastdir[0] == '\0') {
  1851. free(input);
  1852. break;
  1853. }
  1854. /* Switch to last visited dir */
  1855. xstrlcpy(newpath, lastdir, PATH_MAX);
  1856. truecd = 1;
  1857. } else if ((r = all_dots(tmp))) {
  1858. if (r == 1) {
  1859. /* Always in the current dir */
  1860. free(input);
  1861. break;
  1862. }
  1863. /* Show a message if already at / */
  1864. if (istopdir(path)) {
  1865. printmsg(STR_ATROOT);
  1866. free(input);
  1867. goto nochange;
  1868. }
  1869. --r; /* One . for the current dir */
  1870. dir = path;
  1871. /* Note: fd is used as a tmp variable here */
  1872. for (fd = 0; fd < r; ++fd) {
  1873. /* Reached / ? */
  1874. if (istopdir(path)) {
  1875. /* Can't cd beyond / */
  1876. break;
  1877. }
  1878. dir = xdirname(dir);
  1879. if (access(dir, R_OK) == -1) {
  1880. printwarn();
  1881. free(input);
  1882. goto nochange;
  1883. }
  1884. }
  1885. truecd = 1;
  1886. /* Save the path in case of cd ..
  1887. * We mark the current dir in parent dir
  1888. */
  1889. if (r == 1) {
  1890. xstrlcpy(oldpath, path, PATH_MAX);
  1891. truecd = 2;
  1892. }
  1893. xstrlcpy(newpath, dir, PATH_MAX);
  1894. } else
  1895. mkpath(path, tmp, newpath, PATH_MAX);
  1896. free(input);
  1897. if (access(newpath, R_OK) == -1) {
  1898. printwarn();
  1899. break;
  1900. }
  1901. if (truecd == 0) {
  1902. /* Probable change in dir */
  1903. /* No-op if it's the same directory */
  1904. if (xstrcmp(path, newpath) == 0)
  1905. break;
  1906. oldpath[0] = '\0';
  1907. } else if (truecd == 1)
  1908. /* Sure change in dir */
  1909. oldpath[0] = '\0';
  1910. /* Save last working directory */
  1911. xstrlcpy(lastdir, path, PATH_MAX);
  1912. /* Save the newly opted dir in path */
  1913. xstrlcpy(path, newpath, PATH_MAX);
  1914. /* Reset filter */
  1915. xstrlcpy(fltr, ifilter, LINE_MAX);
  1916. DPRINTF_S(path);
  1917. if (cfg.filtermode)
  1918. presel = FILTER;
  1919. goto begin;
  1920. }
  1921. case SEL_CDHOME:
  1922. tgt = getenv("HOME");
  1923. if (tgt == NULL) {
  1924. clearprompt();
  1925. goto nochange;
  1926. } // fallthrough
  1927. case SEL_CDBEGIN:
  1928. if (!tgt)
  1929. tgt = ipath;
  1930. if (access(tgt, R_OK) == -1) {
  1931. printwarn();
  1932. tgt = NULL;
  1933. goto nochange;
  1934. }
  1935. if (xstrcmp(path, tgt) == 0) {
  1936. tgt = NULL;
  1937. break;
  1938. }
  1939. /* Save last working directory */
  1940. xstrlcpy(lastdir, path, PATH_MAX);
  1941. xstrlcpy(path, tgt, PATH_MAX);
  1942. oldpath[0] = '\0';
  1943. /* Reset filter */
  1944. xstrlcpy(fltr, ifilter, LINE_MAX);
  1945. DPRINTF_S(path);
  1946. if (cfg.filtermode)
  1947. presel = FILTER;
  1948. tgt = NULL;
  1949. goto begin;
  1950. case SEL_CDLAST: // fallthrough
  1951. case SEL_VISIT:
  1952. if (sel == SEL_VISIT) {
  1953. if (xstrcmp(mark, path) == 0)
  1954. break;
  1955. tmp = mark;
  1956. } else
  1957. tmp = lastdir;
  1958. if (tmp[0] == '\0') {
  1959. printmsg("Not set...");
  1960. goto nochange;
  1961. }
  1962. if (access(tmp, R_OK) == -1) {
  1963. printwarn();
  1964. goto nochange;
  1965. }
  1966. xstrlcpy(newpath, tmp, PATH_MAX);
  1967. xstrlcpy(lastdir, path, PATH_MAX);
  1968. xstrlcpy(path, newpath, PATH_MAX);
  1969. oldpath[0] = '\0';
  1970. /* Reset filter */
  1971. xstrlcpy(fltr, ifilter, LINE_MAX);
  1972. DPRINTF_S(path);
  1973. if (cfg.filtermode)
  1974. presel = FILTER;
  1975. goto begin;
  1976. case SEL_CDBM:
  1977. printprompt("key: ");
  1978. tmp = readinput();
  1979. clearprompt();
  1980. if (tmp == NULL)
  1981. break;
  1982. for (r = 0; bookmark[r].key && r < MAX_BM; ++r) {
  1983. if (xstrcmp(bookmark[r].key, tmp) == -1)
  1984. continue;
  1985. if (bookmark[r].loc[0] == '~') {
  1986. /* Expand ~ to HOME */
  1987. char *home = getenv("HOME");
  1988. if (home)
  1989. snprintf(newpath, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  1990. else {
  1991. printmsg(STR_NOHOME);
  1992. goto nochange;
  1993. }
  1994. } else
  1995. mkpath(path, bookmark[r].loc,
  1996. newpath, PATH_MAX);
  1997. if (access(newpath, R_OK) == -1) {
  1998. printwarn();
  1999. goto nochange;
  2000. }
  2001. if (xstrcmp(path, newpath) == 0)
  2002. break;
  2003. oldpath[0] = '\0';
  2004. break;
  2005. }
  2006. if (!bookmark[r].key) {
  2007. printmsg("No matching bookmark");
  2008. goto nochange;
  2009. }
  2010. /* Save last working directory */
  2011. xstrlcpy(lastdir, path, PATH_MAX);
  2012. /* Save the newly opted dir in path */
  2013. xstrlcpy(path, newpath, PATH_MAX);
  2014. /* Reset filter */
  2015. xstrlcpy(fltr, ifilter, LINE_MAX);
  2016. DPRINTF_S(path);
  2017. if (cfg.filtermode)
  2018. presel = FILTER;
  2019. goto begin;
  2020. case SEL_MARK:
  2021. xstrlcpy(mark, path, PATH_MAX);
  2022. printmsg(mark);
  2023. goto nochange;
  2024. case SEL_TOGGLEDOT:
  2025. cfg.showhidden ^= 1;
  2026. initfilter(cfg.showhidden, &ifilter);
  2027. xstrlcpy(fltr, ifilter, LINE_MAX);
  2028. goto begin;
  2029. case SEL_DETAIL:
  2030. cfg.showdetail ^= 1;
  2031. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2032. /* Save current */
  2033. if (ndents > 0)
  2034. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2035. goto begin;
  2036. case SEL_STATS:
  2037. if (ndents > 0) {
  2038. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2039. r = lstat(oldpath, &sb);
  2040. if (r == -1) {
  2041. if (dents)
  2042. dentfree(dents);
  2043. printerr(1, "lstat");
  2044. } else {
  2045. r = show_stats(oldpath, dents[cur].name, &sb);
  2046. if (r < 0) {
  2047. printwarn();
  2048. goto nochange;
  2049. }
  2050. }
  2051. }
  2052. break;
  2053. case SEL_MEDIA: // fallthrough
  2054. case SEL_FMEDIA:
  2055. if (ndents > 0) {
  2056. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2057. if (show_mediainfo(oldpath, run) == -1) {
  2058. sprintf(g_buf, "%s missing", metaviewer);
  2059. printmsg(g_buf);
  2060. goto nochange;
  2061. }
  2062. }
  2063. break;
  2064. case SEL_DFB:
  2065. if (!desktop_manager) {
  2066. printmsg("NNN_DE_FILE_MANAGER not set");
  2067. goto nochange;
  2068. }
  2069. spawn(desktop_manager, path, NULL, path, F_NOTRACE | F_NOWAIT);
  2070. break;
  2071. case SEL_FSIZE:
  2072. cfg.sizeorder ^= 1;
  2073. cfg.mtimeorder = 0;
  2074. cfg.blkorder = 0;
  2075. /* Save current */
  2076. if (ndents > 0)
  2077. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2078. goto begin;
  2079. case SEL_BSIZE:
  2080. cfg.blkorder ^= 1;
  2081. if (cfg.blkorder) {
  2082. cfg.showdetail = 1;
  2083. printptr = &printent_long;
  2084. }
  2085. cfg.mtimeorder = 0;
  2086. cfg.sizeorder = 0;
  2087. /* Save current */
  2088. if (ndents > 0)
  2089. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2090. goto begin;
  2091. case SEL_MTIME:
  2092. cfg.mtimeorder ^= 1;
  2093. cfg.sizeorder = 0;
  2094. cfg.blkorder = 0;
  2095. /* Save current */
  2096. if (ndents > 0)
  2097. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2098. goto begin;
  2099. case SEL_REDRAW:
  2100. /* Save current */
  2101. if (ndents > 0)
  2102. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2103. goto begin;
  2104. case SEL_COPY:
  2105. if (copier && ndents) {
  2106. if (istopdir(path))
  2107. snprintf(newpath, PATH_MAX, "/%s", dents[cur].name);
  2108. else
  2109. snprintf(newpath, PATH_MAX, "%s/%s", path, dents[cur].name);
  2110. spawn(copier, newpath, NULL, NULL, F_NONE);
  2111. printmsg(newpath);
  2112. } else if (!copier)
  2113. printmsg("NNN_COPIER is not set");
  2114. goto nochange;
  2115. case SEL_RENAME:
  2116. if (ndents <= 0)
  2117. break;
  2118. printprompt("rename to: ");
  2119. tmp = readinput();
  2120. clearprompt();
  2121. if (tmp == NULL)
  2122. break;
  2123. /* Allow only relative paths */
  2124. if (tmp[0] == '/' || basename(tmp) != tmp) {
  2125. printmsg("relative paths only");
  2126. goto nochange;
  2127. }
  2128. /* Skip renaming to same name */
  2129. if (xstrcmp(tmp, dents[cur].name) == 0)
  2130. break;
  2131. /* Open the descriptor to currently open directory */
  2132. fd = open(path, O_RDONLY | O_DIRECTORY);
  2133. if (fd == -1) {
  2134. printwarn();
  2135. goto nochange;
  2136. }
  2137. /* Check if another file with same name exists */
  2138. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2139. /* File with the same name exists */
  2140. xstrlcpy(g_buf, tmp, NAME_MAX);
  2141. printprompt("overwrite? (y): ");
  2142. tmp = readinput();
  2143. if (tmp == NULL || tmp[0] != 'y' || tmp[1] != '\0') {
  2144. close(fd);
  2145. break;
  2146. }
  2147. tmp = g_buf;
  2148. }
  2149. /* Rename the file */
  2150. r = renameat(fd, dents[cur].name, fd, tmp);
  2151. if (r != 0) {
  2152. printwarn();
  2153. close(fd);
  2154. goto nochange;
  2155. }
  2156. close(fd);
  2157. mkpath(path, tmp, oldpath, PATH_MAX);
  2158. goto begin;
  2159. case SEL_HELP:
  2160. show_help(path);
  2161. break;
  2162. case SEL_RUN:
  2163. run = xgetenv(env, run);
  2164. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2165. /* Repopulate as directory content may have changed */
  2166. goto begin;
  2167. case SEL_RUNARG:
  2168. run = xgetenv(env, run);
  2169. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2170. break;
  2171. }
  2172. /* Screensaver */
  2173. if (idletimeout != 0 && idle == idletimeout) {
  2174. idle = 0;
  2175. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2176. }
  2177. }
  2178. }
  2179. static void
  2180. usage(void)
  2181. {
  2182. printf("usage: nnn [-c N] [-e] [-i] [-l] [-p nlay] [-S]\n\
  2183. [-v] [-h] [PATH]\n\n\
  2184. The missing terminal file browser for X.\n\n\
  2185. positional arguments:\n\
  2186. PATH directory to open [default: current dir]\n\n\
  2187. optional arguments:\n\
  2188. -c N specify dir color, disables if N>7\n\
  2189. -e use exiftool instead of mediainfo\n\
  2190. -i start in navigate-as-you-type mode\n\
  2191. -l start in light mode (fewer details)\n\
  2192. -p nlay path to custom nlay\n\
  2193. -S start in disk usage analyzer mode\n\
  2194. -v show program version and exit\n\
  2195. -h show this help and exit\n\n\
  2196. Version: %s\n\
  2197. License: BSD 2-Clause\n\
  2198. Webpage: https://github.com/jarun/nnn\n", VERSION);
  2199. exit(0);
  2200. }
  2201. int
  2202. main(int argc, char *argv[])
  2203. {
  2204. static char cwd[PATH_MAX];
  2205. char *ipath, *ifilter, *bmstr;
  2206. int opt;
  2207. /* Confirm we are in a terminal */
  2208. if (!isatty(0) || !isatty(1)) {
  2209. fprintf(stderr, "stdin or stdout is not a tty\n");
  2210. exit(1);
  2211. }
  2212. while ((opt = getopt(argc, argv, "Slic:ep:vh")) != -1) {
  2213. switch (opt) {
  2214. case 'S':
  2215. cfg.blkorder = 1;
  2216. break;
  2217. case 'l':
  2218. cfg.showdetail = 0;
  2219. printptr = &printent;
  2220. break;
  2221. case 'i':
  2222. cfg.filtermode = 1;
  2223. break;
  2224. case 'c':
  2225. color = (uchar)atoi(optarg);
  2226. if (color > 7)
  2227. cfg.showcolor = 0;
  2228. break;
  2229. case 'e':
  2230. metaviewer = utils[3];
  2231. break;
  2232. case 'p':
  2233. player = optarg;
  2234. break;
  2235. case 'v':
  2236. printf("%s\n", VERSION);
  2237. return 0;
  2238. case 'h': // fallthrough
  2239. default:
  2240. usage();
  2241. }
  2242. }
  2243. if (argc == optind) {
  2244. /* Start in the current directory */
  2245. ipath = getcwd(cwd, PATH_MAX);
  2246. if (ipath == NULL)
  2247. ipath = "/";
  2248. } else {
  2249. ipath = realpath(argv[optind], cwd);
  2250. if (!ipath) {
  2251. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2252. exit(1);
  2253. }
  2254. }
  2255. /* Increase current open file descriptor limit */
  2256. open_max = max_openfds();
  2257. if (getuid() == 0)
  2258. cfg.showhidden = 1;
  2259. initfilter(cfg.showhidden, &ifilter);
  2260. #ifdef LINUX_INOTIFY
  2261. /* Initialize inotify */
  2262. inotify_fd = inotify_init1(IN_NONBLOCK);
  2263. if (inotify_fd < 0) {
  2264. fprintf(stderr, "Cannot initialize inotify: %s\n", strerror(errno));
  2265. exit(1);
  2266. }
  2267. #elif defined(BSD_KQUEUE)
  2268. kq = kqueue();
  2269. if (kq < 0) {
  2270. fprintf(stderr, "Cannot initialize kqueue: %s\n", strerror(errno));
  2271. exit(1);
  2272. }
  2273. gtimeout.tv_sec = 0;
  2274. gtimeout.tv_nsec = 50; /* 50 ns delay */
  2275. #endif
  2276. /* Parse bookmarks string, if available */
  2277. bmstr = getenv("NNN_BMS");
  2278. if (bmstr)
  2279. parsebmstr(bmstr);
  2280. /* Edit text in EDITOR, if opted */
  2281. if (getenv("NNN_USE_EDITOR"))
  2282. editor = xgetenv("EDITOR", "vi");
  2283. /* Set metadata viewer if not set */
  2284. if (!metaviewer)
  2285. metaviewer = utils[2];
  2286. /* Set player if not set already */
  2287. if (!player)
  2288. player = utils[1];
  2289. /* Get the desktop file browser, if set */
  2290. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2291. /* Get screensaver wait time, if set; copier used as tmp var */
  2292. copier = getenv("NNN_IDLE_TIMEOUT");
  2293. if (copier)
  2294. idletimeout = abs(atoi(copier));
  2295. /* Get the default copier, if set */
  2296. copier = getenv("NNN_COPIER");
  2297. signal(SIGINT, SIG_IGN);
  2298. /* Test initial path */
  2299. if (access(ipath, R_OK) == -1) {
  2300. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2301. exit(1);
  2302. }
  2303. /* Set locale */
  2304. setlocale(LC_ALL, "");
  2305. #ifdef DEBUGMODE
  2306. enabledbg();
  2307. #endif
  2308. initcurses();
  2309. browse(ipath, ifilter);
  2310. exitcurses();
  2311. #ifdef LINUX_INOTIFY
  2312. /* Shutdown inotify */
  2313. if (inotify_wd >= 0)
  2314. inotify_rm_watch(inotify_fd, inotify_wd);
  2315. close(inotify_fd);
  2316. #elif defined(BSD_KQUEUE)
  2317. if (event_fd >= 0)
  2318. close(event_fd);
  2319. close(kq);
  2320. #endif
  2321. #ifdef DEBUGMODE
  2322. disabledbg();
  2323. #endif
  2324. exit(0);
  2325. }