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

2581 строка
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. #define exitcurses() endwin()
  108. #define clearprompt() printmsg("")
  109. #define printwarn() printmsg(strerror(errno))
  110. #define istopdir(path) (path[1] == '\0' && path[0] == '/')
  111. typedef unsigned long ulong;
  112. typedef unsigned int uint;
  113. typedef unsigned char uchar;
  114. /* Directory entry */
  115. typedef struct entry {
  116. char name[NAME_MAX];
  117. mode_t mode;
  118. time_t t;
  119. off_t size;
  120. blkcnt_t blocks; /* number of 512B blocks allocated */
  121. } *pEntry;
  122. /* Bookmark */
  123. typedef struct {
  124. char *key;
  125. char *loc;
  126. } bm;
  127. /* Settings */
  128. typedef struct {
  129. uchar filtermode : 1; /* Set to enter filter mode */
  130. uchar mtimeorder : 1; /* Set to sort by time modified */
  131. uchar sizeorder : 1; /* Set to sort by file size */
  132. uchar blkorder : 1; /* Set to sort by blocks used (disk usage) */
  133. uchar showhidden : 1; /* Set to show hidden files */
  134. uchar showdetail : 1; /* Clear to show fewer file info */
  135. uchar showcolor : 1; /* Set to show dirs in blue */
  136. uchar dircolor : 1; /* Current status of dir color */
  137. } settings;
  138. /* Externs */
  139. #ifdef __APPLE__
  140. extern int add_history(const char *string);
  141. #else
  142. extern void add_history(const char *string);
  143. #endif
  144. extern int wget_wch(WINDOW *win, wint_t *wch);
  145. /* Globals */
  146. /* Configuration */
  147. static settings cfg = {0, 0, 0, 0, 0, 1, 1, 0};
  148. static struct entry *dents;
  149. static int ndents, cur, total_dents;
  150. static uint idle;
  151. static uint idletimeout;
  152. static char *player;
  153. static char *copier;
  154. static char *editor;
  155. static char *desktop_manager;
  156. static blkcnt_t ent_blocks;
  157. static blkcnt_t dir_blocks;
  158. static ulong num_files;
  159. static size_t fs_free;
  160. static uint open_max;
  161. static bm bookmark[MAX_BM];
  162. static const double div_2_pow_10 = 1.0 / 1024.0;
  163. static uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  164. static uchar color = 4;
  165. /* Utilities to open files, run actions */
  166. static char * const utils[] = {
  167. #ifdef __APPLE__
  168. "/usr/bin/open",
  169. #else
  170. "/usr/bin/xdg-open",
  171. #endif
  172. "nlay",
  173. "mediainfo",
  174. "exiftool"
  175. };
  176. static char *metaviewer;
  177. /* For use in functions which are isolated and don't return the buffer */
  178. static char g_buf[MAX_CMD_LEN];
  179. /* Common message strings */
  180. static char *STR_NFTWFAIL = "nftw(3) failed";
  181. static char *STR_ATROOT = "You are at /";
  182. static char *STR_NOHOME = "HOME not set";
  183. /*
  184. * Layout:
  185. * .---------
  186. * | cwd: /mnt/path
  187. * |
  188. * | file0
  189. * | file1
  190. * | > file2
  191. * | file3
  192. * | file4
  193. * ...
  194. * | filen
  195. * |
  196. * | Permission denied
  197. * '------
  198. */
  199. /* Forward declarations */
  200. static void printmsg(char *);
  201. static void printerr(int, char *);
  202. static void redraw(char *path);
  203. /* Functions */
  204. /* Increase the limit on open file descriptors, if possible */
  205. static rlim_t
  206. max_openfds()
  207. {
  208. struct rlimit rl;
  209. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  210. if (limit != 0)
  211. return 32;
  212. limit = rl.rlim_cur;
  213. rl.rlim_cur = rl.rlim_max;
  214. if (setrlimit(RLIMIT_NOFILE, &rl) == 0)
  215. return rl.rlim_max - 64;
  216. if (limit > 128)
  217. return limit - 64;
  218. return 32;
  219. }
  220. /*
  221. * Custom xstrlen()
  222. */
  223. static size_t
  224. xstrlen(const char *s)
  225. {
  226. static size_t len;
  227. if (!s)
  228. return 0;
  229. len = 0;
  230. while (*s)
  231. ++len, ++s;
  232. return len;
  233. }
  234. /*
  235. * Just a safe strncpy(3)
  236. * Always null ('\0') terminates if both src and dest are valid pointers.
  237. * Returns the number of bytes copied including terminating null byte.
  238. */
  239. static size_t
  240. xstrlcpy(char *dest, const char *src, size_t n)
  241. {
  242. static size_t len, blocks;
  243. if (!src || !dest)
  244. return 0;
  245. len = xstrlen(src) + 1;
  246. if (n > len)
  247. n = len;
  248. else if (len > n)
  249. /* Save total number of bytes to copy in len */
  250. len = n;
  251. blocks = n >> _WSHIFT;
  252. n -= (blocks << _WSHIFT);
  253. if (blocks) {
  254. static ulong *s, *d;
  255. s = (ulong *)src;
  256. d = (ulong *)dest;
  257. while (blocks) {
  258. *d = *s;
  259. ++d, ++s;
  260. --blocks;
  261. }
  262. if (!n) {
  263. dest = (char *)d;
  264. *--dest = '\0';
  265. return len;
  266. }
  267. src = (char *)s;
  268. dest = (char *)d;
  269. }
  270. while (--n && (*dest = *src))
  271. ++dest, ++src;
  272. if (!n)
  273. *dest = '\0';
  274. return len;
  275. }
  276. /*
  277. * Custom strcmp(), just what we need.
  278. * Returns 0 if same, else -1
  279. */
  280. static int
  281. xstrcmp(const char *s1, const char *s2)
  282. {
  283. if (!s1 || !s2)
  284. return -1;
  285. while (*s1 && *s1 == *s2)
  286. ++s1, ++s2;
  287. if (*s1 != *s2)
  288. return -1;
  289. return 0;
  290. }
  291. /*
  292. * The poor man's implementation of memrchr(3).
  293. * We are only looking for '/' in this program.
  294. * Ideally 0 < n <= strlen(s).
  295. */
  296. static void *
  297. xmemrchr(uchar *s, uchar ch, size_t n)
  298. {
  299. if (!s || !n)
  300. return NULL;
  301. s = s + n - 1;
  302. while (n) {
  303. if (*s == ch)
  304. return s;
  305. --n, --s;
  306. }
  307. return NULL;
  308. }
  309. /*
  310. * The following dirname(3) implementation does not
  311. * modify the input. We use a copy of the original.
  312. *
  313. * Modified from the glibc (GNU LGPL) version.
  314. */
  315. static char *
  316. xdirname(const char *path)
  317. {
  318. static char *buf = g_buf;
  319. static char *last_slash;
  320. xstrlcpy(buf, path, PATH_MAX);
  321. /* Find last '/'. */
  322. last_slash = xmemrchr((uchar *)buf, '/', strlen(buf));
  323. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  324. /* Determine whether all remaining characters are slashes. */
  325. char *runp;
  326. for (runp = last_slash; runp != buf; --runp)
  327. if (runp[-1] != '/')
  328. break;
  329. /* The '/' is the last character, we have to look further. */
  330. if (runp != buf)
  331. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  332. }
  333. if (last_slash != NULL) {
  334. /* Determine whether all remaining characters are slashes. */
  335. char *runp;
  336. for (runp = last_slash; runp != buf; --runp)
  337. if (runp[-1] != '/')
  338. break;
  339. /* Terminate the buffer. */
  340. if (runp == buf) {
  341. /* The last slash is the first character in the string.
  342. * We have to return "/". As a special case we have to
  343. * return "//" if there are exactly two slashes at the
  344. * beginning of the string. See XBD 4.10 Path Name
  345. * Resolution for more information.
  346. */
  347. if (last_slash == buf + 1)
  348. ++last_slash;
  349. else
  350. last_slash = buf + 1;
  351. } else
  352. last_slash = runp;
  353. last_slash[0] = '\0';
  354. } else {
  355. /* This assignment is ill-designed but the XPG specs require to
  356. * return a string containing "." in any case no directory part
  357. * is found and so a static and constant string is required.
  358. */
  359. buf[0] = '.';
  360. buf[1] = '\0';
  361. }
  362. return buf;
  363. }
  364. /*
  365. * Return number of dots if all chars in a string are dots, else 0
  366. */
  367. static int
  368. all_dots(const char *path)
  369. {
  370. if (!path)
  371. return FALSE;
  372. int count = 0;
  373. while (*path == '.')
  374. ++count, ++path;
  375. if (*path)
  376. return 0;
  377. return count;
  378. }
  379. /* Initialize curses mode */
  380. static void
  381. initcurses(void)
  382. {
  383. if (initscr() == NULL) {
  384. char *term = getenv("TERM");
  385. if (term != NULL)
  386. fprintf(stderr, "error opening TERM: %s\n", term);
  387. else
  388. fprintf(stderr, "initscr() failed\n");
  389. exit(1);
  390. }
  391. cbreak();
  392. noecho();
  393. nonl();
  394. intrflush(stdscr, FALSE);
  395. keypad(stdscr, TRUE);
  396. curs_set(FALSE); /* Hide cursor */
  397. start_color();
  398. use_default_colors();
  399. if (cfg.showcolor)
  400. init_pair(1, color, -1);
  401. timeout(1000); /* One second */
  402. }
  403. /*
  404. * Spawns a child process. Behaviour can be controlled using flag.
  405. * Limited to 2 arguments to a program, flag works on bit set.
  406. */
  407. static void
  408. spawn(char *file, char *arg1, char *arg2, char *dir, uchar flag)
  409. {
  410. pid_t pid;
  411. int status;
  412. if (flag & F_NORMAL)
  413. exitcurses();
  414. pid = fork();
  415. if (pid == 0) {
  416. if (dir != NULL)
  417. status = chdir(dir);
  418. /* Show a marker (to indicate nnn spawned shell) */
  419. if (flag & F_MARKER) {
  420. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  421. printf("Spawned shell level: %d\n",
  422. atoi(getenv("SHLVL")) + 1);
  423. }
  424. /* Suppress stdout and stderr */
  425. if (flag & F_NOTRACE) {
  426. int fd = open("/dev/null", O_WRONLY, 0200);
  427. dup2(fd, 1);
  428. dup2(fd, 2);
  429. close(fd);
  430. }
  431. if (flag & F_SIGINT)
  432. signal(SIGINT, SIG_DFL);
  433. execlp(file, file, arg1, arg2, NULL);
  434. _exit(1);
  435. } else {
  436. if (!(flag & F_NOWAIT))
  437. /* Ignore interruptions */
  438. while (waitpid(pid, &status, 0) == -1)
  439. DPRINTF_D(status);
  440. DPRINTF_D(pid);
  441. if (flag & F_NORMAL)
  442. initcurses();
  443. }
  444. }
  445. /* Get program name from env var, else return fallback program */
  446. static char *
  447. xgetenv(char *name, char *fallback)
  448. {
  449. if (name == NULL)
  450. return fallback;
  451. char *value = getenv(name);
  452. return value && value[0] ? value : fallback;
  453. }
  454. /*
  455. * We assume none of the strings are NULL.
  456. *
  457. * Let's have the logic to sort numeric names in numeric order.
  458. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  459. *
  460. * If the absolute numeric values are same, we fallback to alphasort.
  461. */
  462. static int
  463. xstricmp(char *s1, char *s2)
  464. {
  465. static char *c1, *c2;
  466. c1 = s1;
  467. while (isspace(*c1))
  468. ++c1;
  469. if (*c1 == '-' || *c1 == '+')
  470. ++c1;
  471. while (*c1 >= '0' && *c1 <= '9')
  472. ++c1;
  473. c2 = s2;
  474. while (isspace(*c2))
  475. ++c2;
  476. if (*c2 == '-' || *c2 == '+')
  477. ++c2;
  478. while (*c2 >= '0' && *c2 <= '9')
  479. ++c2;
  480. if (*c1 == '\0' && *c2 == '\0') {
  481. static long long num1, num2;
  482. num1 = strtoll(s1, &c1, 10);
  483. num2 = strtoll(s2, &c2, 10);
  484. if (num1 != num2) {
  485. if (num1 > num2)
  486. return 1;
  487. else
  488. return -1;
  489. }
  490. } else if (*c1 == '\0' && *c2 != '\0')
  491. return -1;
  492. else if (*c1 != '\0' && *c2 == '\0')
  493. return 1;
  494. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  495. ++s1, ++s2;
  496. /* In case of alphabetically same names, make sure
  497. * lower case one comes before upper case one
  498. */
  499. if (!*s1 && !*s2)
  500. return 1;
  501. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  502. }
  503. /* Trim all whitespace from both ends, / from end */
  504. static char *
  505. strstrip(char *s)
  506. {
  507. if (!s || !*s)
  508. return s;
  509. size_t len = xstrlen(s) - 1;
  510. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  511. --len;
  512. s[len + 1] = '\0';
  513. while (*s && isspace(*s))
  514. ++s;
  515. return s;
  516. }
  517. static char *
  518. getmime(char *file)
  519. {
  520. regex_t regex;
  521. uint i;
  522. static uint len = LEN(assocs);
  523. for (i = 0; i < len; ++i) {
  524. if (regcomp(&regex, assocs[i].regex,
  525. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  526. continue;
  527. if (regexec(&regex, file, 0, NULL, 0) == 0)
  528. return assocs[i].mime;
  529. }
  530. return NULL;
  531. }
  532. static int
  533. setfilter(regex_t *regex, char *filter)
  534. {
  535. static size_t len;
  536. static int r;
  537. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  538. if (r != 0 && filter && filter[0] != '\0') {
  539. len = COLS;
  540. if (len > LINE_MAX)
  541. len = LINE_MAX;
  542. regerror(r, regex, g_buf, len);
  543. printmsg(g_buf);
  544. }
  545. return r;
  546. }
  547. static void
  548. initfilter(int dot, char **ifilter)
  549. {
  550. *ifilter = dot ? "." : "^[^.]";
  551. }
  552. static int
  553. visible(regex_t *regex, char *file)
  554. {
  555. return regexec(regex, file, 0, NULL, 0) == 0;
  556. }
  557. static int
  558. entrycmp(const void *va, const void *vb)
  559. {
  560. static pEntry pa, pb;
  561. pa = (pEntry)va;
  562. pb = (pEntry)vb;
  563. /* Sort directories first */
  564. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  565. return 1;
  566. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  567. return -1;
  568. /* Do the actual sorting */
  569. if (cfg.mtimeorder)
  570. return pb->t - pa->t;
  571. if (cfg.sizeorder) {
  572. if (pb->size > pa->size)
  573. return 1;
  574. else if (pb->size < pa->size)
  575. return -1;
  576. }
  577. if (cfg.blkorder) {
  578. if (pb->blocks > pa->blocks)
  579. return 1;
  580. else if (pb->blocks < pa->blocks)
  581. return -1;
  582. }
  583. return xstricmp(pa->name, pb->name);
  584. }
  585. /* Messages show up at the bottom */
  586. static void
  587. printmsg(char *msg)
  588. {
  589. mvprintw(LINES - 1, 0, "%s\n", msg);
  590. }
  591. /* Kill curses and display error before exiting */
  592. static void
  593. printerr(int ret, char *prefix)
  594. {
  595. exitcurses();
  596. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  597. exit(ret);
  598. }
  599. /* Print prompt on the last line */
  600. static void
  601. printprompt(char *str)
  602. {
  603. clearprompt();
  604. printw(str);
  605. }
  606. /* Returns SEL_* if key is bound and 0 otherwise.
  607. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  608. * The next keyboard input can be simulated by presel.
  609. */
  610. static int
  611. nextsel(char **run, char **env, int *presel)
  612. {
  613. static int c;
  614. static uchar i;
  615. static uint len = LEN(bindings);
  616. c = *presel;
  617. if (c == 0)
  618. c = getch();
  619. else
  620. *presel = 0;
  621. if (c == -1)
  622. ++idle;
  623. else
  624. idle = 0;
  625. for (i = 0; i < len; ++i)
  626. if (c == bindings[i].sym) {
  627. *run = bindings[i].run;
  628. *env = bindings[i].env;
  629. return bindings[i].act;
  630. }
  631. return 0;
  632. }
  633. /*
  634. * Move non-matching entries to the end
  635. */
  636. static void
  637. fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  638. {
  639. static int count;
  640. for (count = 0; count < ndents; ++count) {
  641. if (filter(re, (*dents)[count].name) == 0) {
  642. if (count != --ndents) {
  643. static struct entry _dent, *dentp1, *dentp2;
  644. dentp1 = &(*dents)[count];
  645. dentp2 = &(*dents)[ndents];
  646. /* Copy count to tmp */
  647. xstrlcpy(_dent.name, dentp1->name, NAME_MAX);
  648. _dent.mode = dentp1->mode;
  649. _dent.t = dentp1->t;
  650. _dent.size = dentp1->size;
  651. _dent.blocks = dentp1->blocks;
  652. /* Copy ndents - 1 to count */
  653. xstrlcpy(dentp1->name, dentp2->name, NAME_MAX);
  654. dentp1->mode = dentp2->mode;
  655. dentp1->t = dentp2->t;
  656. dentp1->size = dentp2->size;
  657. dentp1->blocks = dentp2->blocks;
  658. /* Copy tmp to ndents - 1 */
  659. xstrlcpy(dentp2->name, _dent.name, NAME_MAX);
  660. dentp2->mode = _dent.mode;
  661. dentp2->t = _dent.t;
  662. dentp2->size = _dent.size;
  663. dentp2->blocks = _dent.blocks;
  664. --count;
  665. }
  666. continue;
  667. }
  668. }
  669. }
  670. static int
  671. matches(char *fltr)
  672. {
  673. static regex_t re;
  674. /* Search filter */
  675. if (setfilter(&re, fltr) != 0)
  676. return -1;
  677. fill(&dents, visible, &re);
  678. qsort(dents, ndents, sizeof(*dents), entrycmp);
  679. return 0;
  680. }
  681. static int
  682. readln(char *path)
  683. {
  684. static char ln[LINE_MAX << 2];
  685. static wchar_t wln[LINE_MAX];
  686. static wint_t ch[2] = {0};
  687. int r, total = ndents;
  688. int oldcur = cur;
  689. int len = 1;
  690. char *pln = ln + 1;
  691. memset(wln, 0, LINE_MAX << 2);
  692. wln[0] = FILTER;
  693. ln[0] = FILTER;
  694. ln[1] = '\0';
  695. cur = 0;
  696. timeout(-1);
  697. echo();
  698. curs_set(TRUE);
  699. printprompt(ln);
  700. while ((r = wget_wch(stdscr, ch)) != ERR)
  701. if (r == OK)
  702. switch (*ch) {
  703. case '\r': // with nonl(), this is ENTER key value
  704. if (len == 1) {
  705. cur = oldcur;
  706. goto end;
  707. }
  708. if (matches(pln) == -1)
  709. goto end;
  710. redraw(path);
  711. goto end;
  712. case 127: // handle DEL
  713. if (len == 1) {
  714. cur = oldcur;
  715. *ch = CONTROL('L');
  716. goto end;
  717. }
  718. wln[--len] = '\0';
  719. if (len == 1)
  720. cur = oldcur;
  721. wcstombs(ln, wln, LINE_MAX << 2);
  722. ndents = total;
  723. if (matches(pln) == -1) {
  724. printprompt(ln);
  725. continue;
  726. }
  727. redraw(path);
  728. printprompt(ln);
  729. break;
  730. case CONTROL('L'):
  731. if (len == 1)
  732. cur = oldcur; // fallthrough
  733. case CONTROL('Q'):
  734. goto end;
  735. default:
  736. /* Reset cur in case it's a repeat search */
  737. if (len == 1)
  738. cur = 0;
  739. wln[len] = (wchar_t)*ch;
  740. wln[++len] = '\0';
  741. wcstombs(ln, wln, LINE_MAX << 2);
  742. ndents = total;
  743. if (matches(pln) == -1)
  744. continue;
  745. redraw(path);
  746. printprompt(ln);
  747. }
  748. else
  749. switch (*ch) {
  750. case KEY_DC: // fallthrough
  751. case KEY_BACKSPACE:
  752. if (len == 1) {
  753. cur = oldcur;
  754. *ch = CONTROL('L');
  755. goto end;
  756. }
  757. wln[--len] = '\0';
  758. if (len == 1)
  759. cur = oldcur;
  760. wcstombs(ln, wln, LINE_MAX << 2);
  761. ndents = total;
  762. if (matches(pln) == -1)
  763. continue;
  764. redraw(path);
  765. printprompt(ln);
  766. break;
  767. case KEY_DOWN: // fallthrough
  768. case KEY_UP: // fallthrough
  769. case KEY_LEFT: // fallthrough
  770. case KEY_RIGHT: // fallthrough
  771. case KEY_F(2):
  772. if (len == 1)
  773. cur = oldcur; // fallthrough
  774. default:
  775. goto end;
  776. }
  777. end:
  778. noecho();
  779. curs_set(FALSE);
  780. timeout(1000);
  781. /* Return keys for navigation etc. */
  782. return *ch;
  783. }
  784. /*
  785. * Returns "dir/name or "/name"
  786. */
  787. static char *
  788. mkpath(char *dir, char *name, char *out, size_t n)
  789. {
  790. /* Handle absolute path */
  791. if (name[0] == '/')
  792. xstrlcpy(out, name, n);
  793. else {
  794. /* Handle root case */
  795. if (istopdir(dir))
  796. snprintf(out, n, "/%s", name);
  797. else
  798. snprintf(out, n, "%s/%s", dir, name);
  799. }
  800. return out;
  801. }
  802. static void
  803. parsebmstr(char *bms)
  804. {
  805. int i = 0;
  806. while (*bms && i < MAX_BM) {
  807. bookmark[i].key = bms;
  808. ++bms;
  809. while (*bms && *bms != ':')
  810. ++bms;
  811. if (!*bms) {
  812. bookmark[i].key = NULL;
  813. break;
  814. }
  815. *bms = '\0';
  816. bookmark[i].loc = ++bms;
  817. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  818. bookmark[i].key = NULL;
  819. break;
  820. }
  821. while (*bms && *bms != ';')
  822. ++bms;
  823. if (*bms)
  824. *bms = '\0';
  825. else
  826. break;
  827. ++bms;
  828. ++i;
  829. }
  830. }
  831. static char *
  832. readinput(void)
  833. {
  834. timeout(-1);
  835. echo();
  836. curs_set(TRUE);
  837. memset(g_buf, 0, LINE_MAX);
  838. wgetnstr(stdscr, g_buf, LINE_MAX - 1);
  839. noecho();
  840. curs_set(FALSE);
  841. timeout(1000);
  842. return g_buf[0] ? g_buf : NULL;
  843. }
  844. /*
  845. * Replace escape characters in a string with '?'
  846. */
  847. static char *
  848. unescape(const char *str)
  849. {
  850. static char buffer[PATH_MAX];
  851. static wchar_t wbuf[PATH_MAX];
  852. static wchar_t *buf;
  853. buffer[0] = '\0';
  854. buf = wbuf;
  855. /* Convert multi-byte to wide char */
  856. mbstowcs(wbuf, str, PATH_MAX);
  857. while (*buf) {
  858. if (*buf <= '\x1f' || *buf == '\x7f')
  859. *buf = '\?';
  860. ++buf;
  861. }
  862. /* Convert wide char to multi-byte */
  863. wcstombs(buffer, wbuf, PATH_MAX);
  864. return buffer;
  865. }
  866. static void
  867. printent(struct entry *ent, int sel)
  868. {
  869. static int ncols;
  870. if (PATH_MAX + 16 < COLS)
  871. ncols = PATH_MAX + 16;
  872. else
  873. ncols = COLS;
  874. if (S_ISDIR(ent->mode))
  875. snprintf(g_buf, ncols, "%s%s/", CURSYM(sel),
  876. unescape(ent->name));
  877. else if (S_ISLNK(ent->mode))
  878. snprintf(g_buf, ncols, "%s%s@", CURSYM(sel),
  879. unescape(ent->name));
  880. else if (S_ISSOCK(ent->mode))
  881. snprintf(g_buf, ncols, "%s%s=", CURSYM(sel),
  882. unescape(ent->name));
  883. else if (S_ISFIFO(ent->mode))
  884. snprintf(g_buf, ncols, "%s%s|", CURSYM(sel),
  885. unescape(ent->name));
  886. else if (ent->mode & 0100)
  887. snprintf(g_buf, ncols, "%s%s*", CURSYM(sel),
  888. unescape(ent->name));
  889. else
  890. snprintf(g_buf, ncols, "%s%s", CURSYM(sel),
  891. unescape(ent->name));
  892. /* Dirs are always shown on top */
  893. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  894. attroff(COLOR_PAIR(1) | A_BOLD);
  895. cfg.dircolor = 0;
  896. }
  897. printw("%s\n", g_buf);
  898. }
  899. static char *
  900. coolsize(off_t size)
  901. {
  902. static const char * const U = "BKMGTPEZY";
  903. static char size_buf[12]; /* Buffer to hold human readable size */
  904. static int i;
  905. static off_t tmp;
  906. static long double rem;
  907. i = 0;
  908. rem = 0;
  909. while (size > 1024) {
  910. tmp = size;
  911. size >>= 10;
  912. rem = tmp - (size << 10);
  913. ++i;
  914. }
  915. snprintf(size_buf, 12, "%.*Lf%c", i, size + rem * div_2_pow_10, U[i]);
  916. return size_buf;
  917. }
  918. static void
  919. printent_long(struct entry *ent, int sel)
  920. {
  921. static int ncols;
  922. static char buf[18];
  923. if (PATH_MAX + 32 < COLS)
  924. ncols = PATH_MAX + 32;
  925. else
  926. ncols = COLS;
  927. strftime(buf, 18, "%d %m %Y %H:%M", localtime(&ent->t));
  928. if (sel)
  929. attron(A_REVERSE);
  930. if (!cfg.blkorder) {
  931. if (S_ISDIR(ent->mode))
  932. snprintf(g_buf, ncols, "%s%-16.16s / %s/",
  933. CURSYM(sel), buf, unescape(ent->name));
  934. else if (S_ISLNK(ent->mode))
  935. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  936. CURSYM(sel), buf, unescape(ent->name));
  937. else if (S_ISSOCK(ent->mode))
  938. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  939. CURSYM(sel), buf, unescape(ent->name));
  940. else if (S_ISFIFO(ent->mode))
  941. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  942. CURSYM(sel), buf, unescape(ent->name));
  943. else if (S_ISBLK(ent->mode))
  944. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  945. CURSYM(sel), buf, unescape(ent->name));
  946. else if (S_ISCHR(ent->mode))
  947. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  948. CURSYM(sel), buf, unescape(ent->name));
  949. else if (ent->mode & 0100)
  950. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  951. CURSYM(sel), buf, coolsize(ent->size),
  952. unescape(ent->name));
  953. else
  954. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  955. CURSYM(sel), buf, coolsize(ent->size),
  956. unescape(ent->name));
  957. } else {
  958. if (S_ISDIR(ent->mode))
  959. snprintf(g_buf, ncols, "%s%-16.16s %8.8s/ %s/",
  960. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  961. unescape(ent->name));
  962. else if (S_ISLNK(ent->mode))
  963. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  964. CURSYM(sel), buf,
  965. unescape(ent->name));
  966. else if (S_ISSOCK(ent->mode))
  967. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  968. CURSYM(sel), buf,
  969. unescape(ent->name));
  970. else if (S_ISFIFO(ent->mode))
  971. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  972. CURSYM(sel), buf,
  973. unescape(ent->name));
  974. else if (S_ISBLK(ent->mode))
  975. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  976. CURSYM(sel), buf,
  977. unescape(ent->name));
  978. else if (S_ISCHR(ent->mode))
  979. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  980. CURSYM(sel), buf,
  981. unescape(ent->name));
  982. else if (ent->mode & 0100)
  983. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  984. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  985. unescape(ent->name));
  986. else
  987. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  988. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  989. unescape(ent->name));
  990. }
  991. /* Dirs are always shown on top */
  992. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  993. attroff(COLOR_PAIR(1) | A_BOLD);
  994. cfg.dircolor = 0;
  995. }
  996. printw("%s\n", g_buf);
  997. if (sel)
  998. attroff(A_REVERSE);
  999. }
  1000. static void (*printptr)(struct entry *ent, int sel) = &printent_long;
  1001. static char
  1002. get_fileind(mode_t mode, char *desc)
  1003. {
  1004. static char c;
  1005. if (S_ISREG(mode)) {
  1006. c = '-';
  1007. sprintf(desc, "%s", "regular file");
  1008. if (mode & 0100)
  1009. strcat(desc, ", executable");
  1010. } else if (S_ISDIR(mode)) {
  1011. c = 'd';
  1012. sprintf(desc, "%s", "directory");
  1013. } else if (S_ISBLK(mode)) {
  1014. c = 'b';
  1015. sprintf(desc, "%s", "block special device");
  1016. } else if (S_ISCHR(mode)) {
  1017. c = 'c';
  1018. sprintf(desc, "%s", "character special device");
  1019. #ifdef S_ISFIFO
  1020. } else if (S_ISFIFO(mode)) {
  1021. c = 'p';
  1022. sprintf(desc, "%s", "FIFO");
  1023. #endif /* S_ISFIFO */
  1024. #ifdef S_ISLNK
  1025. } else if (S_ISLNK(mode)) {
  1026. c = 'l';
  1027. sprintf(desc, "%s", "symbolic link");
  1028. #endif /* S_ISLNK */
  1029. #ifdef S_ISSOCK
  1030. } else if (S_ISSOCK(mode)) {
  1031. c = 's';
  1032. sprintf(desc, "%s", "socket");
  1033. #endif /* S_ISSOCK */
  1034. #ifdef S_ISDOOR
  1035. /* Solaris 2.6, etc. */
  1036. } else if (S_ISDOOR(mode)) {
  1037. c = 'D';
  1038. desc[0] = '\0';
  1039. #endif /* S_ISDOOR */
  1040. } else {
  1041. /* Unknown type -- possibly a regular file? */
  1042. c = '?';
  1043. desc[0] = '\0';
  1044. }
  1045. return c;
  1046. }
  1047. /* Convert a mode field into "ls -l" type perms field. */
  1048. static char *
  1049. get_lsperms(mode_t mode, char *desc)
  1050. {
  1051. static const char * const rwx[] = {"---", "--x", "-w-", "-wx",
  1052. "r--", "r-x", "rw-", "rwx"};
  1053. static char bits[11];
  1054. bits[0] = get_fileind(mode, desc);
  1055. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  1056. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  1057. strcpy(&bits[7], rwx[(mode & 7)]);
  1058. if (mode & S_ISUID)
  1059. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1060. if (mode & S_ISGID)
  1061. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1062. if (mode & S_ISVTX)
  1063. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1064. bits[10] = '\0';
  1065. return bits;
  1066. }
  1067. /*
  1068. * Gets only a single line (that's what we need
  1069. * for now) or shows full command output in pager.
  1070. *
  1071. * If pager is valid, returns NULL
  1072. */
  1073. static char *
  1074. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2,
  1075. int pager)
  1076. {
  1077. pid_t pid;
  1078. int pipefd[2];
  1079. FILE *pf;
  1080. int tmp, flags;
  1081. char *ret = NULL;
  1082. if (pipe(pipefd) == -1)
  1083. printerr(1, "pipe(2)");
  1084. for (tmp = 0; tmp < 2; ++tmp) {
  1085. /* Get previous flags */
  1086. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1087. /* Set bit for non-blocking flag */
  1088. flags |= O_NONBLOCK;
  1089. /* Change flags on fd */
  1090. fcntl(pipefd[tmp], F_SETFL, flags);
  1091. }
  1092. pid = fork();
  1093. if (pid == 0) {
  1094. /* In child */
  1095. close(pipefd[0]);
  1096. dup2(pipefd[1], STDOUT_FILENO);
  1097. dup2(pipefd[1], STDERR_FILENO);
  1098. close(pipefd[1]);
  1099. execlp(file, file, arg1, arg2, NULL);
  1100. _exit(1);
  1101. }
  1102. /* In parent */
  1103. waitpid(pid, &tmp, 0);
  1104. close(pipefd[1]);
  1105. if (!pager) {
  1106. pf = fdopen(pipefd[0], "r");
  1107. if (pf) {
  1108. ret = fgets(buf, bytes, pf);
  1109. close(pipefd[0]);
  1110. }
  1111. return ret;
  1112. }
  1113. pid = fork();
  1114. if (pid == 0) {
  1115. /* Show in pager in child */
  1116. dup2(pipefd[0], STDIN_FILENO);
  1117. close(pipefd[0]);
  1118. execlp("less", "less", NULL);
  1119. _exit(1);
  1120. }
  1121. /* In parent */
  1122. waitpid(pid, &tmp, 0);
  1123. close(pipefd[0]);
  1124. return NULL;
  1125. }
  1126. /*
  1127. * Follows the stat(1) output closely
  1128. */
  1129. static int
  1130. show_stats(char *fpath, char *fname, struct stat *sb)
  1131. {
  1132. char *perms = get_lsperms(sb->st_mode, g_buf);
  1133. char *p, *begin = g_buf;
  1134. char tmp[] = "/tmp/nnnXXXXXX";
  1135. int fd = mkstemp(tmp);
  1136. if (fd == -1)
  1137. return -1;
  1138. /* Show file name or 'symlink' -> 'target' */
  1139. if (perms[0] == 'l') {
  1140. /* Note that MAX_CMD_LEN > PATH_MAX */
  1141. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1142. if (len != -1) {
  1143. g_buf[len] = '\0';
  1144. dprintf(fd, " File: '%s' -> ", unescape(fname));
  1145. dprintf(fd, "'%s'", unescape(g_buf));
  1146. xstrlcpy(g_buf, "symbolic link", MAX_CMD_LEN);
  1147. }
  1148. } else
  1149. dprintf(fd, " File: '%s'", unescape(fname));
  1150. /* Show size, blocks, file type */
  1151. #ifdef __APPLE__
  1152. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1153. #else
  1154. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1155. #endif
  1156. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1157. /* Show containing device, inode, hardlink count */
  1158. #ifdef __APPLE__
  1159. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1160. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1161. #else
  1162. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1163. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1164. #endif
  1165. g_buf, sb->st_ino, sb->st_nlink);
  1166. /* Show major, minor number for block or char device */
  1167. if (perms[0] == 'b' || perms[0] == 'c')
  1168. dprintf(fd, " Device type: %x,%x",
  1169. major(sb->st_rdev), minor(sb->st_rdev));
  1170. /* Show permissions, owner, group */
  1171. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1172. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  1173. perms,
  1174. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  1175. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1176. /* Show last access time */
  1177. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1178. dprintf(fd, "\n\n Access: %s", g_buf);
  1179. /* Show last modification time */
  1180. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1181. dprintf(fd, "\n Modify: %s", g_buf);
  1182. /* Show last status change time */
  1183. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1184. dprintf(fd, "\n Change: %s", g_buf);
  1185. if (S_ISREG(sb->st_mode)) {
  1186. /* Show file(1) output */
  1187. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1188. if (p) {
  1189. dprintf(fd, "\n\n ");
  1190. while (*p) {
  1191. if (*p == ',') {
  1192. *p = '\0';
  1193. dprintf(fd, " %s\n", begin);
  1194. begin = p + 1;
  1195. }
  1196. ++p;
  1197. }
  1198. dprintf(fd, " %s", begin);
  1199. }
  1200. dprintf(fd, "\n\n");
  1201. } else
  1202. dprintf(fd, "\n\n\n");
  1203. close(fd);
  1204. exitcurses();
  1205. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1206. unlink(tmp);
  1207. initcurses();
  1208. return 0;
  1209. }
  1210. static int
  1211. show_mediainfo(char *fpath, char *arg)
  1212. {
  1213. if (!get_output(g_buf, MAX_CMD_LEN, "which", metaviewer, NULL, 0))
  1214. return -1;
  1215. exitcurses();
  1216. get_output(NULL, 0, metaviewer, fpath, arg, 1);
  1217. initcurses();
  1218. return 0;
  1219. }
  1220. static int
  1221. show_help(void)
  1222. {
  1223. char tmp[] = "/tmp/nnnXXXXXX";
  1224. static char helpstr[] = ("\
  1225. Key | Function\n\
  1226. -+-\n\
  1227. ↑, k, ^P | Previous entry\n\
  1228. ↓, j, ^N | Next entry\n\
  1229. PgUp, ^U | Scroll half page up\n\
  1230. PgDn, ^D | Scroll half page down\n\
  1231. Home, g, ^, ^A | Jump to first entry\n\
  1232. End, G, $, ^E | Jump to last entry\n\
  1233. →, ↵, l, ^M | Open file or enter dir\n\
  1234. ←, Bksp, h, ^H | Go to parent dir\n\
  1235. Insert | Toggle navigate-as-you-type\n\
  1236. ~ | Jump to HOME dir\n\
  1237. & | Jump to initial dir\n\
  1238. - | Jump to last visited dir\n\
  1239. / | Filter dir contents\n\
  1240. ^/ | Open desktop search tool\n\
  1241. . | Toggle hide .dot files\n\
  1242. b | Show bookmark key prompt\n\
  1243. c | Show change dir prompt\n\
  1244. d | Toggle detail view\n\
  1245. D | Show current file details\n\
  1246. m | Show concise media info\n\
  1247. M | Show full media info\n\
  1248. s | Toggle sort by file size\n\
  1249. S | Toggle disk usage mode\n\
  1250. t | Toggle sort by mtime\n\
  1251. ! | Spawn SHELL in current dir\n\
  1252. e | Edit entry in EDITOR\n\
  1253. o | Open dir in file manager\n\
  1254. p | Open entry in PAGER\n\
  1255. ^K | Invoke file path copier\n\
  1256. ^L, F2 | Force a redraw, unfilter\n\
  1257. ? | Show help, settings\n\
  1258. Q | Quit and change dir\n\
  1259. q, ^Q | Quit\n\n");
  1260. int i = 0, fd = mkstemp(tmp);
  1261. if (fd == -1)
  1262. return -1;
  1263. dprintf(fd, "%s", helpstr);
  1264. if (getenv("NNN_BMS")) {
  1265. dprintf(fd, "BOOKMARKS\n");
  1266. for (; i < MAX_BM; ++i)
  1267. if (bookmark[i].key)
  1268. dprintf(fd, "\t%s: %s\n",
  1269. bookmark[i].key, bookmark[i].loc);
  1270. else
  1271. break;
  1272. dprintf(fd, "\n");
  1273. }
  1274. if (editor)
  1275. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1276. if (desktop_manager)
  1277. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1278. if (idletimeout)
  1279. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1280. if (copier)
  1281. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1282. dprintf(fd, "\n");
  1283. close(fd);
  1284. exitcurses();
  1285. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1286. unlink(tmp);
  1287. initcurses();
  1288. return 0;
  1289. }
  1290. static int
  1291. sum_bsizes(const char *fpath, const struct stat *sb,
  1292. int typeflag, struct FTW *ftwbuf)
  1293. {
  1294. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1295. ent_blocks += sb->st_blocks;
  1296. ++num_files;
  1297. return 0;
  1298. }
  1299. static int
  1300. getorder(size_t size)
  1301. {
  1302. switch (size) {
  1303. case 4096:
  1304. return 12;
  1305. case 512:
  1306. return 9;
  1307. case 8192:
  1308. return 13;
  1309. case 16384:
  1310. return 14;
  1311. case 32768:
  1312. return 15;
  1313. case 65536:
  1314. return 16;
  1315. case 131072:
  1316. return 17;
  1317. case 262144:
  1318. return 18;
  1319. case 524288:
  1320. return 19;
  1321. case 1048576:
  1322. return 20;
  1323. case 2048:
  1324. return 11;
  1325. case 1024:
  1326. return 10;
  1327. default:
  1328. return 0;
  1329. }
  1330. }
  1331. static int
  1332. dentfill(char *path, struct entry **dents,
  1333. int (*filter)(regex_t *, char *), regex_t *re)
  1334. {
  1335. static DIR *dirp;
  1336. static struct dirent *dp;
  1337. static struct stat sb;
  1338. static int fd, n;
  1339. static char *namep;
  1340. static struct entry *dentp;
  1341. dirp = opendir(path);
  1342. if (dirp == NULL)
  1343. return 0;
  1344. fd = dirfd(dirp);
  1345. n = 0;
  1346. if (cfg.blkorder) {
  1347. static struct statvfs svb;
  1348. if (statvfs(path, &svb) == -1)
  1349. fs_free = 0;
  1350. else
  1351. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1352. num_files = 0;
  1353. dir_blocks = 0;
  1354. }
  1355. while ((dp = readdir(dirp)) != NULL) {
  1356. namep = dp->d_name;
  1357. if (filter(re, namep) == 0) {
  1358. if (!cfg.blkorder)
  1359. continue;
  1360. /* Skip self and parent */
  1361. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1362. (namep[1] == '.' && namep[2] == '\0'))))
  1363. continue;
  1364. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW)
  1365. == -1)
  1366. continue;
  1367. if (S_ISDIR(sb.st_mode)) {
  1368. ent_blocks = 0;
  1369. mkpath(path, namep, g_buf, PATH_MAX);
  1370. if (nftw(g_buf, sum_bsizes, open_max,
  1371. FTW_MOUNT | FTW_PHYS) == -1) {
  1372. printmsg(STR_NFTWFAIL);
  1373. dir_blocks += sb.st_blocks;
  1374. } else
  1375. dir_blocks += ent_blocks;
  1376. } else {
  1377. if (sb.st_blocks)
  1378. dir_blocks += sb.st_blocks;
  1379. ++num_files;
  1380. }
  1381. continue;
  1382. }
  1383. /* Skip self and parent */
  1384. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1385. (namep[1] == '.' && namep[2] == '\0'))))
  1386. continue;
  1387. if (fstatat(fd, namep, &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. dentp = &(*dents)[n];
  1399. xstrlcpy(dentp->name, namep, NAME_MAX);
  1400. dentp->mode = sb.st_mode;
  1401. dentp->t = sb.st_mtime;
  1402. dentp->size = sb.st_size;
  1403. if (cfg.blkorder) {
  1404. if (S_ISDIR(sb.st_mode)) {
  1405. ent_blocks = 0;
  1406. mkpath(path, namep, g_buf, PATH_MAX);
  1407. if (nftw(g_buf, sum_bsizes, open_max,
  1408. FTW_MOUNT | FTW_PHYS) == -1) {
  1409. printmsg(STR_NFTWFAIL);
  1410. dentp->blocks = sb.st_blocks;
  1411. } else
  1412. dentp->blocks = ent_blocks;
  1413. } else {
  1414. dentp->blocks = sb.st_blocks;
  1415. ++num_files;
  1416. }
  1417. if (dentp->blocks)
  1418. dir_blocks += dentp->blocks;
  1419. }
  1420. ++n;
  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 (istopdir(path)) {
  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. exitcurses();
  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 (istopdir(path)) {
  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 (istopdir(path)) {
  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 (istopdir(path))
  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] [-p nlay] [-S]\n\
  2087. [-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. -p nlay path to custom nlay\n\
  2097. -S start in disk usage analyzer mode\n\
  2098. -v show program version and exit\n\
  2099. -h show this help and exit\n\n\
  2100. Version: %s\n\
  2101. License: BSD 2-Clause\n\
  2102. Webpage: https://github.com/jarun/nnn\n", VERSION);
  2103. exit(0);
  2104. }
  2105. int
  2106. main(int argc, char *argv[])
  2107. {
  2108. char cwd[PATH_MAX], *ipath;
  2109. char *ifilter, *bmstr;
  2110. int opt;
  2111. /* Confirm we are in a terminal */
  2112. if (!isatty(0) || !isatty(1)) {
  2113. fprintf(stderr, "stdin or stdout is not a tty\n");
  2114. exit(1);
  2115. }
  2116. while ((opt = getopt(argc, argv, "Slic:ep:vh")) != -1) {
  2117. switch (opt) {
  2118. case 'S':
  2119. cfg.blkorder = 1;
  2120. break;
  2121. case 'l':
  2122. cfg.showdetail = 0;
  2123. printptr = &printent;
  2124. break;
  2125. case 'i':
  2126. cfg.filtermode = 1;
  2127. break;
  2128. case 'c':
  2129. color = (uchar)atoi(optarg);
  2130. if (color > 7)
  2131. cfg.showcolor = 0;
  2132. break;
  2133. case 'e':
  2134. metaviewer = utils[3];
  2135. break;
  2136. case 'p':
  2137. player = optarg;
  2138. break;
  2139. case 'v':
  2140. printf("%s\n", VERSION);
  2141. return 0;
  2142. case 'h': // fallthrough
  2143. default:
  2144. usage();
  2145. }
  2146. }
  2147. if (argc == optind) {
  2148. /* Start in the current directory */
  2149. ipath = getcwd(cwd, PATH_MAX);
  2150. if (ipath == NULL)
  2151. ipath = "/";
  2152. } else {
  2153. ipath = realpath(argv[optind], cwd);
  2154. if (!ipath) {
  2155. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2156. exit(1);
  2157. }
  2158. }
  2159. /* Increase current open file descriptor limit */
  2160. open_max = max_openfds();
  2161. if (getuid() == 0)
  2162. cfg.showhidden = 1;
  2163. initfilter(cfg.showhidden, &ifilter);
  2164. /* Parse bookmarks string, if available */
  2165. bmstr = getenv("NNN_BMS");
  2166. if (bmstr)
  2167. parsebmstr(bmstr);
  2168. /* Edit text in EDITOR, if opted */
  2169. if (getenv("NNN_USE_EDITOR"))
  2170. editor = xgetenv("EDITOR", "vi");
  2171. /* Set metadata viewer if not set */
  2172. if (!metaviewer)
  2173. metaviewer = utils[2];
  2174. /* Set player if not set already */
  2175. if (!player)
  2176. player = utils[1];
  2177. /* Get the desktop file browser, if set */
  2178. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2179. /* Get screensaver wait time, if set; copier used as tmp var */
  2180. copier = getenv("NNN_IDLE_TIMEOUT");
  2181. if (copier)
  2182. idletimeout = abs(atoi(copier));
  2183. /* Get the default copier, if set */
  2184. copier = getenv("NNN_COPIER");
  2185. signal(SIGINT, SIG_IGN);
  2186. /* Test initial path */
  2187. if (access(ipath, R_OK) == -1) {
  2188. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2189. exit(1);
  2190. }
  2191. /* Set locale */
  2192. setlocale(LC_ALL, "");
  2193. #ifdef DEBUGMODE
  2194. enabledbg();
  2195. #endif
  2196. initcurses();
  2197. browse(ipath, ifilter);
  2198. exitcurses();
  2199. #ifdef DEBUGMODE
  2200. disabledbg();
  2201. #endif
  2202. exit(0);
  2203. }