My build of nnn with minor changes
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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