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.
 
 
 
 
 
 

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