My build of nnn with minor changes
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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