My build of nnn with minor changes
 
 
 
 
 
 

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