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.
 
 
 
 
 
 

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