My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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