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.
 
 
 
 
 
 

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