My build of nnn with minor changes
 
 
 
 
 
 

2599 wiersze
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 tmp, flags;
  1090. char *ret = NULL;
  1091. if (pipe(pipefd) == -1)
  1092. printerr(1, "pipe(2)");
  1093. for (tmp = 0; tmp < 2; ++tmp) {
  1094. /* Get previous flags */
  1095. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1096. /* Set bit for non-blocking flag */
  1097. flags |= O_NONBLOCK;
  1098. /* Change flags on fd */
  1099. fcntl(pipefd[tmp], F_SETFL, flags);
  1100. }
  1101. pid = fork();
  1102. if (pid == 0) {
  1103. /* In child */
  1104. close(pipefd[0]);
  1105. dup2(pipefd[1], STDOUT_FILENO);
  1106. dup2(pipefd[1], STDERR_FILENO);
  1107. close(pipefd[1]);
  1108. execlp(file, file, arg1, arg2, NULL);
  1109. _exit(1);
  1110. }
  1111. /* In parent */
  1112. waitpid(pid, &tmp, 0);
  1113. close(pipefd[1]);
  1114. if (!pager) {
  1115. pf = fdopen(pipefd[0], "r");
  1116. if (pf) {
  1117. ret = fgets(buf, bytes, pf);
  1118. close(pipefd[0]);
  1119. }
  1120. return ret;
  1121. }
  1122. pid = fork();
  1123. if (pid == 0) {
  1124. /* Show in pager in child */
  1125. dup2(pipefd[0], STDIN_FILENO);
  1126. close(pipefd[0]);
  1127. execlp("less", "less", NULL);
  1128. _exit(1);
  1129. }
  1130. /* In parent */
  1131. waitpid(pid, &tmp, 0);
  1132. close(pipefd[0]);
  1133. return NULL;
  1134. }
  1135. /*
  1136. * Follows the stat(1) output closely
  1137. */
  1138. static int
  1139. show_stats(char *fpath, char *fname, struct stat *sb)
  1140. {
  1141. char *perms = get_lsperms(sb->st_mode, g_buf);
  1142. char *p, *begin = g_buf;
  1143. char tmp[] = "/tmp/nnnXXXXXX";
  1144. int fd = mkstemp(tmp);
  1145. if (fd == -1)
  1146. return -1;
  1147. /* Show file name or 'symlink' -> 'target' */
  1148. if (perms[0] == 'l') {
  1149. /* Note that MAX_CMD_LEN > PATH_MAX */
  1150. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1151. if (len != -1) {
  1152. g_buf[len] = '\0';
  1153. dprintf(fd, " File: '%s' -> ", unescape(fname));
  1154. dprintf(fd, "'%s'", unescape(g_buf));
  1155. xstrlcpy(g_buf, "symbolic link", MAX_CMD_LEN);
  1156. }
  1157. } else
  1158. dprintf(fd, " File: '%s'", unescape(fname));
  1159. /* Show size, blocks, file type */
  1160. #ifdef __APPLE__
  1161. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1162. #else
  1163. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1164. #endif
  1165. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1166. /* Show containing device, inode, hardlink count */
  1167. #ifdef __APPLE__
  1168. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1169. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1170. #else
  1171. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1172. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1173. #endif
  1174. g_buf, sb->st_ino, sb->st_nlink);
  1175. /* Show major, minor number for block or char device */
  1176. if (perms[0] == 'b' || perms[0] == 'c')
  1177. dprintf(fd, " Device type: %x,%x",
  1178. major(sb->st_rdev), minor(sb->st_rdev));
  1179. /* Show permissions, owner, group */
  1180. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1181. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  1182. perms,
  1183. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  1184. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1185. /* Show last access time */
  1186. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1187. dprintf(fd, "\n\n Access: %s", g_buf);
  1188. /* Show last modification time */
  1189. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1190. dprintf(fd, "\n Modify: %s", g_buf);
  1191. /* Show last status change time */
  1192. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1193. dprintf(fd, "\n Change: %s", g_buf);
  1194. if (S_ISREG(sb->st_mode)) {
  1195. /* Show file(1) output */
  1196. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1197. if (p) {
  1198. dprintf(fd, "\n\n ");
  1199. while (*p) {
  1200. if (*p == ',') {
  1201. *p = '\0';
  1202. dprintf(fd, " %s\n", begin);
  1203. begin = p + 1;
  1204. }
  1205. ++p;
  1206. }
  1207. dprintf(fd, " %s", begin);
  1208. }
  1209. dprintf(fd, "\n\n");
  1210. } else
  1211. dprintf(fd, "\n\n\n");
  1212. close(fd);
  1213. exitcurses();
  1214. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1215. unlink(tmp);
  1216. initcurses();
  1217. return 0;
  1218. }
  1219. static int
  1220. show_mediainfo(char *fpath, char *arg)
  1221. {
  1222. if (!get_output(g_buf, MAX_CMD_LEN, "which", "mediainfo", NULL, 0))
  1223. return -1;
  1224. exitcurses();
  1225. get_output(NULL, 0, "mediainfo", fpath, arg, 1);
  1226. initcurses();
  1227. return 0;
  1228. }
  1229. static int
  1230. show_help(void)
  1231. {
  1232. char tmp[] = "/tmp/nnnXXXXXX";
  1233. static char helpstr[] = ("\
  1234. Key | Function\n\
  1235. -+-\n\
  1236. Up, k, ^P | Previous entry\n\
  1237. Down, j, ^N | Next entry\n\
  1238. PgUp, ^U | Scroll half page up\n\
  1239. PgDn, ^D | Scroll half page down\n\
  1240. Home, g, ^, ^A | Jump to first entry\n\
  1241. End, G, $, ^E | Jump to last entry\n\
  1242. Right, Enter, l, ^M | Open file or enter dir\n\
  1243. Left, Bksp, h, ^H | Go to parent dir\n\
  1244. Insert | Toggle navigate-as-you-type mode\n\
  1245. ~ | Jump to HOME dir\n\
  1246. & | Jump to initial dir\n\
  1247. - | Jump to last visited dir\n\
  1248. / | Filter dir contents\n\
  1249. ^/ | Search dir in desktop search tool\n\
  1250. . | Toggle hide .dot files\n\
  1251. b | Show bookmark key prompt\n\
  1252. c | Show change dir prompt\n\
  1253. d | Toggle detail view\n\
  1254. D | Toggle current file details screen\n\
  1255. m | Show concise mediainfo\n\
  1256. M | Show full mediainfo\n\
  1257. s | Toggle sort by file size\n\
  1258. S | Toggle disk usage analyzer mode\n\
  1259. t | Toggle sort by modified time\n\
  1260. ! | Spawn SHELL in PWD (fallback sh)\n\
  1261. e | Edit entry in EDITOR (fallback vi)\n\
  1262. o | Open dir in NNN_DE_FILE_MANAGER\n\
  1263. p | Open entry in PAGER (fallback less)\n\
  1264. ^K | Invoke file path copier\n\
  1265. ^L, F2 | Force a redraw, exit filter prompt\n\
  1266. ? | Toggle help and settings screen\n\
  1267. Q | Quit and change directory\n\
  1268. q, ^Q | Quit\n\n\n");
  1269. int i = 0, fd = mkstemp(tmp);
  1270. if (fd == -1)
  1271. return -1;
  1272. dprintf(fd, "%s", helpstr);
  1273. if (getenv("NNN_BMS")) {
  1274. dprintf(fd, "BOOKMARKS\n");
  1275. for (; i < MAX_BM; ++i)
  1276. if (bookmark[i].key)
  1277. dprintf(fd, " %s: %s\n",
  1278. bookmark[i].key, bookmark[i].loc);
  1279. else
  1280. break;
  1281. dprintf(fd, "\n");
  1282. }
  1283. if (editor)
  1284. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1285. if (desktop_manager)
  1286. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1287. if (idletimeout)
  1288. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1289. if (copier)
  1290. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1291. dprintf(fd, "\n");
  1292. close(fd);
  1293. exitcurses();
  1294. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1295. unlink(tmp);
  1296. initcurses();
  1297. return 0;
  1298. }
  1299. static int
  1300. sum_bsizes(const char *fpath, const struct stat *sb,
  1301. int typeflag, struct FTW *ftwbuf)
  1302. {
  1303. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1304. ent_blocks += sb->st_blocks;
  1305. ++num_files;
  1306. return 0;
  1307. }
  1308. static int
  1309. getorder(size_t size)
  1310. {
  1311. switch (size) {
  1312. case 4096:
  1313. return 12;
  1314. case 512:
  1315. return 9;
  1316. case 8192:
  1317. return 13;
  1318. case 16384:
  1319. return 14;
  1320. case 32768:
  1321. return 15;
  1322. case 65536:
  1323. return 16;
  1324. case 131072:
  1325. return 17;
  1326. case 262144:
  1327. return 18;
  1328. case 524288:
  1329. return 19;
  1330. case 1048576:
  1331. return 20;
  1332. case 2048:
  1333. return 11;
  1334. case 1024:
  1335. return 10;
  1336. default:
  1337. return 0;
  1338. }
  1339. }
  1340. static int
  1341. dentfill(char *path, struct entry **dents,
  1342. int (*filter)(regex_t *, char *), regex_t *re)
  1343. {
  1344. static DIR *dirp;
  1345. static struct dirent *dp;
  1346. static struct stat sb;
  1347. static int fd, n;
  1348. n = 0;
  1349. if (cfg.blkorder) {
  1350. num_files = 0;
  1351. dir_blocks = 0;
  1352. }
  1353. dirp = opendir(path);
  1354. if (dirp == NULL)
  1355. return 0;
  1356. fd = dirfd(dirp);
  1357. while ((dp = readdir(dirp)) != NULL) {
  1358. /* Skip self and parent */
  1359. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  1360. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  1361. continue;
  1362. if (filter(re, dp->d_name) == 0) {
  1363. if (!cfg.blkorder)
  1364. continue;
  1365. if (fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW)
  1366. == -1)
  1367. continue;
  1368. if (S_ISDIR(sb.st_mode)) {
  1369. ent_blocks = 0;
  1370. mkpath(path, dp->d_name, g_buf, PATH_MAX);
  1371. if (nftw(g_buf, sum_bsizes, open_max,
  1372. FTW_MOUNT | FTW_PHYS) == -1) {
  1373. printmsg("nftw(3) failed");
  1374. dir_blocks += sb.st_blocks;
  1375. } else
  1376. dir_blocks += ent_blocks;
  1377. } else {
  1378. if (sb.st_blocks)
  1379. dir_blocks += sb.st_blocks;
  1380. ++num_files;
  1381. }
  1382. continue;
  1383. }
  1384. if (fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1385. if (*dents)
  1386. free(*dents);
  1387. printerr(1, "fstatat");
  1388. }
  1389. if (n == total_dents) {
  1390. total_dents += 64;
  1391. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1392. if (*dents == NULL)
  1393. printerr(1, "realloc");
  1394. }
  1395. xstrlcpy((*dents)[n].name, dp->d_name, NAME_MAX);
  1396. (*dents)[n].mode = sb.st_mode;
  1397. (*dents)[n].t = sb.st_mtime;
  1398. (*dents)[n].size = sb.st_size;
  1399. if (cfg.blkorder) {
  1400. if (S_ISDIR(sb.st_mode)) {
  1401. ent_blocks = 0;
  1402. mkpath(path, dp->d_name, g_buf, PATH_MAX);
  1403. if (nftw(g_buf, sum_bsizes, open_max,
  1404. FTW_MOUNT | FTW_PHYS) == -1) {
  1405. printmsg("nftw(3) failed");
  1406. (*dents)[n].blocks = sb.st_blocks;
  1407. } else
  1408. (*dents)[n].blocks = ent_blocks;
  1409. } else {
  1410. (*dents)[n].blocks = sb.st_blocks;
  1411. ++num_files;
  1412. }
  1413. if ((*dents)[n].blocks)
  1414. dir_blocks += (*dents)[n].blocks;
  1415. }
  1416. ++n;
  1417. }
  1418. if (cfg.blkorder) {
  1419. static struct statvfs svb;
  1420. if (statvfs(path, &svb) == -1)
  1421. fs_free = 0;
  1422. else
  1423. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1424. }
  1425. /* Should never be null */
  1426. if (closedir(dirp) == -1) {
  1427. if (*dents)
  1428. free(*dents);
  1429. printerr(1, "closedir");
  1430. }
  1431. return n;
  1432. }
  1433. static void
  1434. dentfree(struct entry *dents)
  1435. {
  1436. free(dents);
  1437. }
  1438. /* Return the position of the matching entry or 0 otherwise */
  1439. static int
  1440. dentfind(struct entry *dents, int n, char *path)
  1441. {
  1442. if (!path)
  1443. return 0;
  1444. static int i;
  1445. static char *p;
  1446. p = basename(path);
  1447. DPRINTF_S(p);
  1448. for (i = 0; i < n; ++i)
  1449. if (xstrcmp(p, dents[i].name) == 0)
  1450. return i;
  1451. return 0;
  1452. }
  1453. static int
  1454. populate(char *path, char *oldpath, char *fltr)
  1455. {
  1456. static regex_t re;
  1457. /* Can fail when permissions change while browsing */
  1458. if (access(path, R_OK) == -1)
  1459. return -1;
  1460. /* Search filter */
  1461. if (setfilter(&re, fltr) != 0)
  1462. return -1;
  1463. if (cfg.blkorder) {
  1464. printmsg("Calculating...");
  1465. refresh();
  1466. }
  1467. ndents = dentfill(path, &dents, visible, &re);
  1468. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1469. /* Find cur from history */
  1470. cur = dentfind(dents, ndents, oldpath);
  1471. return 0;
  1472. }
  1473. static void
  1474. redraw(char *path)
  1475. {
  1476. static int nlines, i;
  1477. static size_t ncols;
  1478. nlines = MIN(LINES - 4, ndents);
  1479. /* Clean screen */
  1480. erase();
  1481. /* Strip trailing slashes */
  1482. for (i = xstrlen(path) - 1; i > 0; --i)
  1483. if (path[i] == '/')
  1484. path[i] = '\0';
  1485. else
  1486. break;
  1487. DPRINTF_D(cur);
  1488. DPRINTF_S(path);
  1489. /* No text wrapping in cwd line */
  1490. if (!realpath(path, g_buf)) {
  1491. printmsg("Cannot resolve path");
  1492. return;
  1493. }
  1494. ncols = COLS;
  1495. if (ncols > PATH_MAX)
  1496. ncols = PATH_MAX;
  1497. /* - xstrlen(CWD) - 1 = 6 */
  1498. g_buf[ncols - 6] = '\0';
  1499. printw(CWD "%s\n\n", g_buf);
  1500. if (cfg.showcolor) {
  1501. attron(COLOR_PAIR(1) | A_BOLD);
  1502. cfg.dircolor = 1;
  1503. }
  1504. /* Print listing */
  1505. if (cur < (nlines >> 1)) {
  1506. for (i = 0; i < nlines; ++i)
  1507. printptr(&dents[i], i == cur);
  1508. } else if (cur >= ndents - (nlines >> 1)) {
  1509. for (i = ndents - nlines; i < ndents; ++i)
  1510. printptr(&dents[i], i == cur);
  1511. } else {
  1512. static int odd;
  1513. odd = ISODD(nlines);
  1514. nlines >>= 1;
  1515. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1516. printptr(&dents[i], i == cur);
  1517. }
  1518. /* Must reset e.g. no files in dir */
  1519. if (cfg.dircolor) {
  1520. attroff(COLOR_PAIR(1) | A_BOLD);
  1521. cfg.dircolor = 0;
  1522. }
  1523. if (cfg.showdetail) {
  1524. if (ndents) {
  1525. static char ind[2] = "\0\0";
  1526. static char sort[9];
  1527. if (cfg.mtimeorder)
  1528. sprintf(sort, "by time ");
  1529. else if (cfg.sizeorder)
  1530. sprintf(sort, "by size ");
  1531. else
  1532. sort[0] = '\0';
  1533. if (S_ISDIR(dents[cur].mode))
  1534. ind[0] = '/';
  1535. else if (S_ISLNK(dents[cur].mode))
  1536. ind[0] = '@';
  1537. else if (S_ISSOCK(dents[cur].mode))
  1538. ind[0] = '=';
  1539. else if (S_ISFIFO(dents[cur].mode))
  1540. ind[0] = '|';
  1541. else if (dents[cur].mode & 0100)
  1542. ind[0] = '*';
  1543. else
  1544. ind[0] = '\0';
  1545. /* We need to show filename as it may
  1546. * be truncated in directory listing
  1547. */
  1548. if (!cfg.blkorder)
  1549. sprintf(g_buf, "total %d %s[%s%s]", ndents,
  1550. sort, unescape(dents[cur].name), ind);
  1551. else {
  1552. i = sprintf(g_buf, "du: %s (%lu files) ",
  1553. coolsize(dir_blocks << 9),
  1554. num_files);
  1555. sprintf(g_buf + i, "vol: %s free [%s%s]",
  1556. coolsize(fs_free),
  1557. unescape(dents[cur].name), ind);
  1558. }
  1559. printmsg(g_buf);
  1560. } else
  1561. printmsg("0 items");
  1562. }
  1563. }
  1564. static void
  1565. browse(char *ipath, char *ifilter)
  1566. {
  1567. char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1568. char lastdir[PATH_MAX];
  1569. char fltr[LINE_MAX];
  1570. char *dir, *tmp, *run, *env;
  1571. struct stat sb;
  1572. int r, fd, presel;
  1573. enum action sel = SEL_RUNARG + 1;
  1574. xstrlcpy(path, ipath, PATH_MAX);
  1575. xstrlcpy(fltr, ifilter, LINE_MAX);
  1576. oldpath[0] = '\0';
  1577. newpath[0] = '\0';
  1578. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1579. if (cfg.filtermode)
  1580. presel = FILTER;
  1581. else
  1582. presel = 0;
  1583. begin:
  1584. if (populate(path, oldpath, fltr) == -1) {
  1585. printwarn();
  1586. goto nochange;
  1587. }
  1588. for (;;) {
  1589. redraw(path);
  1590. nochange:
  1591. /* Exit if parent has exited */
  1592. if (getppid() == 1)
  1593. _exit(0);
  1594. sel = nextsel(&run, &env, &presel);
  1595. switch (sel) {
  1596. case SEL_CDQUIT:
  1597. {
  1598. char *tmpfile = "/tmp/nnn";
  1599. tmp = getenv("NNN_TMPFILE");
  1600. if (tmp)
  1601. tmpfile = tmp;
  1602. FILE *fp = fopen(tmpfile, "w");
  1603. if (fp) {
  1604. fprintf(fp, "cd \"%s\"", path);
  1605. fclose(fp);
  1606. }
  1607. /* Fall through to exit */
  1608. } // fallthrough
  1609. case SEL_QUIT:
  1610. dentfree(dents);
  1611. return;
  1612. case SEL_BACK:
  1613. /* There is no going back */
  1614. if (path[0] == '/' && path[1] == '\0') {
  1615. printmsg("You are at /");
  1616. goto nochange;
  1617. }
  1618. dir = xdirname(path);
  1619. if (access(dir, R_OK) == -1) {
  1620. printwarn();
  1621. goto nochange;
  1622. }
  1623. /* Save history */
  1624. xstrlcpy(oldpath, path, PATH_MAX);
  1625. /* Save last working directory */
  1626. xstrlcpy(lastdir, path, PATH_MAX);
  1627. xstrlcpy(path, dir, PATH_MAX);
  1628. /* Reset filter */
  1629. xstrlcpy(fltr, ifilter, LINE_MAX);
  1630. if (cfg.filtermode)
  1631. presel = FILTER;
  1632. goto begin;
  1633. case SEL_GOIN:
  1634. /* Cannot descend in empty directories */
  1635. if (ndents == 0)
  1636. goto begin;
  1637. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1638. DPRINTF_S(newpath);
  1639. /* Get path info */
  1640. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1641. if (fd == -1) {
  1642. printwarn();
  1643. goto nochange;
  1644. }
  1645. r = fstat(fd, &sb);
  1646. if (r == -1) {
  1647. printwarn();
  1648. close(fd);
  1649. goto nochange;
  1650. }
  1651. close(fd);
  1652. DPRINTF_U(sb.st_mode);
  1653. switch (sb.st_mode & S_IFMT) {
  1654. case S_IFDIR:
  1655. if (access(newpath, R_OK) == -1) {
  1656. printwarn();
  1657. goto nochange;
  1658. }
  1659. /* Save last working directory */
  1660. xstrlcpy(lastdir, path, PATH_MAX);
  1661. xstrlcpy(path, newpath, PATH_MAX);
  1662. oldpath[0] = '\0';
  1663. /* Reset filter */
  1664. xstrlcpy(fltr, ifilter, LINE_MAX);
  1665. if (cfg.filtermode)
  1666. presel = FILTER;
  1667. goto begin;
  1668. case S_IFREG:
  1669. {
  1670. /* If NNN_USE_EDITOR is set,
  1671. * open text in EDITOR
  1672. */
  1673. if (editor) {
  1674. if (getmime(dents[cur].name)) {
  1675. spawn(editor, newpath, NULL,
  1676. NULL, F_NORMAL);
  1677. continue;
  1678. }
  1679. /* Recognize and open plain
  1680. * text files with vi
  1681. */
  1682. if (get_output(g_buf, MAX_CMD_LEN,
  1683. "file", "-bi",
  1684. newpath, 0) == NULL)
  1685. continue;
  1686. if (strstr(g_buf, "text/") == g_buf) {
  1687. spawn(editor, newpath, NULL,
  1688. NULL, F_NORMAL);
  1689. continue;
  1690. }
  1691. }
  1692. /* Invoke desktop opener as last resort */
  1693. spawn(utils[0], newpath, NULL, NULL, F_NOTRACE);
  1694. continue;
  1695. }
  1696. default:
  1697. printmsg("Unsupported file");
  1698. goto nochange;
  1699. }
  1700. case SEL_FLTR:
  1701. presel = readln(path);
  1702. xstrlcpy(fltr, ifilter, LINE_MAX);
  1703. DPRINTF_S(fltr);
  1704. /* Save current */
  1705. if (ndents > 0)
  1706. mkpath(path, dents[cur].name, oldpath,
  1707. PATH_MAX);
  1708. goto nochange;
  1709. case SEL_MFLTR:
  1710. cfg.filtermode ^= 1;
  1711. if (cfg.filtermode)
  1712. presel = FILTER;
  1713. else
  1714. printmsg("navigate-as-you-type off");
  1715. goto nochange;
  1716. case SEL_SEARCH:
  1717. spawn(player, path, "search", NULL, F_NORMAL);
  1718. break;
  1719. case SEL_NEXT:
  1720. if (cur < ndents - 1)
  1721. ++cur;
  1722. else if (ndents)
  1723. /* Roll over, set cursor to first entry */
  1724. cur = 0;
  1725. break;
  1726. case SEL_PREV:
  1727. if (cur > 0)
  1728. --cur;
  1729. else if (ndents)
  1730. /* Roll over, set cursor to last entry */
  1731. cur = ndents - 1;
  1732. break;
  1733. case SEL_PGDN:
  1734. if (cur < ndents - 1)
  1735. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1736. break;
  1737. case SEL_PGUP:
  1738. if (cur > 0)
  1739. cur -= MIN((LINES - 4) / 2, cur);
  1740. break;
  1741. case SEL_HOME:
  1742. cur = 0;
  1743. break;
  1744. case SEL_END:
  1745. cur = ndents - 1;
  1746. break;
  1747. case SEL_CD:
  1748. {
  1749. static char *input;
  1750. static int truecd;
  1751. /* Save the program start dir */
  1752. tmp = getcwd(newpath, PATH_MAX);
  1753. if (tmp == NULL) {
  1754. printwarn();
  1755. goto nochange;
  1756. }
  1757. /* Switch to current path for readline(3) */
  1758. if (chdir(path) == -1) {
  1759. printwarn();
  1760. goto nochange;
  1761. }
  1762. exitcurses();
  1763. tmp = readline("chdir: ");
  1764. initcurses();
  1765. /* Change back to program start dir */
  1766. if (chdir(newpath) == -1)
  1767. printwarn();
  1768. if (tmp[0] == '\0')
  1769. break;
  1770. /* Add to readline(3) history */
  1771. add_history(tmp);
  1772. input = tmp;
  1773. tmp = strstrip(tmp);
  1774. if (tmp[0] == '\0') {
  1775. free(input);
  1776. break;
  1777. }
  1778. truecd = 0;
  1779. if (tmp[0] == '~') {
  1780. /* Expand ~ to HOME absolute path */
  1781. char *home = getenv("HOME");
  1782. if (home)
  1783. snprintf(newpath, PATH_MAX, "%s%s",
  1784. home, tmp + 1);
  1785. else {
  1786. free(input);
  1787. printmsg("HOME not set");
  1788. goto nochange;
  1789. }
  1790. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1791. if (lastdir[0] == '\0') {
  1792. free(input);
  1793. break;
  1794. }
  1795. /* Switch to last visited dir */
  1796. xstrlcpy(newpath, lastdir, PATH_MAX);
  1797. truecd = 1;
  1798. } else if ((r = all_dots(tmp))) {
  1799. if (r == 1) {
  1800. /* Always in the current dir */
  1801. free(input);
  1802. break;
  1803. }
  1804. /* Show a message if already at / */
  1805. if (path[0] == '/' && path[1] == '\0') {
  1806. printmsg("You are at /");
  1807. free(input);
  1808. goto nochange;
  1809. }
  1810. --r; /* One . for the current dir */
  1811. dir = path;
  1812. /* Note: fd is used as a tmp variable here */
  1813. for (fd = 0; fd < r; ++fd) {
  1814. /* Reached / ? */
  1815. if (path[0] == '/' && path[1] == '\0') {
  1816. /* Can't cd beyond / */
  1817. break;
  1818. }
  1819. dir = xdirname(dir);
  1820. if (access(dir, R_OK) == -1) {
  1821. printwarn();
  1822. free(input);
  1823. goto nochange;
  1824. }
  1825. }
  1826. truecd = 1;
  1827. /* Save the path in case of cd ..
  1828. * We mark the current dir in parent dir
  1829. */
  1830. if (r == 1) {
  1831. xstrlcpy(oldpath, path, PATH_MAX);
  1832. truecd = 2;
  1833. }
  1834. xstrlcpy(newpath, dir, PATH_MAX);
  1835. } else
  1836. mkpath(path, tmp, newpath, PATH_MAX);
  1837. free(input);
  1838. if (access(newpath, R_OK) == -1) {
  1839. printwarn();
  1840. break;
  1841. }
  1842. if (truecd == 0) {
  1843. /* Probable change in dir */
  1844. /* No-op if it's the same directory */
  1845. if (xstrcmp(path, newpath) == 0)
  1846. break;
  1847. oldpath[0] = '\0';
  1848. } else if (truecd == 1)
  1849. /* Sure change in dir */
  1850. oldpath[0] = '\0';
  1851. /* Save last working directory */
  1852. xstrlcpy(lastdir, path, PATH_MAX);
  1853. /* Save the newly opted dir in path */
  1854. xstrlcpy(path, newpath, PATH_MAX);
  1855. /* Reset filter */
  1856. xstrlcpy(fltr, ifilter, LINE_MAX);
  1857. DPRINTF_S(path);
  1858. if (cfg.filtermode)
  1859. presel = FILTER;
  1860. goto begin;
  1861. }
  1862. case SEL_CDHOME:
  1863. tmp = getenv("HOME");
  1864. if (tmp == NULL) {
  1865. clearprompt();
  1866. goto nochange;
  1867. }
  1868. if (access(tmp, R_OK) == -1) {
  1869. printwarn();
  1870. goto nochange;
  1871. }
  1872. if (xstrcmp(path, tmp) == 0)
  1873. break;
  1874. /* Save last working directory */
  1875. xstrlcpy(lastdir, path, PATH_MAX);
  1876. xstrlcpy(path, tmp, PATH_MAX);
  1877. oldpath[0] = '\0';
  1878. /* Reset filter */
  1879. xstrlcpy(fltr, ifilter, LINE_MAX);
  1880. DPRINTF_S(path);
  1881. if (cfg.filtermode)
  1882. presel = FILTER;
  1883. goto begin;
  1884. case SEL_CDBEGIN:
  1885. if (access(ipath, R_OK) == -1) {
  1886. printwarn();
  1887. goto nochange;
  1888. }
  1889. if (xstrcmp(path, ipath) == 0)
  1890. break;
  1891. /* Save last working directory */
  1892. xstrlcpy(lastdir, path, PATH_MAX);
  1893. xstrlcpy(path, ipath, PATH_MAX);
  1894. oldpath[0] = '\0';
  1895. /* Reset filter */
  1896. xstrlcpy(fltr, ifilter, LINE_MAX);
  1897. DPRINTF_S(path);
  1898. if (cfg.filtermode)
  1899. presel = FILTER;
  1900. goto begin;
  1901. case SEL_CDLAST:
  1902. if (lastdir[0] == '\0')
  1903. break;
  1904. if (access(lastdir, R_OK) == -1) {
  1905. printwarn();
  1906. goto nochange;
  1907. }
  1908. xstrlcpy(newpath, lastdir, PATH_MAX);
  1909. xstrlcpy(lastdir, path, PATH_MAX);
  1910. xstrlcpy(path, newpath, PATH_MAX);
  1911. oldpath[0] = '\0';
  1912. /* Reset filter */
  1913. xstrlcpy(fltr, ifilter, LINE_MAX);
  1914. DPRINTF_S(path);
  1915. if (cfg.filtermode)
  1916. presel = FILTER;
  1917. goto begin;
  1918. case SEL_CDBM:
  1919. printprompt("key: ");
  1920. tmp = readinput();
  1921. clearprompt();
  1922. if (tmp == NULL)
  1923. goto nochange;
  1924. for (r = 0; bookmark[r].key && r < MAX_BM; ++r) {
  1925. if (xstrcmp(bookmark[r].key, tmp) == -1)
  1926. continue;
  1927. if (bookmark[r].loc[0] == '~') {
  1928. /* Expand ~ to HOME */
  1929. char *home = getenv("HOME");
  1930. if (home)
  1931. snprintf(newpath,
  1932. PATH_MAX,
  1933. "%s%s",
  1934. home,
  1935. bookmark[r].loc
  1936. + 1);
  1937. else {
  1938. printmsg("HOME not set");
  1939. goto nochange;
  1940. }
  1941. } else
  1942. mkpath(path, bookmark[r].loc,
  1943. newpath, PATH_MAX);
  1944. if (access(newpath, R_OK) == -1) {
  1945. printwarn();
  1946. goto nochange;
  1947. }
  1948. if (xstrcmp(path, newpath) == 0)
  1949. break;
  1950. oldpath[0] = '\0';
  1951. break;
  1952. }
  1953. if (!bookmark[r].key) {
  1954. printmsg("No matching bookmark");
  1955. goto nochange;
  1956. }
  1957. /* Save last working directory */
  1958. xstrlcpy(lastdir, path, PATH_MAX);
  1959. /* Save the newly opted dir in path */
  1960. xstrlcpy(path, newpath, PATH_MAX);
  1961. /* Reset filter */
  1962. xstrlcpy(fltr, ifilter, LINE_MAX);
  1963. DPRINTF_S(path);
  1964. if (cfg.filtermode)
  1965. presel = FILTER;
  1966. goto begin;
  1967. case SEL_TOGGLEDOT:
  1968. cfg.showhidden ^= 1;
  1969. initfilter(cfg.showhidden, &ifilter);
  1970. xstrlcpy(fltr, ifilter, LINE_MAX);
  1971. goto begin;
  1972. case SEL_DETAIL:
  1973. cfg.showdetail ^= 1;
  1974. cfg.showdetail ? (printptr = &printent_long)
  1975. : (printptr = &printent);
  1976. /* Save current */
  1977. if (ndents > 0)
  1978. mkpath(path, dents[cur].name, oldpath,
  1979. PATH_MAX);
  1980. goto begin;
  1981. case SEL_STATS:
  1982. {
  1983. struct stat sb;
  1984. if (ndents > 0) {
  1985. mkpath(path, dents[cur].name, oldpath,
  1986. PATH_MAX);
  1987. r = lstat(oldpath, &sb);
  1988. if (r == -1) {
  1989. if (dents)
  1990. dentfree(dents);
  1991. printerr(1, "lstat");
  1992. } else {
  1993. r = show_stats(oldpath, dents[cur].name,
  1994. &sb);
  1995. if (r < 0) {
  1996. printmsg(strerror(errno));
  1997. goto nochange;
  1998. }
  1999. }
  2000. }
  2001. break;
  2002. }
  2003. case SEL_MEDIA:
  2004. if (ndents > 0) {
  2005. mkpath(path, dents[cur].name, oldpath,
  2006. PATH_MAX);
  2007. if (show_mediainfo(oldpath, NULL) == -1) {
  2008. printmsg("mediainfo missing");
  2009. goto nochange;
  2010. }
  2011. }
  2012. break;
  2013. case SEL_FMEDIA:
  2014. if (ndents > 0) {
  2015. mkpath(path, dents[cur].name, oldpath,
  2016. PATH_MAX);
  2017. if (show_mediainfo(oldpath, "-f") == -1) {
  2018. printmsg("mediainfo missing");
  2019. goto nochange;
  2020. }
  2021. }
  2022. break;
  2023. case SEL_DFB:
  2024. if (!desktop_manager) {
  2025. printmsg("NNN_DE_FILE_MANAGER not set");
  2026. goto nochange;
  2027. }
  2028. spawn(desktop_manager, path, NULL, path,
  2029. F_NOTRACE | F_NOWAIT);
  2030. break;
  2031. case SEL_FSIZE:
  2032. cfg.sizeorder ^= 1;
  2033. cfg.mtimeorder = 0;
  2034. cfg.blkorder = 0;
  2035. /* Save current */
  2036. if (ndents > 0)
  2037. mkpath(path, dents[cur].name, oldpath,
  2038. PATH_MAX);
  2039. goto begin;
  2040. case SEL_BSIZE:
  2041. cfg.blkorder ^= 1;
  2042. if (cfg.blkorder) {
  2043. cfg.showdetail = 1;
  2044. printptr = &printent_long;
  2045. }
  2046. cfg.mtimeorder = 0;
  2047. cfg.sizeorder = 0;
  2048. /* Save current */
  2049. if (ndents > 0)
  2050. mkpath(path, dents[cur].name, oldpath,
  2051. PATH_MAX);
  2052. goto begin;
  2053. case SEL_MTIME:
  2054. cfg.mtimeorder ^= 1;
  2055. cfg.sizeorder = 0;
  2056. cfg.blkorder = 0;
  2057. /* Save current */
  2058. if (ndents > 0)
  2059. mkpath(path, dents[cur].name, oldpath,
  2060. PATH_MAX);
  2061. goto begin;
  2062. case SEL_REDRAW:
  2063. /* Save current */
  2064. if (ndents > 0)
  2065. mkpath(path, dents[cur].name, oldpath,
  2066. PATH_MAX);
  2067. goto begin;
  2068. case SEL_COPY:
  2069. if (copier && ndents) {
  2070. if (path[0] == '/' && path[1] == '\0')
  2071. snprintf(newpath, PATH_MAX, "/%s",
  2072. dents[cur].name);
  2073. else
  2074. snprintf(newpath, PATH_MAX, "%s/%s",
  2075. path, dents[cur].name);
  2076. spawn(copier, newpath, NULL, NULL, F_NONE);
  2077. printmsg(newpath);
  2078. } else if (!copier)
  2079. printmsg("NNN_COPIER is not set");
  2080. goto nochange;
  2081. case SEL_HELP:
  2082. show_help();
  2083. break;
  2084. case SEL_RUN:
  2085. run = xgetenv(env, run);
  2086. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2087. /* Repopulate as directory content may have changed */
  2088. goto begin;
  2089. case SEL_RUNARG:
  2090. run = xgetenv(env, run);
  2091. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2092. break;
  2093. }
  2094. /* Screensaver */
  2095. if (idletimeout != 0 && idle == idletimeout) {
  2096. idle = 0;
  2097. spawn(player, "", "screensaver", NULL,
  2098. F_NORMAL | F_SIGINT);
  2099. }
  2100. }
  2101. }
  2102. static void
  2103. usage(void)
  2104. {
  2105. printf("usage: nnn [-l] [-i] [-p custom_nlay] [-S] [-v] [-h] [PATH]\n\n\
  2106. The missing terminal file browser for X.\n\n\
  2107. positional arguments:\n\
  2108. PATH directory to open [default: current dir]\n\n\
  2109. optional arguments:\n\
  2110. -l start in light mode (fewer details)\n\
  2111. -i start in navigate-as-you-type mode\n\
  2112. -n disable color for directory entries\n\
  2113. -p path to custom nlay\n\
  2114. -S start in disk usage analyzer mode\n\
  2115. -v show program version and exit\n\
  2116. -h show this help and exit\n\n\
  2117. Version: %s\n\
  2118. License: BSD 2-Clause\n\
  2119. Webpage: https://github.com/jarun/nnn\n", VERSION);
  2120. exit(0);
  2121. }
  2122. int
  2123. main(int argc, char *argv[])
  2124. {
  2125. char cwd[PATH_MAX], *ipath;
  2126. char *ifilter, *bmstr;
  2127. int opt;
  2128. /* Confirm we are in a terminal */
  2129. if (!isatty(0) || !isatty(1)) {
  2130. fprintf(stderr, "stdin or stdout is not a tty\n");
  2131. exit(1);
  2132. }
  2133. while ((opt = getopt(argc, argv, "lSinp:vh")) != -1) {
  2134. switch (opt) {
  2135. case 'S':
  2136. cfg.blkorder = 1;
  2137. break;
  2138. case 'l':
  2139. cfg.showdetail = 0;
  2140. printptr = &printent;
  2141. break;
  2142. case 'i':
  2143. cfg.filtermode = 1;
  2144. break;
  2145. case 'n':
  2146. cfg.showcolor = 0;
  2147. break;
  2148. case 'p':
  2149. player = optarg;
  2150. break;
  2151. case 'v':
  2152. printf("%s\n", VERSION);
  2153. return 0;
  2154. case 'h': // fallthrough
  2155. default:
  2156. usage();
  2157. }
  2158. }
  2159. if (argc == optind) {
  2160. /* Start in the current directory */
  2161. ipath = getcwd(cwd, PATH_MAX);
  2162. if (ipath == NULL)
  2163. ipath = "/";
  2164. } else {
  2165. ipath = realpath(argv[optind], cwd);
  2166. if (!ipath) {
  2167. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2168. exit(1);
  2169. }
  2170. }
  2171. /* Set the word shift */
  2172. _WSHIFT = sizeof(ulong);
  2173. if (_WSHIFT == 8)
  2174. _WSHIFT = 3;
  2175. else
  2176. _WSHIFT = 2;
  2177. /* Increase current open file descriptor limit */
  2178. open_max = max_openfds();
  2179. if (getuid() == 0)
  2180. cfg.showhidden = 1;
  2181. initfilter(cfg.showhidden, &ifilter);
  2182. /* Parse bookmarks string, if available */
  2183. bmstr = getenv("NNN_BMS");
  2184. if (bmstr)
  2185. parsebmstr(bmstr);
  2186. /* Edit text in EDITOR, if opted */
  2187. if (getenv("NNN_USE_EDITOR"))
  2188. editor = xgetenv("EDITOR", "vi");
  2189. /* Set player if not set already */
  2190. if (!player)
  2191. player = utils[1];
  2192. /* Get the desktop file browser, if set */
  2193. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2194. /* Get screensaver wait time, if set; copier used as tmp var */
  2195. copier = getenv("NNN_IDLE_TIMEOUT");
  2196. if (copier)
  2197. idletimeout = abs(atoi(copier));
  2198. /* Get the default copier, if set */
  2199. copier = getenv("NNN_COPIER");
  2200. signal(SIGINT, SIG_IGN);
  2201. /* Test initial path */
  2202. if (access(ipath, R_OK) == -1) {
  2203. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2204. exit(1);
  2205. }
  2206. /* Set locale */
  2207. setlocale(LC_ALL, "");
  2208. #ifdef DEBUGMODE
  2209. enabledbg();
  2210. #endif
  2211. initcurses();
  2212. browse(ipath, ifilter);
  2213. exitcurses();
  2214. #ifdef DEBUGMODE
  2215. disabledbg();
  2216. #endif
  2217. exit(0);
  2218. }