My build of nnn with minor changes
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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