My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2574 lines
52 KiB

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