My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2584 lines
52 KiB

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