My build of nnn with minor changes
 
 
 
 
 
 

2576 lines
52 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. #include <sys/stat.h>
  3. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \
  4. || defined(__APPLE__)
  5. # include <sys/types.h>
  6. #else
  7. # include <sys/sysmacros.h>
  8. #endif
  9. #include <sys/wait.h>
  10. #include <sys/statvfs.h>
  11. #include <sys/resource.h>
  12. #include <ctype.h>
  13. #include <curses.h>
  14. #include <dirent.h>
  15. #include <errno.h>
  16. #include <fcntl.h>
  17. #include <grp.h>
  18. #include <libgen.h>
  19. #include <limits.h>
  20. #ifdef __gnu_hurd__
  21. #define PATH_MAX 4096
  22. #endif
  23. #include <locale.h>
  24. #include <pwd.h>
  25. #include <regex.h>
  26. #include <signal.h>
  27. #include <stdarg.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <time.h>
  32. #include <unistd.h>
  33. #include <wchar.h>
  34. #include <readline/readline.h>
  35. #ifndef __USE_XOPEN_EXTENDED
  36. #define __USE_XOPEN_EXTENDED 1
  37. #endif
  38. #include <ftw.h>
  39. #include "config.h"
  40. #ifdef DEBUGMODE
  41. static int DEBUG_FD;
  42. static int
  43. xprintf(int fd, const char *fmt, ...)
  44. {
  45. char buf[BUFSIZ];
  46. int r;
  47. va_list ap;
  48. va_start(ap, fmt);
  49. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  50. if (r > 0)
  51. r = write(fd, buf, r);
  52. va_end(ap);
  53. return r;
  54. }
  55. static int
  56. enabledbg()
  57. {
  58. FILE *fp = fopen("/tmp/nnn_debug", "w");
  59. if (!fp) {
  60. fprintf(stderr, "Cannot open debug file\n");
  61. return -1;
  62. }
  63. DEBUG_FD = fileno(fp);
  64. if (DEBUG_FD == -1) {
  65. fprintf(stderr, "Cannot open debug file descriptor\n");
  66. return -1;
  67. }
  68. return 0;
  69. }
  70. static void
  71. disabledbg()
  72. {
  73. close(DEBUG_FD);
  74. }
  75. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  76. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  77. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  78. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=0x%p\n", x)
  79. #else
  80. #define DPRINTF_D(x)
  81. #define DPRINTF_U(x)
  82. #define DPRINTF_S(x)
  83. #define DPRINTF_P(x)
  84. #endif /* DEBUGMODE */
  85. /* Macro definitions */
  86. #define VERSION "1.2"
  87. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  88. #undef MIN
  89. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  90. #define ISODD(x) ((x) & 1)
  91. #define TOUPPER(ch) \
  92. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  93. #define MAX_CMD_LEN 5120
  94. #define CWD "cwd: "
  95. #define CURSR " > "
  96. #define EMPTY " "
  97. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  98. #define FILTER '/'
  99. #define MAX_BM 10
  100. /* Macros to define process spawn behaviour as flags */
  101. #define F_NONE 0x00 /* no flag set */
  102. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  103. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  104. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  105. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  106. #define F_NORMAL 0x80 /* spawn child process in non-curses regular mode */
  107. #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. default:
  768. if (len == 1)
  769. cur = oldcur;
  770. goto end;
  771. }
  772. end:
  773. noecho();
  774. curs_set(FALSE);
  775. timeout(1000);
  776. /* Return keys for navigation etc. */
  777. return *ch;
  778. }
  779. /*
  780. * Returns "dir/name or "/name"
  781. */
  782. static char *
  783. mkpath(char *dir, char *name, char *out, size_t n)
  784. {
  785. /* Handle absolute path */
  786. if (name[0] == '/')
  787. xstrlcpy(out, name, n);
  788. else {
  789. /* Handle root case */
  790. if (istopdir(dir))
  791. snprintf(out, n, "/%s", name);
  792. else
  793. snprintf(out, n, "%s/%s", dir, name);
  794. }
  795. return out;
  796. }
  797. static void
  798. parsebmstr(char *bms)
  799. {
  800. int i = 0;
  801. while (*bms && i < MAX_BM) {
  802. bookmark[i].key = bms;
  803. ++bms;
  804. while (*bms && *bms != ':')
  805. ++bms;
  806. if (!*bms) {
  807. bookmark[i].key = NULL;
  808. break;
  809. }
  810. *bms = '\0';
  811. bookmark[i].loc = ++bms;
  812. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  813. bookmark[i].key = NULL;
  814. break;
  815. }
  816. while (*bms && *bms != ';')
  817. ++bms;
  818. if (*bms)
  819. *bms = '\0';
  820. else
  821. break;
  822. ++bms;
  823. ++i;
  824. }
  825. }
  826. static char *
  827. readinput(void)
  828. {
  829. timeout(-1);
  830. echo();
  831. curs_set(TRUE);
  832. memset(g_buf, 0, LINE_MAX);
  833. wgetnstr(stdscr, g_buf, LINE_MAX - 1);
  834. noecho();
  835. curs_set(FALSE);
  836. timeout(1000);
  837. return g_buf[0] ? g_buf : NULL;
  838. }
  839. /*
  840. * Replace escape characters in a string with '?'
  841. */
  842. static char *
  843. unescape(const char *str)
  844. {
  845. static char buffer[PATH_MAX];
  846. static wchar_t wbuf[PATH_MAX];
  847. static wchar_t *buf;
  848. buffer[0] = '\0';
  849. buf = wbuf;
  850. /* Convert multi-byte to wide char */
  851. mbstowcs(wbuf, str, PATH_MAX);
  852. while (*buf) {
  853. if (*buf <= '\x1f' || *buf == '\x7f')
  854. *buf = '\?';
  855. ++buf;
  856. }
  857. /* Convert wide char to multi-byte */
  858. wcstombs(buffer, wbuf, PATH_MAX);
  859. return buffer;
  860. }
  861. static void
  862. printent(struct entry *ent, int sel)
  863. {
  864. static int ncols;
  865. if (PATH_MAX + 16 < COLS)
  866. ncols = PATH_MAX + 16;
  867. else
  868. ncols = COLS;
  869. if (S_ISDIR(ent->mode))
  870. snprintf(g_buf, ncols, "%s%s/", CURSYM(sel),
  871. unescape(ent->name));
  872. else if (S_ISLNK(ent->mode))
  873. snprintf(g_buf, ncols, "%s%s@", CURSYM(sel),
  874. unescape(ent->name));
  875. else if (S_ISSOCK(ent->mode))
  876. snprintf(g_buf, ncols, "%s%s=", CURSYM(sel),
  877. unescape(ent->name));
  878. else if (S_ISFIFO(ent->mode))
  879. snprintf(g_buf, ncols, "%s%s|", CURSYM(sel),
  880. unescape(ent->name));
  881. else if (ent->mode & 0100)
  882. snprintf(g_buf, ncols, "%s%s*", CURSYM(sel),
  883. unescape(ent->name));
  884. else
  885. snprintf(g_buf, ncols, "%s%s", CURSYM(sel),
  886. unescape(ent->name));
  887. /* Dirs are always shown on top */
  888. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  889. attroff(COLOR_PAIR(1) | A_BOLD);
  890. cfg.dircolor = 0;
  891. }
  892. printw("%s\n", g_buf);
  893. }
  894. static char *
  895. coolsize(off_t size)
  896. {
  897. static const char * const U = "BKMGTPEZY";
  898. static char size_buf[12]; /* Buffer to hold human readable size */
  899. static int i;
  900. static off_t tmp;
  901. static long double rem;
  902. i = 0;
  903. rem = 0;
  904. while (size > 1024) {
  905. tmp = size;
  906. size >>= 10;
  907. rem = tmp - (size << 10);
  908. ++i;
  909. }
  910. snprintf(size_buf, 12, "%.*Lf%c", i, size + rem * div_2_pow_10, U[i]);
  911. return size_buf;
  912. }
  913. static void
  914. printent_long(struct entry *ent, int sel)
  915. {
  916. static int ncols;
  917. static char buf[18];
  918. if (PATH_MAX + 32 < COLS)
  919. ncols = PATH_MAX + 32;
  920. else
  921. ncols = COLS;
  922. strftime(buf, 18, "%d %m %Y %H:%M", localtime(&ent->t));
  923. if (sel)
  924. attron(A_REVERSE);
  925. if (!cfg.blkorder) {
  926. if (S_ISDIR(ent->mode))
  927. snprintf(g_buf, ncols, "%s%-16.16s / %s/",
  928. CURSYM(sel), buf, unescape(ent->name));
  929. else if (S_ISLNK(ent->mode))
  930. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  931. CURSYM(sel), buf, unescape(ent->name));
  932. else if (S_ISSOCK(ent->mode))
  933. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  934. CURSYM(sel), buf, unescape(ent->name));
  935. else if (S_ISFIFO(ent->mode))
  936. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  937. CURSYM(sel), buf, unescape(ent->name));
  938. else if (S_ISBLK(ent->mode))
  939. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  940. CURSYM(sel), buf, unescape(ent->name));
  941. else if (S_ISCHR(ent->mode))
  942. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  943. CURSYM(sel), buf, unescape(ent->name));
  944. else if (ent->mode & 0100)
  945. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  946. CURSYM(sel), buf, coolsize(ent->size),
  947. unescape(ent->name));
  948. else
  949. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  950. CURSYM(sel), buf, coolsize(ent->size),
  951. unescape(ent->name));
  952. } else {
  953. if (S_ISDIR(ent->mode))
  954. snprintf(g_buf, ncols, "%s%-16.16s %8.8s/ %s/",
  955. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  956. unescape(ent->name));
  957. else if (S_ISLNK(ent->mode))
  958. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  959. CURSYM(sel), buf,
  960. unescape(ent->name));
  961. else if (S_ISSOCK(ent->mode))
  962. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  963. CURSYM(sel), buf,
  964. unescape(ent->name));
  965. else if (S_ISFIFO(ent->mode))
  966. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  967. CURSYM(sel), buf,
  968. unescape(ent->name));
  969. else if (S_ISBLK(ent->mode))
  970. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  971. CURSYM(sel), buf,
  972. unescape(ent->name));
  973. else if (S_ISCHR(ent->mode))
  974. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  975. CURSYM(sel), buf,
  976. unescape(ent->name));
  977. else if (ent->mode & 0100)
  978. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  979. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  980. unescape(ent->name));
  981. else
  982. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  983. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  984. unescape(ent->name));
  985. }
  986. /* Dirs are always shown on top */
  987. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  988. attroff(COLOR_PAIR(1) | A_BOLD);
  989. cfg.dircolor = 0;
  990. }
  991. printw("%s\n", g_buf);
  992. if (sel)
  993. attroff(A_REVERSE);
  994. }
  995. static void (*printptr)(struct entry *ent, int sel) = &printent_long;
  996. static char
  997. get_fileind(mode_t mode, char *desc)
  998. {
  999. static char c;
  1000. if (S_ISREG(mode)) {
  1001. c = '-';
  1002. sprintf(desc, "%s", "regular file");
  1003. if (mode & 0100)
  1004. strcat(desc, ", executable");
  1005. } else if (S_ISDIR(mode)) {
  1006. c = 'd';
  1007. sprintf(desc, "%s", "directory");
  1008. } else if (S_ISBLK(mode)) {
  1009. c = 'b';
  1010. sprintf(desc, "%s", "block special device");
  1011. } else if (S_ISCHR(mode)) {
  1012. c = 'c';
  1013. sprintf(desc, "%s", "character special device");
  1014. #ifdef S_ISFIFO
  1015. } else if (S_ISFIFO(mode)) {
  1016. c = 'p';
  1017. sprintf(desc, "%s", "FIFO");
  1018. #endif /* S_ISFIFO */
  1019. #ifdef S_ISLNK
  1020. } else if (S_ISLNK(mode)) {
  1021. c = 'l';
  1022. sprintf(desc, "%s", "symbolic link");
  1023. #endif /* S_ISLNK */
  1024. #ifdef S_ISSOCK
  1025. } else if (S_ISSOCK(mode)) {
  1026. c = 's';
  1027. sprintf(desc, "%s", "socket");
  1028. #endif /* S_ISSOCK */
  1029. #ifdef S_ISDOOR
  1030. /* Solaris 2.6, etc. */
  1031. } else if (S_ISDOOR(mode)) {
  1032. c = 'D';
  1033. desc[0] = '\0';
  1034. #endif /* S_ISDOOR */
  1035. } else {
  1036. /* Unknown type -- possibly a regular file? */
  1037. c = '?';
  1038. desc[0] = '\0';
  1039. }
  1040. return c;
  1041. }
  1042. /* Convert a mode field into "ls -l" type perms field. */
  1043. static char *
  1044. get_lsperms(mode_t mode, char *desc)
  1045. {
  1046. static const char * const rwx[] = {"---", "--x", "-w-", "-wx",
  1047. "r--", "r-x", "rw-", "rwx"};
  1048. static char bits[11];
  1049. bits[0] = get_fileind(mode, desc);
  1050. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  1051. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  1052. strcpy(&bits[7], rwx[(mode & 7)]);
  1053. if (mode & S_ISUID)
  1054. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1055. if (mode & S_ISGID)
  1056. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1057. if (mode & S_ISVTX)
  1058. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1059. bits[10] = '\0';
  1060. return bits;
  1061. }
  1062. /*
  1063. * Gets only a single line (that's what we need
  1064. * for now) or shows full command output in pager.
  1065. *
  1066. * If pager is valid, returns NULL
  1067. */
  1068. static char *
  1069. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2,
  1070. int pager)
  1071. {
  1072. pid_t pid;
  1073. int pipefd[2];
  1074. FILE *pf;
  1075. int tmp, flags;
  1076. char *ret = NULL;
  1077. if (pipe(pipefd) == -1)
  1078. printerr(1, "pipe(2)");
  1079. for (tmp = 0; tmp < 2; ++tmp) {
  1080. /* Get previous flags */
  1081. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1082. /* Set bit for non-blocking flag */
  1083. flags |= O_NONBLOCK;
  1084. /* Change flags on fd */
  1085. fcntl(pipefd[tmp], F_SETFL, flags);
  1086. }
  1087. pid = fork();
  1088. if (pid == 0) {
  1089. /* In child */
  1090. close(pipefd[0]);
  1091. dup2(pipefd[1], STDOUT_FILENO);
  1092. dup2(pipefd[1], STDERR_FILENO);
  1093. close(pipefd[1]);
  1094. execlp(file, file, arg1, arg2, NULL);
  1095. _exit(1);
  1096. }
  1097. /* In parent */
  1098. waitpid(pid, &tmp, 0);
  1099. close(pipefd[1]);
  1100. if (!pager) {
  1101. pf = fdopen(pipefd[0], "r");
  1102. if (pf) {
  1103. ret = fgets(buf, bytes, pf);
  1104. close(pipefd[0]);
  1105. }
  1106. return ret;
  1107. }
  1108. pid = fork();
  1109. if (pid == 0) {
  1110. /* Show in pager in child */
  1111. dup2(pipefd[0], STDIN_FILENO);
  1112. close(pipefd[0]);
  1113. execlp("less", "less", NULL);
  1114. _exit(1);
  1115. }
  1116. /* In parent */
  1117. waitpid(pid, &tmp, 0);
  1118. close(pipefd[0]);
  1119. return NULL;
  1120. }
  1121. /*
  1122. * Follows the stat(1) output closely
  1123. */
  1124. static int
  1125. show_stats(char *fpath, char *fname, struct stat *sb)
  1126. {
  1127. char *perms = get_lsperms(sb->st_mode, g_buf);
  1128. char *p, *begin = g_buf;
  1129. char tmp[] = "/tmp/nnnXXXXXX";
  1130. int fd = mkstemp(tmp);
  1131. if (fd == -1)
  1132. return -1;
  1133. /* Show file name or 'symlink' -> 'target' */
  1134. if (perms[0] == 'l') {
  1135. /* Note that MAX_CMD_LEN > PATH_MAX */
  1136. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1137. if (len != -1) {
  1138. g_buf[len] = '\0';
  1139. dprintf(fd, " File: '%s' -> ", unescape(fname));
  1140. dprintf(fd, "'%s'", unescape(g_buf));
  1141. xstrlcpy(g_buf, "symbolic link", MAX_CMD_LEN);
  1142. }
  1143. } else
  1144. dprintf(fd, " File: '%s'", unescape(fname));
  1145. /* Show size, blocks, file type */
  1146. #ifdef __APPLE__
  1147. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1148. #else
  1149. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1150. #endif
  1151. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1152. /* Show containing device, inode, hardlink count */
  1153. #ifdef __APPLE__
  1154. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1155. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1156. #else
  1157. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1158. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1159. #endif
  1160. g_buf, sb->st_ino, sb->st_nlink);
  1161. /* Show major, minor number for block or char device */
  1162. if (perms[0] == 'b' || perms[0] == 'c')
  1163. dprintf(fd, " Device type: %x,%x",
  1164. major(sb->st_rdev), minor(sb->st_rdev));
  1165. /* Show permissions, owner, group */
  1166. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1167. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  1168. perms,
  1169. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  1170. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1171. /* Show last access time */
  1172. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1173. dprintf(fd, "\n\n Access: %s", g_buf);
  1174. /* Show last modification time */
  1175. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1176. dprintf(fd, "\n Modify: %s", g_buf);
  1177. /* Show last status change time */
  1178. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1179. dprintf(fd, "\n Change: %s", g_buf);
  1180. if (S_ISREG(sb->st_mode)) {
  1181. /* Show file(1) output */
  1182. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1183. if (p) {
  1184. dprintf(fd, "\n\n ");
  1185. while (*p) {
  1186. if (*p == ',') {
  1187. *p = '\0';
  1188. dprintf(fd, " %s\n", begin);
  1189. begin = p + 1;
  1190. }
  1191. ++p;
  1192. }
  1193. dprintf(fd, " %s", begin);
  1194. }
  1195. dprintf(fd, "\n\n");
  1196. } else
  1197. dprintf(fd, "\n\n\n");
  1198. close(fd);
  1199. exitcurses();
  1200. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1201. unlink(tmp);
  1202. initcurses();
  1203. return 0;
  1204. }
  1205. static int
  1206. show_mediainfo(char *fpath, char *arg)
  1207. {
  1208. if (!get_output(g_buf, MAX_CMD_LEN, "which", metaviewer, NULL, 0))
  1209. return -1;
  1210. exitcurses();
  1211. get_output(NULL, 0, metaviewer, fpath, arg, 1);
  1212. initcurses();
  1213. return 0;
  1214. }
  1215. static int
  1216. show_help(void)
  1217. {
  1218. char tmp[] = "/tmp/nnnXXXXXX";
  1219. static char helpstr[] = ("\
  1220. Key | Function\n\
  1221. -+-\n\
  1222. ↑, k, ^P | Previous entry\n\
  1223. ↓, j, ^N | Next entry\n\
  1224. PgUp, ^U | Scroll half page up\n\
  1225. PgDn, ^D | Scroll half page down\n\
  1226. Home, g, ^, ^A | Jump to first entry\n\
  1227. End, G, $, ^E | Jump to last entry\n\
  1228. →, ↵, l, ^M | Open file or enter dir\n\
  1229. ←, Bksp, h, ^H | Go to parent dir\n\
  1230. Insert | Toggle navigate-as-you-type\n\
  1231. ~ | Jump to HOME dir\n\
  1232. & | Jump to initial dir\n\
  1233. - | Jump to last visited dir\n\
  1234. / | Filter dir contents\n\
  1235. ^/ | Open desktop search tool\n\
  1236. . | Toggle hide .dot files\n\
  1237. b | Show bookmark key prompt\n\
  1238. c | Show change dir prompt\n\
  1239. d | Toggle detail view\n\
  1240. D | Show current file details\n\
  1241. m | Show concise media info\n\
  1242. M | Show full media info\n\
  1243. s | Toggle sort by file size\n\
  1244. S | Toggle disk usage mode\n\
  1245. t | Toggle sort by mtime\n\
  1246. ! | Spawn SHELL in current dir\n\
  1247. e | Edit entry in EDITOR\n\
  1248. o | Open dir in file manager\n\
  1249. p | Open entry in PAGER\n\
  1250. ^K | Invoke file path copier\n\
  1251. ^L, F2 | Force a redraw, unfilter\n\
  1252. ? | Show help, settings\n\
  1253. Q | Quit and change dir\n\
  1254. q, ^Q | Quit\n\n");
  1255. int i = 0, fd = mkstemp(tmp);
  1256. if (fd == -1)
  1257. return -1;
  1258. dprintf(fd, "%s", helpstr);
  1259. if (getenv("NNN_BMS")) {
  1260. dprintf(fd, "BOOKMARKS\n");
  1261. for (; i < MAX_BM; ++i)
  1262. if (bookmark[i].key)
  1263. dprintf(fd, "\t%s: %s\n",
  1264. bookmark[i].key, bookmark[i].loc);
  1265. else
  1266. break;
  1267. dprintf(fd, "\n");
  1268. }
  1269. if (editor)
  1270. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1271. if (desktop_manager)
  1272. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1273. if (idletimeout)
  1274. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1275. if (copier)
  1276. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1277. dprintf(fd, "\n");
  1278. close(fd);
  1279. exitcurses();
  1280. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1281. unlink(tmp);
  1282. initcurses();
  1283. return 0;
  1284. }
  1285. static int
  1286. sum_bsizes(const char *fpath, const struct stat *sb,
  1287. int typeflag, struct FTW *ftwbuf)
  1288. {
  1289. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1290. ent_blocks += sb->st_blocks;
  1291. ++num_files;
  1292. return 0;
  1293. }
  1294. static int
  1295. getorder(size_t size)
  1296. {
  1297. switch (size) {
  1298. case 4096:
  1299. return 12;
  1300. case 512:
  1301. return 9;
  1302. case 8192:
  1303. return 13;
  1304. case 16384:
  1305. return 14;
  1306. case 32768:
  1307. return 15;
  1308. case 65536:
  1309. return 16;
  1310. case 131072:
  1311. return 17;
  1312. case 262144:
  1313. return 18;
  1314. case 524288:
  1315. return 19;
  1316. case 1048576:
  1317. return 20;
  1318. case 2048:
  1319. return 11;
  1320. case 1024:
  1321. return 10;
  1322. default:
  1323. return 0;
  1324. }
  1325. }
  1326. static int
  1327. dentfill(char *path, struct entry **dents,
  1328. int (*filter)(regex_t *, char *), regex_t *re)
  1329. {
  1330. static DIR *dirp;
  1331. static struct dirent *dp;
  1332. static struct stat sb;
  1333. static int fd, n;
  1334. static char *namep;
  1335. static struct entry *dentp;
  1336. dirp = opendir(path);
  1337. if (dirp == NULL)
  1338. return 0;
  1339. fd = dirfd(dirp);
  1340. n = 0;
  1341. if (cfg.blkorder) {
  1342. static struct statvfs svb;
  1343. if (statvfs(path, &svb) == -1)
  1344. fs_free = 0;
  1345. else
  1346. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1347. num_files = 0;
  1348. dir_blocks = 0;
  1349. }
  1350. while ((dp = readdir(dirp)) != NULL) {
  1351. namep = dp->d_name;
  1352. if (filter(re, namep) == 0) {
  1353. if (!cfg.blkorder)
  1354. continue;
  1355. /* Skip self and parent */
  1356. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1357. (namep[1] == '.' && namep[2] == '\0'))))
  1358. continue;
  1359. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW)
  1360. == -1)
  1361. continue;
  1362. if (S_ISDIR(sb.st_mode)) {
  1363. ent_blocks = 0;
  1364. mkpath(path, namep, g_buf, PATH_MAX);
  1365. if (nftw(g_buf, sum_bsizes, open_max,
  1366. FTW_MOUNT | FTW_PHYS) == -1) {
  1367. printmsg(STR_NFTWFAIL);
  1368. dir_blocks += sb.st_blocks;
  1369. } else
  1370. dir_blocks += ent_blocks;
  1371. } else {
  1372. if (sb.st_blocks)
  1373. dir_blocks += sb.st_blocks;
  1374. ++num_files;
  1375. }
  1376. continue;
  1377. }
  1378. /* Skip self and parent */
  1379. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1380. (namep[1] == '.' && namep[2] == '\0'))))
  1381. continue;
  1382. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1383. if (*dents)
  1384. free(*dents);
  1385. printerr(1, "fstatat");
  1386. }
  1387. if (n == total_dents) {
  1388. total_dents += 64;
  1389. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1390. if (*dents == NULL)
  1391. printerr(1, "realloc");
  1392. }
  1393. dentp = &(*dents)[n];
  1394. xstrlcpy(dentp->name, namep, NAME_MAX);
  1395. dentp->mode = sb.st_mode;
  1396. dentp->t = sb.st_mtime;
  1397. dentp->size = sb.st_size;
  1398. if (cfg.blkorder) {
  1399. if (S_ISDIR(sb.st_mode)) {
  1400. ent_blocks = 0;
  1401. mkpath(path, namep, g_buf, PATH_MAX);
  1402. if (nftw(g_buf, sum_bsizes, open_max,
  1403. FTW_MOUNT | FTW_PHYS) == -1) {
  1404. printmsg(STR_NFTWFAIL);
  1405. dentp->blocks = sb.st_blocks;
  1406. } else
  1407. dentp->blocks = ent_blocks;
  1408. } else {
  1409. dentp->blocks = sb.st_blocks;
  1410. ++num_files;
  1411. }
  1412. if (dentp->blocks)
  1413. dir_blocks += dentp->blocks;
  1414. }
  1415. ++n;
  1416. }
  1417. /* Should never be null */
  1418. if (closedir(dirp) == -1) {
  1419. if (*dents)
  1420. free(*dents);
  1421. printerr(1, "closedir");
  1422. }
  1423. return n;
  1424. }
  1425. static void
  1426. dentfree(struct entry *dents)
  1427. {
  1428. free(dents);
  1429. }
  1430. /* Return the position of the matching entry or 0 otherwise */
  1431. static int
  1432. dentfind(struct entry *dents, int n, char *path)
  1433. {
  1434. if (!path)
  1435. return 0;
  1436. static int i;
  1437. static char *p;
  1438. p = basename(path);
  1439. DPRINTF_S(p);
  1440. for (i = 0; i < n; ++i)
  1441. if (xstrcmp(p, dents[i].name) == 0)
  1442. return i;
  1443. return 0;
  1444. }
  1445. static int
  1446. populate(char *path, char *oldpath, char *fltr)
  1447. {
  1448. static regex_t re;
  1449. /* Can fail when permissions change while browsing */
  1450. if (access(path, R_OK) == -1)
  1451. return -1;
  1452. /* Search filter */
  1453. if (setfilter(&re, fltr) != 0)
  1454. return -1;
  1455. if (cfg.blkorder) {
  1456. printmsg("Calculating...");
  1457. refresh();
  1458. }
  1459. ndents = dentfill(path, &dents, visible, &re);
  1460. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1461. /* Find cur from history */
  1462. cur = dentfind(dents, ndents, oldpath);
  1463. return 0;
  1464. }
  1465. static void
  1466. redraw(char *path)
  1467. {
  1468. static int nlines, i;
  1469. static size_t ncols;
  1470. nlines = MIN(LINES - 4, ndents);
  1471. /* Clean screen */
  1472. erase();
  1473. /* Strip trailing slashes */
  1474. for (i = xstrlen(path) - 1; i > 0; --i)
  1475. if (path[i] == '/')
  1476. path[i] = '\0';
  1477. else
  1478. break;
  1479. DPRINTF_D(cur);
  1480. DPRINTF_S(path);
  1481. /* No text wrapping in cwd line */
  1482. if (!realpath(path, g_buf)) {
  1483. printmsg("Cannot resolve path");
  1484. return;
  1485. }
  1486. ncols = COLS;
  1487. if (ncols > PATH_MAX)
  1488. ncols = PATH_MAX;
  1489. /* - xstrlen(CWD) - 1 = 6 */
  1490. g_buf[ncols - 6] = '\0';
  1491. printw(CWD "%s\n\n", g_buf);
  1492. if (cfg.showcolor) {
  1493. attron(COLOR_PAIR(1) | A_BOLD);
  1494. cfg.dircolor = 1;
  1495. }
  1496. /* Print listing */
  1497. if (cur < (nlines >> 1)) {
  1498. for (i = 0; i < nlines; ++i)
  1499. printptr(&dents[i], i == cur);
  1500. } else if (cur >= ndents - (nlines >> 1)) {
  1501. for (i = ndents - nlines; i < ndents; ++i)
  1502. printptr(&dents[i], i == cur);
  1503. } else {
  1504. static int odd;
  1505. odd = ISODD(nlines);
  1506. nlines >>= 1;
  1507. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1508. printptr(&dents[i], i == cur);
  1509. }
  1510. /* Must reset e.g. no files in dir */
  1511. if (cfg.dircolor) {
  1512. attroff(COLOR_PAIR(1) | A_BOLD);
  1513. cfg.dircolor = 0;
  1514. }
  1515. if (cfg.showdetail) {
  1516. if (ndents) {
  1517. static char ind[2] = "\0\0";
  1518. static char sort[9];
  1519. if (cfg.mtimeorder)
  1520. sprintf(sort, "by time ");
  1521. else if (cfg.sizeorder)
  1522. sprintf(sort, "by size ");
  1523. else
  1524. sort[0] = '\0';
  1525. if (S_ISDIR(dents[cur].mode))
  1526. ind[0] = '/';
  1527. else if (S_ISLNK(dents[cur].mode))
  1528. ind[0] = '@';
  1529. else if (S_ISSOCK(dents[cur].mode))
  1530. ind[0] = '=';
  1531. else if (S_ISFIFO(dents[cur].mode))
  1532. ind[0] = '|';
  1533. else if (dents[cur].mode & 0100)
  1534. ind[0] = '*';
  1535. else
  1536. ind[0] = '\0';
  1537. /* We need to show filename as it may
  1538. * be truncated in directory listing
  1539. */
  1540. if (!cfg.blkorder)
  1541. sprintf(g_buf, "total %d %s[%s%s]", ndents,
  1542. sort, unescape(dents[cur].name), ind);
  1543. else {
  1544. i = sprintf(g_buf, "du: %s (%lu files) ",
  1545. coolsize(dir_blocks << 9),
  1546. num_files);
  1547. sprintf(g_buf + i, "vol: %s free [%s%s]",
  1548. coolsize(fs_free),
  1549. unescape(dents[cur].name), ind);
  1550. }
  1551. printmsg(g_buf);
  1552. } else
  1553. printmsg("0 items");
  1554. }
  1555. }
  1556. static void
  1557. browse(char *ipath, char *ifilter)
  1558. {
  1559. char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1560. char lastdir[PATH_MAX];
  1561. char fltr[LINE_MAX];
  1562. char *dir, *tmp, *run, *env, *tgt = NULL;
  1563. struct stat sb;
  1564. int r, fd, presel;
  1565. enum action sel = SEL_RUNARG + 1;
  1566. xstrlcpy(path, ipath, PATH_MAX);
  1567. xstrlcpy(fltr, ifilter, LINE_MAX);
  1568. oldpath[0] = '\0';
  1569. newpath[0] = '\0';
  1570. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1571. if (cfg.filtermode)
  1572. presel = FILTER;
  1573. else
  1574. presel = 0;
  1575. begin:
  1576. if (populate(path, oldpath, fltr) == -1) {
  1577. printwarn();
  1578. goto nochange;
  1579. }
  1580. for (;;) {
  1581. redraw(path);
  1582. nochange:
  1583. /* Exit if parent has exited */
  1584. if (getppid() == 1)
  1585. _exit(0);
  1586. sel = nextsel(&run, &env, &presel);
  1587. switch (sel) {
  1588. case SEL_CDQUIT:
  1589. {
  1590. char *tmpfile = "/tmp/nnn";
  1591. tmp = getenv("NNN_TMPFILE");
  1592. if (tmp)
  1593. tmpfile = tmp;
  1594. FILE *fp = fopen(tmpfile, "w");
  1595. if (fp) {
  1596. fprintf(fp, "cd \"%s\"", path);
  1597. fclose(fp);
  1598. }
  1599. /* Fall through to exit */
  1600. } // fallthrough
  1601. case SEL_QUIT:
  1602. dentfree(dents);
  1603. return;
  1604. case SEL_BACK:
  1605. /* There is no going back */
  1606. if (istopdir(path)) {
  1607. printmsg(STR_ATROOT);
  1608. goto nochange;
  1609. }
  1610. dir = xdirname(path);
  1611. if (access(dir, R_OK) == -1) {
  1612. printwarn();
  1613. goto nochange;
  1614. }
  1615. /* Save history */
  1616. xstrlcpy(oldpath, path, PATH_MAX);
  1617. /* Save last working directory */
  1618. xstrlcpy(lastdir, path, PATH_MAX);
  1619. xstrlcpy(path, dir, PATH_MAX);
  1620. /* Reset filter */
  1621. xstrlcpy(fltr, ifilter, LINE_MAX);
  1622. if (cfg.filtermode)
  1623. presel = FILTER;
  1624. goto begin;
  1625. case SEL_GOIN:
  1626. /* Cannot descend in empty directories */
  1627. if (ndents == 0)
  1628. goto begin;
  1629. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1630. DPRINTF_S(newpath);
  1631. /* Get path info */
  1632. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1633. if (fd == -1) {
  1634. printwarn();
  1635. goto nochange;
  1636. }
  1637. r = fstat(fd, &sb);
  1638. if (r == -1) {
  1639. printwarn();
  1640. close(fd);
  1641. goto nochange;
  1642. }
  1643. close(fd);
  1644. DPRINTF_U(sb.st_mode);
  1645. switch (sb.st_mode & S_IFMT) {
  1646. case S_IFDIR:
  1647. if (access(newpath, R_OK) == -1) {
  1648. printwarn();
  1649. goto nochange;
  1650. }
  1651. /* Save last working directory */
  1652. xstrlcpy(lastdir, path, PATH_MAX);
  1653. xstrlcpy(path, newpath, PATH_MAX);
  1654. oldpath[0] = '\0';
  1655. /* Reset filter */
  1656. xstrlcpy(fltr, ifilter, LINE_MAX);
  1657. if (cfg.filtermode)
  1658. presel = FILTER;
  1659. goto begin;
  1660. case S_IFREG:
  1661. {
  1662. /* If NNN_USE_EDITOR is set,
  1663. * open text in EDITOR
  1664. */
  1665. if (editor) {
  1666. if (getmime(dents[cur].name)) {
  1667. spawn(editor, newpath, NULL,
  1668. NULL, F_NORMAL);
  1669. continue;
  1670. }
  1671. /* Recognize and open plain
  1672. * text files with vi
  1673. */
  1674. if (get_output(g_buf, MAX_CMD_LEN,
  1675. "file", "-bi",
  1676. newpath, 0) == NULL)
  1677. continue;
  1678. if (strstr(g_buf, "text/") == g_buf) {
  1679. spawn(editor, newpath, NULL,
  1680. NULL, F_NORMAL);
  1681. continue;
  1682. }
  1683. }
  1684. /* Invoke desktop opener as last resort */
  1685. spawn(utils[0], newpath, NULL, NULL, F_NOTRACE);
  1686. continue;
  1687. }
  1688. default:
  1689. printmsg("Unsupported file");
  1690. goto nochange;
  1691. }
  1692. case SEL_FLTR:
  1693. presel = readln(path);
  1694. xstrlcpy(fltr, ifilter, LINE_MAX);
  1695. DPRINTF_S(fltr);
  1696. /* Save current */
  1697. if (ndents > 0)
  1698. mkpath(path, dents[cur].name, oldpath,
  1699. PATH_MAX);
  1700. goto nochange;
  1701. case SEL_MFLTR:
  1702. cfg.filtermode ^= 1;
  1703. if (cfg.filtermode)
  1704. presel = FILTER;
  1705. else
  1706. printmsg("navigate-as-you-type off");
  1707. goto nochange;
  1708. case SEL_SEARCH:
  1709. spawn(player, path, "search", NULL, F_NORMAL);
  1710. break;
  1711. case SEL_NEXT:
  1712. if (cur < ndents - 1)
  1713. ++cur;
  1714. else if (ndents)
  1715. /* Roll over, set cursor to first entry */
  1716. cur = 0;
  1717. break;
  1718. case SEL_PREV:
  1719. if (cur > 0)
  1720. --cur;
  1721. else if (ndents)
  1722. /* Roll over, set cursor to last entry */
  1723. cur = ndents - 1;
  1724. break;
  1725. case SEL_PGDN:
  1726. if (cur < ndents - 1)
  1727. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1728. break;
  1729. case SEL_PGUP:
  1730. if (cur > 0)
  1731. cur -= MIN((LINES - 4) / 2, cur);
  1732. break;
  1733. case SEL_HOME:
  1734. cur = 0;
  1735. break;
  1736. case SEL_END:
  1737. cur = ndents - 1;
  1738. break;
  1739. case SEL_CD:
  1740. {
  1741. static char *input;
  1742. static int truecd;
  1743. /* Save the program start dir */
  1744. tmp = getcwd(newpath, PATH_MAX);
  1745. if (tmp == NULL) {
  1746. printwarn();
  1747. goto nochange;
  1748. }
  1749. /* Switch to current path for readline(3) */
  1750. if (chdir(path) == -1) {
  1751. printwarn();
  1752. goto nochange;
  1753. }
  1754. exitcurses();
  1755. tmp = readline("chdir: ");
  1756. initcurses();
  1757. /* Change back to program start dir */
  1758. if (chdir(newpath) == -1)
  1759. printwarn();
  1760. if (tmp[0] == '\0')
  1761. break;
  1762. /* Add to readline(3) history */
  1763. add_history(tmp);
  1764. input = tmp;
  1765. tmp = strstrip(tmp);
  1766. if (tmp[0] == '\0') {
  1767. free(input);
  1768. break;
  1769. }
  1770. truecd = 0;
  1771. if (tmp[0] == '~') {
  1772. /* Expand ~ to HOME absolute path */
  1773. char *home = getenv("HOME");
  1774. if (home)
  1775. snprintf(newpath, PATH_MAX, "%s%s",
  1776. home, tmp + 1);
  1777. else {
  1778. free(input);
  1779. printmsg(STR_NOHOME);
  1780. goto nochange;
  1781. }
  1782. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1783. if (lastdir[0] == '\0') {
  1784. free(input);
  1785. break;
  1786. }
  1787. /* Switch to last visited dir */
  1788. xstrlcpy(newpath, lastdir, PATH_MAX);
  1789. truecd = 1;
  1790. } else if ((r = all_dots(tmp))) {
  1791. if (r == 1) {
  1792. /* Always in the current dir */
  1793. free(input);
  1794. break;
  1795. }
  1796. /* Show a message if already at / */
  1797. if (istopdir(path)) {
  1798. printmsg(STR_ATROOT);
  1799. free(input);
  1800. goto nochange;
  1801. }
  1802. --r; /* One . for the current dir */
  1803. dir = path;
  1804. /* Note: fd is used as a tmp variable here */
  1805. for (fd = 0; fd < r; ++fd) {
  1806. /* Reached / ? */
  1807. if (istopdir(path)) {
  1808. /* Can't cd beyond / */
  1809. break;
  1810. }
  1811. dir = xdirname(dir);
  1812. if (access(dir, R_OK) == -1) {
  1813. printwarn();
  1814. free(input);
  1815. goto nochange;
  1816. }
  1817. }
  1818. truecd = 1;
  1819. /* Save the path in case of cd ..
  1820. * We mark the current dir in parent dir
  1821. */
  1822. if (r == 1) {
  1823. xstrlcpy(oldpath, path, PATH_MAX);
  1824. truecd = 2;
  1825. }
  1826. xstrlcpy(newpath, dir, PATH_MAX);
  1827. } else
  1828. mkpath(path, tmp, newpath, PATH_MAX);
  1829. free(input);
  1830. if (access(newpath, R_OK) == -1) {
  1831. printwarn();
  1832. break;
  1833. }
  1834. if (truecd == 0) {
  1835. /* Probable change in dir */
  1836. /* No-op if it's the same directory */
  1837. if (xstrcmp(path, newpath) == 0)
  1838. break;
  1839. oldpath[0] = '\0';
  1840. } else if (truecd == 1)
  1841. /* Sure change in dir */
  1842. oldpath[0] = '\0';
  1843. /* Save last working directory */
  1844. xstrlcpy(lastdir, path, PATH_MAX);
  1845. /* Save the newly opted dir in path */
  1846. xstrlcpy(path, newpath, PATH_MAX);
  1847. /* Reset filter */
  1848. xstrlcpy(fltr, ifilter, LINE_MAX);
  1849. DPRINTF_S(path);
  1850. if (cfg.filtermode)
  1851. presel = FILTER;
  1852. goto begin;
  1853. }
  1854. case SEL_CDHOME:
  1855. tgt = getenv("HOME");
  1856. if (tgt == NULL) {
  1857. clearprompt();
  1858. goto nochange;
  1859. } // fallthrough
  1860. case SEL_CDBEGIN:
  1861. if (!tgt)
  1862. tgt = ipath;
  1863. if (access(tgt, R_OK) == -1) {
  1864. printwarn();
  1865. tgt = NULL;
  1866. goto nochange;
  1867. }
  1868. if (xstrcmp(path, tgt) == 0) {
  1869. tgt = NULL;
  1870. break;
  1871. }
  1872. /* Save last working directory */
  1873. xstrlcpy(lastdir, path, PATH_MAX);
  1874. xstrlcpy(path, tgt, PATH_MAX);
  1875. oldpath[0] = '\0';
  1876. /* Reset filter */
  1877. xstrlcpy(fltr, ifilter, LINE_MAX);
  1878. DPRINTF_S(path);
  1879. if (cfg.filtermode)
  1880. presel = FILTER;
  1881. tgt = NULL;
  1882. goto begin;
  1883. case SEL_CDLAST:
  1884. if (lastdir[0] == '\0') {
  1885. printmsg("Hit end of history...");
  1886. goto nochange;
  1887. }
  1888. if (access(lastdir, R_OK) == -1) {
  1889. printwarn();
  1890. goto nochange;
  1891. }
  1892. xstrlcpy(newpath, lastdir, PATH_MAX);
  1893. xstrlcpy(lastdir, path, PATH_MAX);
  1894. xstrlcpy(path, newpath, PATH_MAX);
  1895. oldpath[0] = '\0';
  1896. /* Reset filter */
  1897. xstrlcpy(fltr, ifilter, LINE_MAX);
  1898. DPRINTF_S(path);
  1899. if (cfg.filtermode)
  1900. presel = FILTER;
  1901. goto begin;
  1902. case SEL_CDBM:
  1903. printprompt("key: ");
  1904. tmp = readinput();
  1905. clearprompt();
  1906. if (tmp == NULL)
  1907. goto nochange;
  1908. for (r = 0; bookmark[r].key && r < MAX_BM; ++r) {
  1909. if (xstrcmp(bookmark[r].key, tmp) == -1)
  1910. continue;
  1911. if (bookmark[r].loc[0] == '~') {
  1912. /* Expand ~ to HOME */
  1913. char *home = getenv("HOME");
  1914. if (home)
  1915. snprintf(newpath,
  1916. PATH_MAX,
  1917. "%s%s",
  1918. home,
  1919. bookmark[r].loc
  1920. + 1);
  1921. else {
  1922. printmsg(STR_NOHOME);
  1923. goto nochange;
  1924. }
  1925. } else
  1926. mkpath(path, bookmark[r].loc,
  1927. newpath, PATH_MAX);
  1928. if (access(newpath, R_OK) == -1) {
  1929. printwarn();
  1930. goto nochange;
  1931. }
  1932. if (xstrcmp(path, newpath) == 0)
  1933. break;
  1934. oldpath[0] = '\0';
  1935. break;
  1936. }
  1937. if (!bookmark[r].key) {
  1938. printmsg("No matching bookmark");
  1939. goto nochange;
  1940. }
  1941. /* Save last working directory */
  1942. xstrlcpy(lastdir, path, PATH_MAX);
  1943. /* Save the newly opted dir in path */
  1944. xstrlcpy(path, newpath, PATH_MAX);
  1945. /* Reset filter */
  1946. xstrlcpy(fltr, ifilter, LINE_MAX);
  1947. DPRINTF_S(path);
  1948. if (cfg.filtermode)
  1949. presel = FILTER;
  1950. goto begin;
  1951. case SEL_TOGGLEDOT:
  1952. cfg.showhidden ^= 1;
  1953. initfilter(cfg.showhidden, &ifilter);
  1954. xstrlcpy(fltr, ifilter, LINE_MAX);
  1955. goto begin;
  1956. case SEL_DETAIL:
  1957. cfg.showdetail ^= 1;
  1958. cfg.showdetail ? (printptr = &printent_long)
  1959. : (printptr = &printent);
  1960. /* Save current */
  1961. if (ndents > 0)
  1962. mkpath(path, dents[cur].name, oldpath,
  1963. PATH_MAX);
  1964. goto begin;
  1965. case SEL_STATS:
  1966. {
  1967. struct stat sb;
  1968. if (ndents > 0) {
  1969. mkpath(path, dents[cur].name, oldpath,
  1970. PATH_MAX);
  1971. r = lstat(oldpath, &sb);
  1972. if (r == -1) {
  1973. if (dents)
  1974. dentfree(dents);
  1975. printerr(1, "lstat");
  1976. } else {
  1977. r = show_stats(oldpath, dents[cur].name,
  1978. &sb);
  1979. if (r < 0) {
  1980. printmsg(strerror(errno));
  1981. goto nochange;
  1982. }
  1983. }
  1984. }
  1985. break;
  1986. }
  1987. case SEL_MEDIA: // fallthrough
  1988. case SEL_FMEDIA:
  1989. if (ndents > 0) {
  1990. mkpath(path, dents[cur].name, oldpath,
  1991. PATH_MAX);
  1992. if (show_mediainfo(oldpath, run) == -1) {
  1993. sprintf(g_buf, "%s missing", metaviewer);
  1994. printmsg(g_buf);
  1995. goto nochange;
  1996. }
  1997. }
  1998. break;
  1999. case SEL_DFB:
  2000. if (!desktop_manager) {
  2001. printmsg("NNN_DE_FILE_MANAGER not set");
  2002. goto nochange;
  2003. }
  2004. spawn(desktop_manager, path, NULL, path,
  2005. F_NOTRACE | F_NOWAIT);
  2006. break;
  2007. case SEL_FSIZE:
  2008. cfg.sizeorder ^= 1;
  2009. cfg.mtimeorder = 0;
  2010. cfg.blkorder = 0;
  2011. /* Save current */
  2012. if (ndents > 0)
  2013. mkpath(path, dents[cur].name, oldpath,
  2014. PATH_MAX);
  2015. goto begin;
  2016. case SEL_BSIZE:
  2017. cfg.blkorder ^= 1;
  2018. if (cfg.blkorder) {
  2019. cfg.showdetail = 1;
  2020. printptr = &printent_long;
  2021. }
  2022. cfg.mtimeorder = 0;
  2023. cfg.sizeorder = 0;
  2024. /* Save current */
  2025. if (ndents > 0)
  2026. mkpath(path, dents[cur].name, oldpath,
  2027. PATH_MAX);
  2028. goto begin;
  2029. case SEL_MTIME:
  2030. cfg.mtimeorder ^= 1;
  2031. cfg.sizeorder = 0;
  2032. cfg.blkorder = 0;
  2033. /* Save current */
  2034. if (ndents > 0)
  2035. mkpath(path, dents[cur].name, oldpath,
  2036. PATH_MAX);
  2037. goto begin;
  2038. case SEL_REDRAW:
  2039. /* Save current */
  2040. if (ndents > 0)
  2041. mkpath(path, dents[cur].name, oldpath,
  2042. PATH_MAX);
  2043. goto begin;
  2044. case SEL_COPY:
  2045. if (copier && ndents) {
  2046. if (istopdir(path))
  2047. snprintf(newpath, PATH_MAX, "/%s",
  2048. dents[cur].name);
  2049. else
  2050. snprintf(newpath, PATH_MAX, "%s/%s",
  2051. path, dents[cur].name);
  2052. spawn(copier, newpath, NULL, NULL, F_NONE);
  2053. printmsg(newpath);
  2054. } else if (!copier)
  2055. printmsg("NNN_COPIER is not set");
  2056. goto nochange;
  2057. case SEL_HELP:
  2058. show_help();
  2059. break;
  2060. case SEL_RUN:
  2061. run = xgetenv(env, run);
  2062. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2063. /* Repopulate as directory content may have changed */
  2064. goto begin;
  2065. case SEL_RUNARG:
  2066. run = xgetenv(env, run);
  2067. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2068. break;
  2069. }
  2070. /* Screensaver */
  2071. if (idletimeout != 0 && idle == idletimeout) {
  2072. idle = 0;
  2073. spawn(player, "", "screensaver", NULL,
  2074. F_NORMAL | F_SIGINT);
  2075. }
  2076. }
  2077. }
  2078. static void
  2079. usage(void)
  2080. {
  2081. printf("usage: nnn [-c N] [-e] [-i] [-l] [-p nlay] [-S]\n\
  2082. [-v] [-h] [PATH]\n\n\
  2083. The missing terminal file browser for X.\n\n\
  2084. positional arguments:\n\
  2085. PATH directory to open [default: current dir]\n\n\
  2086. optional arguments:\n\
  2087. -c N specify dir color, disables if N>7\n\
  2088. -e use exiftool instead of mediainfo\n\
  2089. -i start in navigate-as-you-type mode\n\
  2090. -l start in light mode (fewer details)\n\
  2091. -p nlay path to custom nlay\n\
  2092. -S start in disk usage analyzer mode\n\
  2093. -v show program version and exit\n\
  2094. -h show this help and exit\n\n\
  2095. Version: %s\n\
  2096. License: BSD 2-Clause\n\
  2097. Webpage: https://github.com/jarun/nnn\n", VERSION);
  2098. exit(0);
  2099. }
  2100. int
  2101. main(int argc, char *argv[])
  2102. {
  2103. char cwd[PATH_MAX], *ipath;
  2104. char *ifilter, *bmstr;
  2105. int opt;
  2106. /* Confirm we are in a terminal */
  2107. if (!isatty(0) || !isatty(1)) {
  2108. fprintf(stderr, "stdin or stdout is not a tty\n");
  2109. exit(1);
  2110. }
  2111. while ((opt = getopt(argc, argv, "Slic:ep:vh")) != -1) {
  2112. switch (opt) {
  2113. case 'S':
  2114. cfg.blkorder = 1;
  2115. break;
  2116. case 'l':
  2117. cfg.showdetail = 0;
  2118. printptr = &printent;
  2119. break;
  2120. case 'i':
  2121. cfg.filtermode = 1;
  2122. break;
  2123. case 'c':
  2124. color = (uchar)atoi(optarg);
  2125. if (color > 7)
  2126. cfg.showcolor = 0;
  2127. break;
  2128. case 'e':
  2129. metaviewer = utils[3];
  2130. break;
  2131. case 'p':
  2132. player = optarg;
  2133. break;
  2134. case 'v':
  2135. printf("%s\n", VERSION);
  2136. return 0;
  2137. case 'h': // fallthrough
  2138. default:
  2139. usage();
  2140. }
  2141. }
  2142. if (argc == optind) {
  2143. /* Start in the current directory */
  2144. ipath = getcwd(cwd, PATH_MAX);
  2145. if (ipath == NULL)
  2146. ipath = "/";
  2147. } else {
  2148. ipath = realpath(argv[optind], cwd);
  2149. if (!ipath) {
  2150. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2151. exit(1);
  2152. }
  2153. }
  2154. /* Increase current open file descriptor limit */
  2155. open_max = max_openfds();
  2156. if (getuid() == 0)
  2157. cfg.showhidden = 1;
  2158. initfilter(cfg.showhidden, &ifilter);
  2159. /* Parse bookmarks string, if available */
  2160. bmstr = getenv("NNN_BMS");
  2161. if (bmstr)
  2162. parsebmstr(bmstr);
  2163. /* Edit text in EDITOR, if opted */
  2164. if (getenv("NNN_USE_EDITOR"))
  2165. editor = xgetenv("EDITOR", "vi");
  2166. /* Set metadata viewer if not set */
  2167. if (!metaviewer)
  2168. metaviewer = utils[2];
  2169. /* Set player if not set already */
  2170. if (!player)
  2171. player = utils[1];
  2172. /* Get the desktop file browser, if set */
  2173. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2174. /* Get screensaver wait time, if set; copier used as tmp var */
  2175. copier = getenv("NNN_IDLE_TIMEOUT");
  2176. if (copier)
  2177. idletimeout = abs(atoi(copier));
  2178. /* Get the default copier, if set */
  2179. copier = getenv("NNN_COPIER");
  2180. signal(SIGINT, SIG_IGN);
  2181. /* Test initial path */
  2182. if (access(ipath, R_OK) == -1) {
  2183. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2184. exit(1);
  2185. }
  2186. /* Set locale */
  2187. setlocale(LC_ALL, "");
  2188. #ifdef DEBUGMODE
  2189. enabledbg();
  2190. #endif
  2191. initcurses();
  2192. browse(ipath, ifilter);
  2193. exitcurses();
  2194. #ifdef DEBUGMODE
  2195. disabledbg();
  2196. #endif
  2197. exit(0);
  2198. }