My build of nnn with minor changes
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

2471 Zeilen
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 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. /* Macros to define process spawn behaviour as flags */
  96. #define SP_NONE 0x00 /* no flag set */
  97. #define SP_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  98. #define SP_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  99. #define SP_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  100. #define SP_SIGINT 0x08 /* restore default SIGINT handler */
  101. #define SP_NORMAL 0x80 /* spawn child process in non-curses regular mode */
  102. typedef unsigned long ulong;
  103. typedef unsigned int uint;
  104. typedef unsigned char uchar;
  105. /* Directory entry */
  106. typedef struct entry {
  107. char name[NAME_MAX];
  108. mode_t mode;
  109. time_t t;
  110. off_t size;
  111. blkcnt_t blocks; /* number of 512B blocks allocated */
  112. } *pEntry;
  113. /* Bookmark */
  114. typedef struct {
  115. char *key;
  116. char *loc;
  117. } bm;
  118. /* Settings */
  119. typedef struct
  120. {
  121. uchar filtermode : 1; /* Set to enter filter mode */
  122. uchar mtimeorder : 1; /* Set to sort by time modified */
  123. uchar sizeorder : 1; /* Set to sort by file size */
  124. uchar blkorder : 1; /* Set to sort by blocks used (disk usage) */
  125. uchar showhidden : 1; /* Set to show hidden files */
  126. uchar showdetail : 1; /* Clear to show fewer file info */
  127. uchar reserved : 2;
  128. } settings;
  129. /* Externs */
  130. #ifdef __APPLE__
  131. extern int add_history(const char *string);
  132. #else
  133. extern void add_history(const char *string);
  134. #endif
  135. extern int wget_wch(WINDOW *win, wint_t *wch);
  136. /* Globals */
  137. static settings cfg = {0, 0, 0, 0, 0, 1, 0};
  138. /* Idle timeout in seconds, 0 to disable */
  139. static int idletimeout;
  140. static struct entry *dents;
  141. static int ndents, cur, total_dents;
  142. static int idle;
  143. static char *player;
  144. static char *copier;
  145. static char *editor;
  146. static char *desktop_manager;
  147. static blkcnt_t ent_blocks;
  148. static blkcnt_t dir_blocks;
  149. static ulong num_files;
  150. static size_t fs_free;
  151. static uint open_max;
  152. static bm bookmark[MAX_BM];
  153. static const double div_2_pow_10 = 1.0 / 1024.0;
  154. /* Utilities to open files, run actions */
  155. static char *utils[] = {
  156. #ifdef __APPLE__
  157. "/usr/bin/open",
  158. #else
  159. "/usr/bin/xdg-open",
  160. #endif
  161. "nlay"
  162. };
  163. /* For use in functions which are isolated and don't return the buffer */
  164. static char g_buf[MAX_CMD_LEN];
  165. /*
  166. * Layout:
  167. * .---------
  168. * | cwd: /mnt/path
  169. * |
  170. * | file0
  171. * | file1
  172. * | > file2
  173. * | file3
  174. * | file4
  175. * ...
  176. * | filen
  177. * |
  178. * | Permission denied
  179. * '------
  180. */
  181. /* Forward declarations */
  182. static void printmsg(char *);
  183. static void printwarn(void);
  184. static void printerr(int, char *);
  185. static void redraw(char *path);
  186. /* Functions */
  187. /* Increase the limit on open file descriptors, if possible */
  188. static rlim_t
  189. max_openfds()
  190. {
  191. struct rlimit rl;
  192. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  193. if (limit != 0)
  194. return 32;
  195. limit = rl.rlim_cur;
  196. rl.rlim_cur = rl.rlim_max;
  197. if (setrlimit(RLIMIT_NOFILE, &rl) == 0)
  198. return rl.rlim_max - 64;
  199. if (limit > 128)
  200. return limit - 64;
  201. return 32;
  202. }
  203. /* Just a safe strncpy(3) */
  204. static void
  205. xstrlcpy(char *dest, const char *src, size_t n)
  206. {
  207. while (--n && (*dest = *src))
  208. ++dest, ++src;
  209. if (!n)
  210. *dest = '\0';
  211. }
  212. /*
  213. * The poor man's implementation of memrchr(3).
  214. * We are only looking for '/' in this program.
  215. */
  216. static void *
  217. xmemrchr(const void *s, uchar ch, size_t n)
  218. {
  219. if (!s || !n)
  220. return NULL;
  221. static uchar *p;
  222. p = (uchar *)s + n - 1;
  223. while (n) {
  224. if (*p == ch)
  225. return p;
  226. --p;
  227. --n;
  228. }
  229. return NULL;
  230. }
  231. /*
  232. * The following dirname(3) implementation does not
  233. * modify the input. We use a copy of the original.
  234. *
  235. * Modified from the glibc (GNU LGPL) version.
  236. */
  237. static char *
  238. xdirname(const char *path)
  239. {
  240. static char buf[PATH_MAX];
  241. static char *last_slash;
  242. xstrlcpy(buf, path, PATH_MAX);
  243. /* Find last '/'. */
  244. last_slash = strrchr(buf, '/');
  245. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  246. /* Determine whether all remaining characters are slashes. */
  247. char *runp;
  248. for (runp = last_slash; runp != buf; --runp)
  249. if (runp[-1] != '/')
  250. break;
  251. /* The '/' is the last character, we have to look further. */
  252. if (runp != buf)
  253. last_slash = xmemrchr(buf, '/', runp - buf);
  254. }
  255. if (last_slash != NULL) {
  256. /* Determine whether all remaining characters are slashes. */
  257. char *runp;
  258. for (runp = last_slash; runp != buf; --runp)
  259. if (runp[-1] != '/')
  260. break;
  261. /* Terminate the buffer. */
  262. if (runp == buf) {
  263. /* The last slash is the first character in the string.
  264. * We have to return "/". As a special case we have to
  265. * return "//" if there are exactly two slashes at the
  266. * beginning of the string. See XBD 4.10 Path Name
  267. * Resolution for more information.
  268. */
  269. if (last_slash == buf + 1)
  270. ++last_slash;
  271. else
  272. last_slash = buf + 1;
  273. } else
  274. last_slash = runp;
  275. last_slash[0] = '\0';
  276. } else {
  277. /* This assignment is ill-designed but the XPG specs require to
  278. * return a string containing "." in any case no directory part
  279. * is found and so a static and constant string is required.
  280. */
  281. buf[0] = '.';
  282. buf[1] = '\0';
  283. }
  284. return buf;
  285. }
  286. /*
  287. * Return number of dots if all chars in a string are dots, else 0
  288. */
  289. static int
  290. all_dots(const char *ptr)
  291. {
  292. if (!ptr)
  293. return FALSE;
  294. int count = 0;
  295. while (*ptr == '.')
  296. ++count, ++ptr;
  297. if (*ptr)
  298. return 0;
  299. return count;
  300. }
  301. /* Initialize curses mode */
  302. static void
  303. initcurses(void)
  304. {
  305. if (initscr() == NULL) {
  306. char *term = getenv("TERM");
  307. if (term != NULL)
  308. fprintf(stderr, "error opening terminal: %s\n", term);
  309. else
  310. fprintf(stderr, "failed to initialize curses\n");
  311. exit(1);
  312. }
  313. cbreak();
  314. noecho();
  315. nonl();
  316. intrflush(stdscr, FALSE);
  317. keypad(stdscr, TRUE);
  318. curs_set(FALSE); /* Hide cursor */
  319. start_color();
  320. use_default_colors();
  321. timeout(1000); /* One second */
  322. }
  323. /* Exit curses mode */
  324. static void
  325. exitcurses(void)
  326. {
  327. endwin(); /* Restore terminal */
  328. }
  329. /*
  330. * Spawns a child process. Behaviour can be controlled using flag.
  331. * Limited to 2 arguments to a program, flag works on bit set.
  332. */
  333. static void
  334. spawn(char *file, char *arg1, char *arg2, char *dir, uchar flag)
  335. {
  336. pid_t pid;
  337. int status;
  338. if (flag & SP_NORMAL)
  339. exitcurses();
  340. pid = fork();
  341. if (pid == 0) {
  342. if (dir != NULL)
  343. status = chdir(dir);
  344. /* Show a marker (to indicate nnn spawned shell) */
  345. if (flag & SP_MARKER)
  346. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  347. /* Suppress stdout and stderr */
  348. if (flag & SP_NOTRACE) {
  349. int fd = open("/dev/null", O_WRONLY, 0200);
  350. dup2(fd, 1);
  351. dup2(fd, 2);
  352. close(fd);
  353. }
  354. if (flag & SP_SIGINT)
  355. signal(SIGINT, SIG_DFL);
  356. execlp(file, file, arg1, arg2, NULL);
  357. _exit(1);
  358. } else {
  359. if (!(flag & SP_NOWAIT))
  360. /* Ignore interruptions */
  361. while (waitpid(pid, &status, 0) == -1)
  362. DPRINTF_D(status);
  363. DPRINTF_D(pid);
  364. if (flag & SP_NORMAL)
  365. initcurses();
  366. }
  367. }
  368. /* Get program name from env var, else return fallback program */
  369. static char *
  370. xgetenv(char *name, char *fallback)
  371. {
  372. if (name == NULL)
  373. return fallback;
  374. char *value = getenv(name);
  375. return value && value[0] ? value : fallback;
  376. }
  377. /*
  378. * We assume none of the strings are NULL.
  379. *
  380. * Let's have the logic to sort numeric names in numeric order.
  381. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  382. *
  383. * If the absolute numeric values are same, we fallback to alphasort.
  384. */
  385. static int
  386. xstricmp(char *s1, char *s2)
  387. {
  388. static char *c1, *c2;
  389. c1 = s1;
  390. while (isspace(*c1))
  391. ++c1;
  392. if (*c1 == '-' || *c1 == '+')
  393. ++c1;
  394. while (*c1 >= '0' && *c1 <= '9')
  395. ++c1;
  396. c2 = s2;
  397. while (isspace(*c2))
  398. ++c2;
  399. if (*c2 == '-' || *c2 == '+')
  400. ++c2;
  401. while (*c2 >= '0' && *c2 <= '9')
  402. ++c2;
  403. if (*c1 == '\0' && *c2 == '\0') {
  404. static long long num1, num2;
  405. num1 = strtoll(s1, &c1, 10);
  406. num2 = strtoll(s2, &c2, 10);
  407. if (num1 != num2) {
  408. if (num1 > num2)
  409. return 1;
  410. else
  411. return -1;
  412. }
  413. } else if (*c1 == '\0' && *c2 != '\0')
  414. return -1;
  415. else if (*c1 != '\0' && *c2 == '\0')
  416. return 1;
  417. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  418. ++s1, ++s2;
  419. /* In case of alphabetically same names, make sure
  420. * lower case one comes before upper case one
  421. */
  422. if (!*s1 && !*s2)
  423. return 1;
  424. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  425. }
  426. /* Trim all whitespace from both ends, / from end */
  427. static char *
  428. strstrip(char *s)
  429. {
  430. if (!s || !*s)
  431. return s;
  432. size_t len = strlen(s) - 1;
  433. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  434. --len;
  435. s[len + 1] = '\0';
  436. while (*s && isspace(*s))
  437. ++s;
  438. return s;
  439. }
  440. static char *
  441. getmime(char *file)
  442. {
  443. regex_t regex;
  444. uint i;
  445. static uint len = LEN(assocs);
  446. for (i = 0; i < len; ++i) {
  447. if (regcomp(&regex, assocs[i].regex,
  448. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  449. continue;
  450. if (regexec(&regex, file, 0, NULL, 0) == 0)
  451. return assocs[i].mime;
  452. }
  453. return NULL;
  454. }
  455. static int
  456. setfilter(regex_t *regex, char *filter)
  457. {
  458. static size_t len;
  459. static int r;
  460. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  461. if (r != 0 && filter && filter[0] != '\0') {
  462. len = COLS;
  463. if (len > LINE_MAX)
  464. len = LINE_MAX;
  465. regerror(r, regex, g_buf, len);
  466. printmsg(g_buf);
  467. }
  468. return r;
  469. }
  470. static void
  471. initfilter(int dot, char **ifilter)
  472. {
  473. *ifilter = dot ? "." : "^[^.]";
  474. }
  475. static int
  476. visible(regex_t *regex, char *file)
  477. {
  478. return regexec(regex, file, 0, NULL, 0) == 0;
  479. }
  480. static int
  481. entrycmp(const void *va, const void *vb)
  482. {
  483. static pEntry pa, pb;
  484. pa = (pEntry)va;
  485. pb = (pEntry)vb;
  486. /* Sort directories first */
  487. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  488. return 1;
  489. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  490. return -1;
  491. /* Do the actual sorting */
  492. if (cfg.mtimeorder)
  493. return pb->t - pa->t;
  494. if (cfg.sizeorder) {
  495. if (pb->size > pa->size)
  496. return 1;
  497. else if (pb->size < pa->size)
  498. return -1;
  499. }
  500. if (cfg.blkorder) {
  501. if (pb->blocks > pa->blocks)
  502. return 1;
  503. else if (pb->blocks < pa->blocks)
  504. return -1;
  505. }
  506. return xstricmp(pa->name, pb->name);
  507. }
  508. /* Messages show up at the bottom */
  509. static void
  510. printmsg(char *msg)
  511. {
  512. move(LINES - 1, 0);
  513. printw("%s\n", msg);
  514. }
  515. /* Display warning as a message */
  516. static void
  517. printwarn(void)
  518. {
  519. printmsg(strerror(errno));
  520. }
  521. /* Kill curses and display error before exiting */
  522. static void
  523. printerr(int ret, char *prefix)
  524. {
  525. exitcurses();
  526. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  527. exit(ret);
  528. }
  529. /* Clear the last line */
  530. static void
  531. clearprompt(void)
  532. {
  533. printmsg("");
  534. }
  535. /* Print prompt on the last line */
  536. static void
  537. printprompt(char *str)
  538. {
  539. clearprompt();
  540. printw(str);
  541. }
  542. /* Returns SEL_* if key is bound and 0 otherwise.
  543. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  544. * The next keyboard input can be simulated by presel.
  545. */
  546. static int
  547. nextsel(char **run, char **env, int *presel)
  548. {
  549. static int c;
  550. static uchar i;
  551. static uint len = LEN(bindings);
  552. c = *presel;
  553. if (c == 0)
  554. c = getch();
  555. else
  556. *presel = 0;
  557. if (c == -1)
  558. ++idle;
  559. else
  560. idle = 0;
  561. for (i = 0; i < len; ++i)
  562. if (c == bindings[i].sym) {
  563. *run = bindings[i].run;
  564. *env = bindings[i].env;
  565. return bindings[i].act;
  566. }
  567. return 0;
  568. }
  569. /*
  570. * Move non-matching entries to the end
  571. */
  572. static void
  573. fill(struct entry **dents,
  574. int (*filter)(regex_t *, char *), regex_t *re)
  575. {
  576. static int count;
  577. for (count = 0; count < ndents; ++count) {
  578. if (filter(re, (*dents)[count].name) == 0) {
  579. if (count != --ndents) {
  580. static struct entry _dent;
  581. /* Copy count to tmp */
  582. xstrlcpy(_dent.name, (*dents)[count].name,
  583. NAME_MAX);
  584. _dent.mode = (*dents)[count].mode;
  585. _dent.t = (*dents)[count].t;
  586. _dent.size = (*dents)[count].size;
  587. _dent.blocks = (*dents)[count].blocks;
  588. /* Copy ndents - 1 to count */
  589. xstrlcpy((*dents)[count].name,
  590. (*dents)[ndents].name, NAME_MAX);
  591. (*dents)[count].mode = (*dents)[ndents].mode;
  592. (*dents)[count].t = (*dents)[ndents].t;
  593. (*dents)[count].size = (*dents)[ndents].size;
  594. (*dents)[count].blocks = (*dents)[ndents].blocks;
  595. /* Copy tmp to ndents - 1 */
  596. xstrlcpy((*dents)[ndents].name, _dent.name,
  597. NAME_MAX);
  598. (*dents)[ndents].mode = _dent.mode;
  599. (*dents)[ndents].t = _dent.t;
  600. (*dents)[ndents].size = _dent.size;
  601. (*dents)[ndents].blocks = _dent.blocks;
  602. --count;
  603. }
  604. continue;
  605. }
  606. }
  607. }
  608. static int
  609. matches(char *fltr)
  610. {
  611. static regex_t re;
  612. /* Search filter */
  613. if (setfilter(&re, fltr) != 0)
  614. return -1;
  615. fill(&dents, visible, &re);
  616. qsort(dents, ndents, sizeof(*dents), entrycmp);
  617. return 0;
  618. }
  619. static int
  620. readln(char *path)
  621. {
  622. static char ln[LINE_MAX << 2];
  623. static wchar_t wln[LINE_MAX];
  624. static wint_t ch[2] = {0};
  625. int r, total = ndents;
  626. int oldcur = cur;
  627. int len = 1;
  628. char *pln = ln + 1;
  629. memset(wln, 0, LINE_MAX << 2);
  630. wln[0] = FILTER;
  631. ln[0] = FILTER;
  632. ln[1] = '\0';
  633. cur = 0;
  634. timeout(-1);
  635. echo();
  636. curs_set(TRUE);
  637. printprompt(ln);
  638. while ((r = wget_wch(stdscr, ch)) != ERR) {
  639. if (r == OK) {
  640. switch (*ch) {
  641. case '\r': // with nonl(), this is ENTER key value
  642. if (len == 1) {
  643. cur = oldcur;
  644. goto end;
  645. }
  646. if (matches(pln) == -1)
  647. goto end;
  648. redraw(path);
  649. goto end;
  650. case 127: // handle DEL
  651. if (len == 1) {
  652. cur = oldcur;
  653. *ch = CONTROL('L');
  654. goto end;
  655. }
  656. if (len == 2)
  657. cur = oldcur;
  658. wln[--len] = '\0';
  659. wcstombs(ln, wln, LINE_MAX << 2);
  660. ndents = total;
  661. if (matches(pln) == -1) {
  662. printprompt(ln);
  663. continue;
  664. }
  665. redraw(path);
  666. printprompt(ln);
  667. break;
  668. case CONTROL('L'):
  669. if (len == 1)
  670. cur = oldcur; // fallthrough
  671. case CONTROL('Q'):
  672. goto end;
  673. default:
  674. wln[len] = (wchar_t)*ch;
  675. ++len;
  676. wln[len] = '\0';
  677. wcstombs(ln, wln, LINE_MAX << 2);
  678. ndents = total;
  679. if (matches(pln) == -1)
  680. continue;
  681. redraw(path);
  682. printprompt(ln);
  683. }
  684. } else {
  685. switch (*ch) {
  686. case KEY_DC: // fallthrough
  687. case KEY_BACKSPACE:
  688. if (len == 1) {
  689. cur = oldcur;
  690. *ch = CONTROL('L');
  691. goto end;
  692. }
  693. if (len == 2)
  694. cur = oldcur;
  695. wln[--len] = '\0';
  696. wcstombs(ln, wln, LINE_MAX << 2);
  697. ndents = total;
  698. if (matches(pln) == -1)
  699. continue;
  700. redraw(path);
  701. printprompt(ln);
  702. break;
  703. case KEY_DOWN: // fallthrough
  704. case KEY_UP: // fallthrough
  705. case KEY_LEFT: // fallthrough
  706. case KEY_RIGHT:
  707. if (len == 1)
  708. cur = oldcur; // fallthrough
  709. default:
  710. goto end;
  711. }
  712. }
  713. }
  714. end:
  715. noecho();
  716. curs_set(FALSE);
  717. timeout(1000);
  718. /* Return keys for navigation etc. */
  719. return *ch;
  720. }
  721. static int
  722. canopendir(char *path)
  723. {
  724. static DIR *dirp;
  725. dirp = opendir(path);
  726. if (dirp == NULL)
  727. return 0;
  728. closedir(dirp);
  729. return 1;
  730. }
  731. /*
  732. * Returns "dir/name or "/name"
  733. */
  734. static char *
  735. mkpath(char *dir, char *name, char *out, size_t n)
  736. {
  737. /* Handle absolute path */
  738. if (name[0] == '/')
  739. xstrlcpy(out, name, n);
  740. else {
  741. /* Handle root case */
  742. if (strcmp(dir, "/") == 0)
  743. snprintf(out, n, "/%s", name);
  744. else
  745. snprintf(out, n, "%s/%s", dir, name);
  746. }
  747. return out;
  748. }
  749. static void
  750. parsebmstr(char *bms)
  751. {
  752. int i = 0;
  753. while (*bms && i < MAX_BM) {
  754. bookmark[i].key = bms;
  755. ++bms;
  756. while (*bms && *bms != ':')
  757. ++bms;
  758. if (!*bms) {
  759. bookmark[i].key = NULL;
  760. break;
  761. }
  762. *bms = '\0';
  763. bookmark[i].loc = ++bms;
  764. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  765. bookmark[i].key = NULL;
  766. break;
  767. }
  768. while (*bms && *bms != ';')
  769. ++bms;
  770. if (*bms)
  771. *bms = '\0';
  772. else
  773. break;
  774. ++bms;
  775. ++i;
  776. }
  777. }
  778. static char *
  779. readinput(void)
  780. {
  781. timeout(-1);
  782. echo();
  783. curs_set(TRUE);
  784. memset(g_buf, 0, LINE_MAX);
  785. wgetnstr(stdscr, g_buf, LINE_MAX - 1);
  786. noecho();
  787. curs_set(FALSE);
  788. timeout(1000);
  789. return g_buf[0] ? g_buf : NULL;
  790. }
  791. static char *
  792. replace_escape(const char *str)
  793. {
  794. static char buffer[PATH_MAX];
  795. static wchar_t wbuf[PATH_MAX];
  796. static wchar_t *buf;
  797. buffer[0] = '\0';
  798. buf = wbuf;
  799. /* Convert multi-byte to wide char */
  800. mbstowcs(wbuf, str, PATH_MAX);
  801. while (*buf) {
  802. if (*buf <= '\x1f' || *buf == '\x7f')
  803. *buf = '\?';
  804. ++buf;
  805. }
  806. /* Convert wide char to multi-byte */
  807. wcstombs(buffer, wbuf, PATH_MAX);
  808. return buffer;
  809. }
  810. static void
  811. printent(struct entry *ent, int sel)
  812. {
  813. static int ncols;
  814. if (PATH_MAX + 16 < COLS)
  815. ncols = PATH_MAX + 16;
  816. else
  817. ncols = COLS;
  818. if (S_ISDIR(ent->mode))
  819. snprintf(g_buf, ncols, "%s%s/", CURSYM(sel),
  820. replace_escape(ent->name));
  821. else if (S_ISLNK(ent->mode))
  822. snprintf(g_buf, ncols, "%s%s@", CURSYM(sel),
  823. replace_escape(ent->name));
  824. else if (S_ISSOCK(ent->mode))
  825. snprintf(g_buf, ncols, "%s%s=", CURSYM(sel),
  826. replace_escape(ent->name));
  827. else if (S_ISFIFO(ent->mode))
  828. snprintf(g_buf, ncols, "%s%s|", CURSYM(sel),
  829. replace_escape(ent->name));
  830. else if (ent->mode & 0100)
  831. snprintf(g_buf, ncols, "%s%s*", CURSYM(sel),
  832. replace_escape(ent->name));
  833. else
  834. snprintf(g_buf, ncols, "%s%s", CURSYM(sel),
  835. replace_escape(ent->name));
  836. printw("%s\n", g_buf);
  837. }
  838. static char*
  839. coolsize(off_t size)
  840. {
  841. static const char * const U[]
  842. = {"B", "K", "M", "G", "T", "P", "E", "Z", "Y"};
  843. static char size_buf[12]; /* Buffer to hold human readable size */
  844. static int i;
  845. static off_t tmp;
  846. static long double rem;
  847. i = 0;
  848. rem = 0;
  849. while (size > 1024) {
  850. tmp = size;
  851. size >>= 10;
  852. rem = tmp - (size << 10);
  853. ++i;
  854. }
  855. snprintf(size_buf, 12, "%.*Lf%s", i, size + rem * div_2_pow_10, U[i]);
  856. return size_buf;
  857. }
  858. static void
  859. printent_long(struct entry *ent, int sel)
  860. {
  861. static int ncols;
  862. static char buf[18];
  863. if (PATH_MAX + 32 < COLS)
  864. ncols = PATH_MAX + 32;
  865. else
  866. ncols = COLS;
  867. strftime(buf, 18, "%d %m %Y %H:%M", localtime(&ent->t));
  868. if (sel)
  869. attron(A_REVERSE);
  870. if (!cfg.blkorder) {
  871. if (S_ISDIR(ent->mode))
  872. snprintf(g_buf, ncols, "%s%-16.16s / %s/",
  873. CURSYM(sel), buf, replace_escape(ent->name));
  874. else if (S_ISLNK(ent->mode))
  875. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  876. CURSYM(sel), buf, replace_escape(ent->name));
  877. else if (S_ISSOCK(ent->mode))
  878. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  879. CURSYM(sel), buf, replace_escape(ent->name));
  880. else if (S_ISFIFO(ent->mode))
  881. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  882. CURSYM(sel), buf, replace_escape(ent->name));
  883. else if (S_ISBLK(ent->mode))
  884. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  885. CURSYM(sel), buf, replace_escape(ent->name));
  886. else if (S_ISCHR(ent->mode))
  887. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  888. CURSYM(sel), buf, replace_escape(ent->name));
  889. else if (ent->mode & 0100)
  890. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  891. CURSYM(sel), buf, coolsize(ent->size),
  892. replace_escape(ent->name));
  893. else
  894. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  895. CURSYM(sel), buf, coolsize(ent->size),
  896. replace_escape(ent->name));
  897. } else {
  898. if (S_ISDIR(ent->mode))
  899. snprintf(g_buf, ncols, "%s%-16.16s %8.8s/ %s/",
  900. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  901. replace_escape(ent->name));
  902. else if (S_ISLNK(ent->mode))
  903. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  904. CURSYM(sel), buf,
  905. replace_escape(ent->name));
  906. else if (S_ISSOCK(ent->mode))
  907. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  908. CURSYM(sel), buf,
  909. replace_escape(ent->name));
  910. else if (S_ISFIFO(ent->mode))
  911. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  912. CURSYM(sel), buf,
  913. replace_escape(ent->name));
  914. else if (S_ISBLK(ent->mode))
  915. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  916. CURSYM(sel), buf,
  917. replace_escape(ent->name));
  918. else if (S_ISCHR(ent->mode))
  919. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  920. CURSYM(sel), buf,
  921. replace_escape(ent->name));
  922. else if (ent->mode & 0100)
  923. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  924. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  925. replace_escape(ent->name));
  926. else
  927. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  928. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  929. replace_escape(ent->name));
  930. }
  931. printw("%s\n", g_buf);
  932. if (sel)
  933. attroff(A_REVERSE);
  934. }
  935. static void (*printptr)(struct entry *ent, int sel) = &printent_long;
  936. static char
  937. get_fileind(mode_t mode, char *desc)
  938. {
  939. static char c;
  940. if (S_ISREG(mode)) {
  941. c = '-';
  942. sprintf(desc, "%s", "regular file");
  943. if (mode & 0100)
  944. strcat(desc, ", executable");
  945. } else if (S_ISDIR(mode)) {
  946. c = 'd';
  947. sprintf(desc, "%s", "directory");
  948. } else if (S_ISBLK(mode)) {
  949. c = 'b';
  950. sprintf(desc, "%s", "block special device");
  951. } else if (S_ISCHR(mode)) {
  952. c = 'c';
  953. sprintf(desc, "%s", "character special device");
  954. #ifdef S_ISFIFO
  955. } else if (S_ISFIFO(mode)) {
  956. c = 'p';
  957. sprintf(desc, "%s", "FIFO");
  958. #endif /* S_ISFIFO */
  959. #ifdef S_ISLNK
  960. } else if (S_ISLNK(mode)) {
  961. c = 'l';
  962. sprintf(desc, "%s", "symbolic link");
  963. #endif /* S_ISLNK */
  964. #ifdef S_ISSOCK
  965. } else if (S_ISSOCK(mode)) {
  966. c = 's';
  967. sprintf(desc, "%s", "socket");
  968. #endif /* S_ISSOCK */
  969. #ifdef S_ISDOOR
  970. /* Solaris 2.6, etc. */
  971. } else if (S_ISDOOR(mode)) {
  972. c = 'D';
  973. desc[0] = '\0';
  974. #endif /* S_ISDOOR */
  975. } else {
  976. /* Unknown type -- possibly a regular file? */
  977. c = '?';
  978. desc[0] = '\0';
  979. }
  980. return c;
  981. }
  982. /* Convert a mode field into "ls -l" type perms field. */
  983. static char *
  984. get_lsperms(mode_t mode, char *desc)
  985. {
  986. static const char * const rwx[] = {"---", "--x", "-w-", "-wx",
  987. "r--", "r-x", "rw-", "rwx"};
  988. static char bits[11];
  989. bits[0] = get_fileind(mode, desc);
  990. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  991. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  992. strcpy(&bits[7], rwx[(mode & 7)]);
  993. if (mode & S_ISUID)
  994. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  995. if (mode & S_ISGID)
  996. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  997. if (mode & S_ISVTX)
  998. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  999. bits[10] = '\0';
  1000. return bits;
  1001. }
  1002. /*
  1003. * Gets only a single line (that's what we need
  1004. * for now) or shows full command output in pager.
  1005. *
  1006. * If pager is valid, returns NULL
  1007. */
  1008. static char *
  1009. get_output(char *buf, size_t bytes, char *file,
  1010. char *arg1, char *arg2, int pager)
  1011. {
  1012. pid_t pid;
  1013. int pipefd[2];
  1014. FILE *pf;
  1015. int status;
  1016. char *ret = NULL;
  1017. if (pipe(pipefd) == -1)
  1018. printerr(1, "pipe(2)");
  1019. pid = fork();
  1020. if (pid == 0) {
  1021. /* In child */
  1022. close(pipefd[0]);
  1023. dup2(pipefd[1], STDOUT_FILENO);
  1024. dup2(pipefd[1], STDERR_FILENO);
  1025. execlp(file, file, arg1, arg2, NULL);
  1026. _exit(1);
  1027. }
  1028. /* In parent */
  1029. waitpid(pid, &status, 0);
  1030. close(pipefd[1]);
  1031. if (!pager) {
  1032. pf = fdopen(pipefd[0], "r");
  1033. if (pf) {
  1034. ret = fgets(buf, bytes, pf);
  1035. close(pipefd[0]);
  1036. }
  1037. return ret;
  1038. }
  1039. pid = fork();
  1040. if (pid == 0) {
  1041. /* Show in pager in child */
  1042. dup2(pipefd[0], STDIN_FILENO);
  1043. execlp("less", "less", NULL);
  1044. close(pipefd[0]);
  1045. _exit(1);
  1046. }
  1047. /* In parent */
  1048. waitpid(pid, &status, 0);
  1049. return NULL;
  1050. }
  1051. /*
  1052. * Follows the stat(1) output closely
  1053. */
  1054. static int
  1055. show_stats(char *fpath, char *fname, struct stat *sb)
  1056. {
  1057. char *perms = get_lsperms(sb->st_mode, g_buf);
  1058. char *p, *begin = g_buf;
  1059. char tmp[] = "/tmp/nnnXXXXXX";
  1060. int fd = mkstemp(tmp);
  1061. if (fd == -1)
  1062. return -1;
  1063. /* Show file name or 'symlink' -> 'target' */
  1064. if (perms[0] == 'l') {
  1065. /* Note that MAX_CMD_LEN > PATH_MAX */
  1066. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1067. if (len != -1) {
  1068. g_buf[len] = '\0';
  1069. dprintf(fd, " File: '%s' -> ",
  1070. replace_escape(fname));
  1071. dprintf(fd, "'%s'",
  1072. replace_escape(g_buf));
  1073. }
  1074. } else
  1075. dprintf(fd, " File: '%s'", replace_escape(fname));
  1076. /* Show size, blocks, file type */
  1077. #ifdef __APPLE__
  1078. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1079. #else
  1080. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1081. #endif
  1082. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1083. /* Show containing device, inode, hardlink count */
  1084. #ifdef __APPLE__
  1085. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1086. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1087. #else
  1088. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1089. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1090. #endif
  1091. g_buf, sb->st_ino, sb->st_nlink);
  1092. /* Show major, minor number for block or char device */
  1093. if (perms[0] == 'b' || perms[0] == 'c')
  1094. dprintf(fd, " Device type: %x,%x",
  1095. major(sb->st_rdev), minor(sb->st_rdev));
  1096. /* Show permissions, owner, group */
  1097. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1098. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  1099. perms,
  1100. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  1101. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1102. /* Show last access time */
  1103. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1104. dprintf(fd, "\n\n Access: %s", g_buf);
  1105. /* Show last modification time */
  1106. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1107. dprintf(fd, "\n Modify: %s", g_buf);
  1108. /* Show last status change time */
  1109. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1110. dprintf(fd, "\n Change: %s", g_buf);
  1111. if (S_ISREG(sb->st_mode)) {
  1112. /* Show file(1) output */
  1113. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1114. if (p) {
  1115. dprintf(fd, "\n\n ");
  1116. while (*p) {
  1117. if (*p == ',') {
  1118. *p = '\0';
  1119. dprintf(fd, " %s\n", begin);
  1120. begin = p + 1;
  1121. }
  1122. ++p;
  1123. }
  1124. dprintf(fd, " %s", begin);
  1125. }
  1126. dprintf(fd, "\n\n");
  1127. } else
  1128. dprintf(fd, "\n\n\n");
  1129. close(fd);
  1130. exitcurses();
  1131. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1132. unlink(tmp);
  1133. initcurses();
  1134. return 0;
  1135. }
  1136. static int
  1137. show_mediainfo(char *fpath, char *arg)
  1138. {
  1139. if (!get_output(g_buf, MAX_CMD_LEN, "which", "mediainfo", NULL, 0))
  1140. return -1;
  1141. exitcurses();
  1142. get_output(NULL, 0, "mediainfo", fpath, arg, 1);
  1143. initcurses();
  1144. return 0;
  1145. }
  1146. static int
  1147. show_help(void)
  1148. {
  1149. char tmp[] = "/tmp/nnnXXXXXX";
  1150. static char helpstr[] = ("\
  1151. Key | Function\n\
  1152. -+-\n\
  1153. Up, k, ^P | Previous entry\n\
  1154. Down, j, ^N | Next entry\n\
  1155. PgUp, ^U | Scroll half page up\n\
  1156. PgDn, ^D | Scroll half page down\n\
  1157. Home, g, ^, ^A | Jump to first entry\n\
  1158. End, G, $, ^E | Jump to last entry\n\
  1159. Right, Enter, l, ^M | Open file or enter dir\n\
  1160. Left, Bksp, h, ^H | Go to parent dir\n\
  1161. Insert | Toggle navigate-as-you-type mode\n\
  1162. ~ | Jump to HOME dir\n\
  1163. & | Jump to initial dir\n\
  1164. - | Jump to last visited dir\n\
  1165. / | Filter dir contents\n\
  1166. ^/ | Search dir in desktop search tool\n\
  1167. . | Toggle hide .dot files\n\
  1168. b | Show bookmark key prompt\n\
  1169. c | Show change dir prompt\n\
  1170. d | Toggle detail view\n\
  1171. D | Toggle current file details screen\n\
  1172. m | Show concise mediainfo\n\
  1173. M | Show full mediainfo\n\
  1174. s | Toggle sort by file size\n\
  1175. S | Toggle disk usage analyzer mode\n\
  1176. t | Toggle sort by modified time\n\
  1177. ! | Spawn SHELL in PWD (fallback sh)\n\
  1178. e | Edit entry in EDITOR (fallback vi)\n\
  1179. o | Open dir in NNN_DE_FILE_MANAGER\n\
  1180. p | Open entry in PAGER (fallback less)\n\
  1181. ^K | Invoke file path copier\n\
  1182. ^L | Force a redraw, exit filter prompt\n\
  1183. ? | Toggle help and settings screen\n\
  1184. Q | Quit and change directory\n\
  1185. q, ^Q | Quit\n\n\n");
  1186. int i = 0, fd = mkstemp(tmp);
  1187. if (fd == -1)
  1188. return -1;
  1189. dprintf(fd, "%s", helpstr);
  1190. if (getenv("NNN_BMS")) {
  1191. dprintf(fd, "BOOKMARKS\n");
  1192. for (; i < MAX_BM; ++i)
  1193. if (bookmark[i].key)
  1194. dprintf(fd, " %s: %s\n",
  1195. bookmark[i].key, bookmark[i].loc);
  1196. else
  1197. break;
  1198. dprintf(fd, "\n");
  1199. }
  1200. if (editor)
  1201. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1202. if (desktop_manager)
  1203. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1204. if (idletimeout)
  1205. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1206. if (copier)
  1207. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1208. dprintf(fd, "\n");
  1209. close(fd);
  1210. exitcurses();
  1211. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1212. unlink(tmp);
  1213. initcurses();
  1214. return 0;
  1215. }
  1216. static int
  1217. sum_bsizes(const char *fpath, const struct stat *sb,
  1218. int typeflag, struct FTW *ftwbuf)
  1219. {
  1220. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1221. ent_blocks += sb->st_blocks;
  1222. ++num_files;
  1223. return 0;
  1224. }
  1225. static int
  1226. getorder(size_t size)
  1227. {
  1228. switch (size) {
  1229. case 4096:
  1230. return 12;
  1231. case 512:
  1232. return 9;
  1233. case 8192:
  1234. return 13;
  1235. case 16384:
  1236. return 14;
  1237. case 32768:
  1238. return 15;
  1239. case 65536:
  1240. return 16;
  1241. case 131072:
  1242. return 17;
  1243. case 262144:
  1244. return 18;
  1245. case 524288:
  1246. return 19;
  1247. case 1048576:
  1248. return 20;
  1249. case 2048:
  1250. return 11;
  1251. case 1024:
  1252. return 10;
  1253. default:
  1254. return 0;
  1255. }
  1256. }
  1257. static int
  1258. dentfill(char *path, struct entry **dents,
  1259. int (*filter)(regex_t *, char *), regex_t *re)
  1260. {
  1261. static DIR *dirp;
  1262. static struct dirent *dp;
  1263. static struct stat sb;
  1264. static int fd, n;
  1265. n = 0;
  1266. if (cfg.blkorder) {
  1267. num_files = 0;
  1268. dir_blocks = 0;
  1269. }
  1270. dirp = opendir(path);
  1271. if (dirp == NULL)
  1272. return 0;
  1273. fd = dirfd(dirp);
  1274. while ((dp = readdir(dirp)) != NULL) {
  1275. /* Skip self and parent */
  1276. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  1277. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  1278. continue;
  1279. if (filter(re, dp->d_name) == 0) {
  1280. if (!cfg.blkorder)
  1281. continue;
  1282. if (fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1283. continue;
  1284. if (S_ISDIR(sb.st_mode)) {
  1285. ent_blocks = 0;
  1286. mkpath(path, dp->d_name, g_buf, PATH_MAX);
  1287. if (nftw(g_buf, sum_bsizes, open_max,
  1288. FTW_MOUNT | FTW_PHYS) == -1) {
  1289. printmsg("nftw(3) failed");
  1290. dir_blocks += sb.st_blocks;
  1291. } else
  1292. dir_blocks += ent_blocks;
  1293. } else {
  1294. if (sb.st_blocks)
  1295. dir_blocks += sb.st_blocks;
  1296. ++num_files;
  1297. }
  1298. continue;
  1299. }
  1300. if (fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1301. if (*dents)
  1302. free(*dents);
  1303. printerr(1, "fstatat");
  1304. }
  1305. if (n == total_dents) {
  1306. total_dents += 64;
  1307. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1308. if (*dents == NULL)
  1309. printerr(1, "realloc");
  1310. }
  1311. xstrlcpy((*dents)[n].name, dp->d_name, NAME_MAX);
  1312. (*dents)[n].mode = sb.st_mode;
  1313. (*dents)[n].t = sb.st_mtime;
  1314. (*dents)[n].size = sb.st_size;
  1315. if (cfg.blkorder) {
  1316. if (S_ISDIR(sb.st_mode)) {
  1317. ent_blocks = 0;
  1318. mkpath(path, dp->d_name, g_buf, PATH_MAX);
  1319. if (nftw(g_buf, sum_bsizes, open_max,
  1320. FTW_MOUNT | FTW_PHYS) == -1) {
  1321. printmsg("nftw(3) failed");
  1322. (*dents)[n].blocks = sb.st_blocks;
  1323. } else
  1324. (*dents)[n].blocks = ent_blocks;
  1325. } else {
  1326. (*dents)[n].blocks = sb.st_blocks;
  1327. ++num_files;
  1328. }
  1329. if ((*dents)[n].blocks)
  1330. dir_blocks += (*dents)[n].blocks;
  1331. }
  1332. ++n;
  1333. }
  1334. if (cfg.blkorder) {
  1335. static struct statvfs svb;
  1336. if (statvfs(path, &svb) == -1)
  1337. fs_free = 0;
  1338. else
  1339. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1340. }
  1341. /* Should never be null */
  1342. if (closedir(dirp) == -1) {
  1343. if (*dents)
  1344. free(*dents);
  1345. printerr(1, "closedir");
  1346. }
  1347. return n;
  1348. }
  1349. static void
  1350. dentfree(struct entry *dents)
  1351. {
  1352. free(dents);
  1353. }
  1354. /* Return the position of the matching entry or 0 otherwise */
  1355. static int
  1356. dentfind(struct entry *dents, int n, char *path)
  1357. {
  1358. if (!path)
  1359. return 0;
  1360. static int i;
  1361. static char *p;
  1362. p = basename(path);
  1363. DPRINTF_S(p);
  1364. for (i = 0; i < n; ++i)
  1365. if (strcmp(p, dents[i].name) == 0)
  1366. return i;
  1367. return 0;
  1368. }
  1369. static int
  1370. populate(char *path, char *oldpath, char *fltr)
  1371. {
  1372. static regex_t re;
  1373. /* Can fail when permissions change while browsing */
  1374. if (canopendir(path) == 0)
  1375. return -1;
  1376. /* Search filter */
  1377. if (setfilter(&re, fltr) != 0)
  1378. return -1;
  1379. if (cfg.blkorder) {
  1380. timeout(0);
  1381. printmsg("Calculating...");
  1382. getch();
  1383. timeout(1000);
  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. #ifdef DEBUGMODE
  2102. enabledbg();
  2103. #endif
  2104. /* Set locale */
  2105. setlocale(LC_ALL, "");
  2106. initcurses();
  2107. browse(ipath, ifilter);
  2108. exitcurses();
  2109. #ifdef DEBUGMODE
  2110. disabledbg();
  2111. #endif
  2112. exit(0);
  2113. }