My build of nnn with minor changes
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

2468 строки
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. mvprintw(LINES - 1, 0, "%s\n", msg);
  513. }
  514. /* Display warning as a message */
  515. static void
  516. printwarn(void)
  517. {
  518. printmsg(strerror(errno));
  519. }
  520. /* Kill curses and display error before exiting */
  521. static void
  522. printerr(int ret, char *prefix)
  523. {
  524. exitcurses();
  525. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  526. exit(ret);
  527. }
  528. /* Clear the last line */
  529. static void
  530. clearprompt(void)
  531. {
  532. printmsg("");
  533. }
  534. /* Print prompt on the last line */
  535. static void
  536. printprompt(char *str)
  537. {
  538. clearprompt();
  539. printw(str);
  540. }
  541. /* Returns SEL_* if key is bound and 0 otherwise.
  542. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  543. * The next keyboard input can be simulated by presel.
  544. */
  545. static int
  546. nextsel(char **run, char **env, int *presel)
  547. {
  548. static int c;
  549. static uchar i;
  550. static uint len = LEN(bindings);
  551. c = *presel;
  552. if (c == 0)
  553. c = getch();
  554. else
  555. *presel = 0;
  556. if (c == -1)
  557. ++idle;
  558. else
  559. idle = 0;
  560. for (i = 0; i < len; ++i)
  561. if (c == bindings[i].sym) {
  562. *run = bindings[i].run;
  563. *env = bindings[i].env;
  564. return bindings[i].act;
  565. }
  566. return 0;
  567. }
  568. /*
  569. * Move non-matching entries to the end
  570. */
  571. static void
  572. fill(struct entry **dents,
  573. int (*filter)(regex_t *, char *), regex_t *re)
  574. {
  575. static int count;
  576. for (count = 0; count < ndents; ++count) {
  577. if (filter(re, (*dents)[count].name) == 0) {
  578. if (count != --ndents) {
  579. static struct entry _dent;
  580. /* Copy count to tmp */
  581. xstrlcpy(_dent.name, (*dents)[count].name,
  582. NAME_MAX);
  583. _dent.mode = (*dents)[count].mode;
  584. _dent.t = (*dents)[count].t;
  585. _dent.size = (*dents)[count].size;
  586. _dent.blocks = (*dents)[count].blocks;
  587. /* Copy ndents - 1 to count */
  588. xstrlcpy((*dents)[count].name,
  589. (*dents)[ndents].name, NAME_MAX);
  590. (*dents)[count].mode = (*dents)[ndents].mode;
  591. (*dents)[count].t = (*dents)[ndents].t;
  592. (*dents)[count].size = (*dents)[ndents].size;
  593. (*dents)[count].blocks = (*dents)[ndents].blocks;
  594. /* Copy tmp to ndents - 1 */
  595. xstrlcpy((*dents)[ndents].name, _dent.name,
  596. NAME_MAX);
  597. (*dents)[ndents].mode = _dent.mode;
  598. (*dents)[ndents].t = _dent.t;
  599. (*dents)[ndents].size = _dent.size;
  600. (*dents)[ndents].blocks = _dent.blocks;
  601. --count;
  602. }
  603. continue;
  604. }
  605. }
  606. }
  607. static int
  608. matches(char *fltr)
  609. {
  610. static regex_t re;
  611. /* Search filter */
  612. if (setfilter(&re, fltr) != 0)
  613. return -1;
  614. fill(&dents, visible, &re);
  615. qsort(dents, ndents, sizeof(*dents), entrycmp);
  616. return 0;
  617. }
  618. static int
  619. readln(char *path)
  620. {
  621. static char ln[LINE_MAX << 2];
  622. static wchar_t wln[LINE_MAX];
  623. static wint_t ch[2] = {0};
  624. int r, total = ndents;
  625. int oldcur = cur;
  626. int len = 1;
  627. char *pln = ln + 1;
  628. memset(wln, 0, LINE_MAX << 2);
  629. wln[0] = FILTER;
  630. ln[0] = FILTER;
  631. ln[1] = '\0';
  632. cur = 0;
  633. timeout(-1);
  634. echo();
  635. curs_set(TRUE);
  636. printprompt(ln);
  637. while ((r = wget_wch(stdscr, ch)) != ERR) {
  638. if (r == OK) {
  639. switch (*ch) {
  640. case '\r': // with nonl(), this is ENTER key value
  641. if (len == 1) {
  642. cur = oldcur;
  643. goto end;
  644. }
  645. if (matches(pln) == -1)
  646. goto end;
  647. redraw(path);
  648. goto end;
  649. case 127: // handle DEL
  650. if (len == 1) {
  651. cur = oldcur;
  652. *ch = CONTROL('L');
  653. goto end;
  654. }
  655. if (len == 2)
  656. cur = oldcur;
  657. wln[--len] = '\0';
  658. wcstombs(ln, wln, LINE_MAX << 2);
  659. ndents = total;
  660. if (matches(pln) == -1) {
  661. printprompt(ln);
  662. continue;
  663. }
  664. redraw(path);
  665. printprompt(ln);
  666. break;
  667. case CONTROL('L'):
  668. if (len == 1)
  669. cur = oldcur; // fallthrough
  670. case CONTROL('Q'):
  671. goto end;
  672. default:
  673. wln[len] = (wchar_t)*ch;
  674. ++len;
  675. wln[len] = '\0';
  676. wcstombs(ln, wln, LINE_MAX << 2);
  677. ndents = total;
  678. if (matches(pln) == -1)
  679. continue;
  680. redraw(path);
  681. printprompt(ln);
  682. }
  683. } else {
  684. switch (*ch) {
  685. case KEY_DC: // fallthrough
  686. case KEY_BACKSPACE:
  687. if (len == 1) {
  688. cur = oldcur;
  689. *ch = CONTROL('L');
  690. goto end;
  691. }
  692. if (len == 2)
  693. cur = oldcur;
  694. wln[--len] = '\0';
  695. wcstombs(ln, wln, LINE_MAX << 2);
  696. ndents = total;
  697. if (matches(pln) == -1)
  698. continue;
  699. redraw(path);
  700. printprompt(ln);
  701. break;
  702. case KEY_DOWN: // fallthrough
  703. case KEY_UP: // fallthrough
  704. case KEY_LEFT: // fallthrough
  705. case KEY_RIGHT:
  706. if (len == 1)
  707. cur = oldcur; // fallthrough
  708. default:
  709. goto end;
  710. }
  711. }
  712. }
  713. end:
  714. noecho();
  715. curs_set(FALSE);
  716. timeout(1000);
  717. /* Return keys for navigation etc. */
  718. return *ch;
  719. }
  720. static int
  721. canopendir(char *path)
  722. {
  723. static DIR *dirp;
  724. dirp = opendir(path);
  725. if (dirp == NULL)
  726. return 0;
  727. closedir(dirp);
  728. return 1;
  729. }
  730. /*
  731. * Returns "dir/name or "/name"
  732. */
  733. static char *
  734. mkpath(char *dir, char *name, char *out, size_t n)
  735. {
  736. /* Handle absolute path */
  737. if (name[0] == '/')
  738. xstrlcpy(out, name, n);
  739. else {
  740. /* Handle root case */
  741. if (strcmp(dir, "/") == 0)
  742. snprintf(out, n, "/%s", name);
  743. else
  744. snprintf(out, n, "%s/%s", dir, name);
  745. }
  746. return out;
  747. }
  748. static void
  749. parsebmstr(char *bms)
  750. {
  751. int i = 0;
  752. while (*bms && i < MAX_BM) {
  753. bookmark[i].key = bms;
  754. ++bms;
  755. while (*bms && *bms != ':')
  756. ++bms;
  757. if (!*bms) {
  758. bookmark[i].key = NULL;
  759. break;
  760. }
  761. *bms = '\0';
  762. bookmark[i].loc = ++bms;
  763. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  764. bookmark[i].key = NULL;
  765. break;
  766. }
  767. while (*bms && *bms != ';')
  768. ++bms;
  769. if (*bms)
  770. *bms = '\0';
  771. else
  772. break;
  773. ++bms;
  774. ++i;
  775. }
  776. }
  777. static char *
  778. readinput(void)
  779. {
  780. timeout(-1);
  781. echo();
  782. curs_set(TRUE);
  783. memset(g_buf, 0, LINE_MAX);
  784. wgetnstr(stdscr, g_buf, LINE_MAX - 1);
  785. noecho();
  786. curs_set(FALSE);
  787. timeout(1000);
  788. return g_buf[0] ? g_buf : NULL;
  789. }
  790. static char *
  791. replace_escape(const char *str)
  792. {
  793. static char buffer[PATH_MAX];
  794. static wchar_t wbuf[PATH_MAX];
  795. static wchar_t *buf;
  796. buffer[0] = '\0';
  797. buf = wbuf;
  798. /* Convert multi-byte to wide char */
  799. mbstowcs(wbuf, str, PATH_MAX);
  800. while (*buf) {
  801. if (*buf <= '\x1f' || *buf == '\x7f')
  802. *buf = '\?';
  803. ++buf;
  804. }
  805. /* Convert wide char to multi-byte */
  806. wcstombs(buffer, wbuf, PATH_MAX);
  807. return buffer;
  808. }
  809. static void
  810. printent(struct entry *ent, int sel)
  811. {
  812. static int ncols;
  813. if (PATH_MAX + 16 < COLS)
  814. ncols = PATH_MAX + 16;
  815. else
  816. ncols = COLS;
  817. if (S_ISDIR(ent->mode))
  818. snprintf(g_buf, ncols, "%s%s/", CURSYM(sel),
  819. replace_escape(ent->name));
  820. else if (S_ISLNK(ent->mode))
  821. snprintf(g_buf, ncols, "%s%s@", CURSYM(sel),
  822. replace_escape(ent->name));
  823. else if (S_ISSOCK(ent->mode))
  824. snprintf(g_buf, ncols, "%s%s=", CURSYM(sel),
  825. replace_escape(ent->name));
  826. else if (S_ISFIFO(ent->mode))
  827. snprintf(g_buf, ncols, "%s%s|", CURSYM(sel),
  828. replace_escape(ent->name));
  829. else if (ent->mode & 0100)
  830. snprintf(g_buf, ncols, "%s%s*", CURSYM(sel),
  831. replace_escape(ent->name));
  832. else
  833. snprintf(g_buf, ncols, "%s%s", CURSYM(sel),
  834. replace_escape(ent->name));
  835. printw("%s\n", g_buf);
  836. }
  837. static char*
  838. coolsize(off_t size)
  839. {
  840. static const char * const U[]
  841. = {"B", "K", "M", "G", "T", "P", "E", "Z", "Y"};
  842. static char size_buf[12]; /* Buffer to hold human readable size */
  843. static int i;
  844. static off_t tmp;
  845. static long double rem;
  846. i = 0;
  847. rem = 0;
  848. while (size > 1024) {
  849. tmp = size;
  850. size >>= 10;
  851. rem = tmp - (size << 10);
  852. ++i;
  853. }
  854. snprintf(size_buf, 12, "%.*Lf%s", i, size + rem * div_2_pow_10, U[i]);
  855. return size_buf;
  856. }
  857. static void
  858. printent_long(struct entry *ent, int sel)
  859. {
  860. static int ncols;
  861. static char buf[18];
  862. if (PATH_MAX + 32 < COLS)
  863. ncols = PATH_MAX + 32;
  864. else
  865. ncols = COLS;
  866. strftime(buf, 18, "%d %m %Y %H:%M", localtime(&ent->t));
  867. if (sel)
  868. attron(A_REVERSE);
  869. if (!cfg.blkorder) {
  870. if (S_ISDIR(ent->mode))
  871. snprintf(g_buf, ncols, "%s%-16.16s / %s/",
  872. CURSYM(sel), buf, replace_escape(ent->name));
  873. else if (S_ISLNK(ent->mode))
  874. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  875. CURSYM(sel), buf, replace_escape(ent->name));
  876. else if (S_ISSOCK(ent->mode))
  877. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  878. CURSYM(sel), buf, replace_escape(ent->name));
  879. else if (S_ISFIFO(ent->mode))
  880. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  881. CURSYM(sel), buf, replace_escape(ent->name));
  882. else if (S_ISBLK(ent->mode))
  883. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  884. CURSYM(sel), buf, replace_escape(ent->name));
  885. else if (S_ISCHR(ent->mode))
  886. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  887. CURSYM(sel), buf, replace_escape(ent->name));
  888. else if (ent->mode & 0100)
  889. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  890. CURSYM(sel), buf, coolsize(ent->size),
  891. replace_escape(ent->name));
  892. else
  893. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  894. CURSYM(sel), buf, coolsize(ent->size),
  895. replace_escape(ent->name));
  896. } else {
  897. if (S_ISDIR(ent->mode))
  898. snprintf(g_buf, ncols, "%s%-16.16s %8.8s/ %s/",
  899. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  900. replace_escape(ent->name));
  901. else if (S_ISLNK(ent->mode))
  902. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  903. CURSYM(sel), buf,
  904. replace_escape(ent->name));
  905. else if (S_ISSOCK(ent->mode))
  906. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  907. CURSYM(sel), buf,
  908. replace_escape(ent->name));
  909. else if (S_ISFIFO(ent->mode))
  910. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  911. CURSYM(sel), buf,
  912. replace_escape(ent->name));
  913. else if (S_ISBLK(ent->mode))
  914. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  915. CURSYM(sel), buf,
  916. replace_escape(ent->name));
  917. else if (S_ISCHR(ent->mode))
  918. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  919. CURSYM(sel), buf,
  920. replace_escape(ent->name));
  921. else if (ent->mode & 0100)
  922. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  923. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  924. replace_escape(ent->name));
  925. else
  926. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  927. CURSYM(sel), buf, coolsize(ent->blocks << 9),
  928. replace_escape(ent->name));
  929. }
  930. printw("%s\n", g_buf);
  931. if (sel)
  932. attroff(A_REVERSE);
  933. }
  934. static void (*printptr)(struct entry *ent, int sel) = &printent_long;
  935. static char
  936. get_fileind(mode_t mode, char *desc)
  937. {
  938. static char c;
  939. if (S_ISREG(mode)) {
  940. c = '-';
  941. sprintf(desc, "%s", "regular file");
  942. if (mode & 0100)
  943. strcat(desc, ", executable");
  944. } else if (S_ISDIR(mode)) {
  945. c = 'd';
  946. sprintf(desc, "%s", "directory");
  947. } else if (S_ISBLK(mode)) {
  948. c = 'b';
  949. sprintf(desc, "%s", "block special device");
  950. } else if (S_ISCHR(mode)) {
  951. c = 'c';
  952. sprintf(desc, "%s", "character special device");
  953. #ifdef S_ISFIFO
  954. } else if (S_ISFIFO(mode)) {
  955. c = 'p';
  956. sprintf(desc, "%s", "FIFO");
  957. #endif /* S_ISFIFO */
  958. #ifdef S_ISLNK
  959. } else if (S_ISLNK(mode)) {
  960. c = 'l';
  961. sprintf(desc, "%s", "symbolic link");
  962. #endif /* S_ISLNK */
  963. #ifdef S_ISSOCK
  964. } else if (S_ISSOCK(mode)) {
  965. c = 's';
  966. sprintf(desc, "%s", "socket");
  967. #endif /* S_ISSOCK */
  968. #ifdef S_ISDOOR
  969. /* Solaris 2.6, etc. */
  970. } else if (S_ISDOOR(mode)) {
  971. c = 'D';
  972. desc[0] = '\0';
  973. #endif /* S_ISDOOR */
  974. } else {
  975. /* Unknown type -- possibly a regular file? */
  976. c = '?';
  977. desc[0] = '\0';
  978. }
  979. return c;
  980. }
  981. /* Convert a mode field into "ls -l" type perms field. */
  982. static char *
  983. get_lsperms(mode_t mode, char *desc)
  984. {
  985. static const char * const rwx[] = {"---", "--x", "-w-", "-wx",
  986. "r--", "r-x", "rw-", "rwx"};
  987. static char bits[11];
  988. bits[0] = get_fileind(mode, desc);
  989. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  990. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  991. strcpy(&bits[7], rwx[(mode & 7)]);
  992. if (mode & S_ISUID)
  993. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  994. if (mode & S_ISGID)
  995. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  996. if (mode & S_ISVTX)
  997. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  998. bits[10] = '\0';
  999. return bits;
  1000. }
  1001. /*
  1002. * Gets only a single line (that's what we need
  1003. * for now) or shows full command output in pager.
  1004. *
  1005. * If pager is valid, returns NULL
  1006. */
  1007. static char *
  1008. get_output(char *buf, size_t bytes, char *file,
  1009. char *arg1, char *arg2, int pager)
  1010. {
  1011. pid_t pid;
  1012. int pipefd[2];
  1013. FILE *pf;
  1014. int status;
  1015. char *ret = NULL;
  1016. if (pipe(pipefd) == -1)
  1017. printerr(1, "pipe(2)");
  1018. pid = fork();
  1019. if (pid == 0) {
  1020. /* In child */
  1021. close(pipefd[0]);
  1022. dup2(pipefd[1], STDOUT_FILENO);
  1023. dup2(pipefd[1], STDERR_FILENO);
  1024. execlp(file, file, arg1, arg2, NULL);
  1025. _exit(1);
  1026. }
  1027. /* In parent */
  1028. waitpid(pid, &status, 0);
  1029. close(pipefd[1]);
  1030. if (!pager) {
  1031. pf = fdopen(pipefd[0], "r");
  1032. if (pf) {
  1033. ret = fgets(buf, bytes, pf);
  1034. close(pipefd[0]);
  1035. }
  1036. return ret;
  1037. }
  1038. pid = fork();
  1039. if (pid == 0) {
  1040. /* Show in pager in child */
  1041. dup2(pipefd[0], STDIN_FILENO);
  1042. execlp("less", "less", NULL);
  1043. close(pipefd[0]);
  1044. _exit(1);
  1045. }
  1046. /* In parent */
  1047. waitpid(pid, &status, 0);
  1048. return NULL;
  1049. }
  1050. /*
  1051. * Follows the stat(1) output closely
  1052. */
  1053. static int
  1054. show_stats(char *fpath, char *fname, struct stat *sb)
  1055. {
  1056. char *perms = get_lsperms(sb->st_mode, g_buf);
  1057. char *p, *begin = g_buf;
  1058. char tmp[] = "/tmp/nnnXXXXXX";
  1059. int fd = mkstemp(tmp);
  1060. if (fd == -1)
  1061. return -1;
  1062. /* Show file name or 'symlink' -> 'target' */
  1063. if (perms[0] == 'l') {
  1064. /* Note that MAX_CMD_LEN > PATH_MAX */
  1065. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1066. if (len != -1) {
  1067. g_buf[len] = '\0';
  1068. dprintf(fd, " File: '%s' -> ",
  1069. replace_escape(fname));
  1070. dprintf(fd, "'%s'",
  1071. replace_escape(g_buf));
  1072. }
  1073. } else
  1074. dprintf(fd, " File: '%s'", replace_escape(fname));
  1075. /* Show size, blocks, file type */
  1076. #ifdef __APPLE__
  1077. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1078. #else
  1079. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1080. #endif
  1081. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1082. /* Show containing device, inode, hardlink count */
  1083. #ifdef __APPLE__
  1084. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1085. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1086. #else
  1087. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1088. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1089. #endif
  1090. g_buf, sb->st_ino, sb->st_nlink);
  1091. /* Show major, minor number for block or char device */
  1092. if (perms[0] == 'b' || perms[0] == 'c')
  1093. dprintf(fd, " Device type: %x,%x",
  1094. major(sb->st_rdev), minor(sb->st_rdev));
  1095. /* Show permissions, owner, group */
  1096. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1097. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  1098. perms,
  1099. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  1100. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1101. /* Show last access time */
  1102. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1103. dprintf(fd, "\n\n Access: %s", g_buf);
  1104. /* Show last modification time */
  1105. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1106. dprintf(fd, "\n Modify: %s", g_buf);
  1107. /* Show last status change time */
  1108. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1109. dprintf(fd, "\n Change: %s", g_buf);
  1110. if (S_ISREG(sb->st_mode)) {
  1111. /* Show file(1) output */
  1112. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1113. if (p) {
  1114. dprintf(fd, "\n\n ");
  1115. while (*p) {
  1116. if (*p == ',') {
  1117. *p = '\0';
  1118. dprintf(fd, " %s\n", begin);
  1119. begin = p + 1;
  1120. }
  1121. ++p;
  1122. }
  1123. dprintf(fd, " %s", begin);
  1124. }
  1125. dprintf(fd, "\n\n");
  1126. } else
  1127. dprintf(fd, "\n\n\n");
  1128. close(fd);
  1129. exitcurses();
  1130. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1131. unlink(tmp);
  1132. initcurses();
  1133. return 0;
  1134. }
  1135. static int
  1136. show_mediainfo(char *fpath, char *arg)
  1137. {
  1138. if (!get_output(g_buf, MAX_CMD_LEN, "which", "mediainfo", NULL, 0))
  1139. return -1;
  1140. exitcurses();
  1141. get_output(NULL, 0, "mediainfo", fpath, arg, 1);
  1142. initcurses();
  1143. return 0;
  1144. }
  1145. static int
  1146. show_help(void)
  1147. {
  1148. char tmp[] = "/tmp/nnnXXXXXX";
  1149. static char helpstr[] = ("\
  1150. Key | Function\n\
  1151. -+-\n\
  1152. Up, k, ^P | Previous entry\n\
  1153. Down, j, ^N | Next entry\n\
  1154. PgUp, ^U | Scroll half page up\n\
  1155. PgDn, ^D | Scroll half page down\n\
  1156. Home, g, ^, ^A | Jump to first entry\n\
  1157. End, G, $, ^E | Jump to last entry\n\
  1158. Right, Enter, l, ^M | Open file or enter dir\n\
  1159. Left, Bksp, h, ^H | Go to parent dir\n\
  1160. Insert | Toggle navigate-as-you-type mode\n\
  1161. ~ | Jump to HOME dir\n\
  1162. & | Jump to initial dir\n\
  1163. - | Jump to last visited dir\n\
  1164. / | Filter dir contents\n\
  1165. ^/ | Search dir in desktop search tool\n\
  1166. . | Toggle hide .dot files\n\
  1167. b | Show bookmark key prompt\n\
  1168. c | Show change dir prompt\n\
  1169. d | Toggle detail view\n\
  1170. D | Toggle current file details screen\n\
  1171. m | Show concise mediainfo\n\
  1172. M | Show full mediainfo\n\
  1173. s | Toggle sort by file size\n\
  1174. S | Toggle disk usage analyzer mode\n\
  1175. t | Toggle sort by modified time\n\
  1176. ! | Spawn SHELL in PWD (fallback sh)\n\
  1177. e | Edit entry in EDITOR (fallback vi)\n\
  1178. o | Open dir in NNN_DE_FILE_MANAGER\n\
  1179. p | Open entry in PAGER (fallback less)\n\
  1180. ^K | Invoke file path copier\n\
  1181. ^L | Force a redraw, exit filter prompt\n\
  1182. ? | Toggle help and settings screen\n\
  1183. Q | Quit and change directory\n\
  1184. q, ^Q | Quit\n\n\n");
  1185. int i = 0, fd = mkstemp(tmp);
  1186. if (fd == -1)
  1187. return -1;
  1188. dprintf(fd, "%s", helpstr);
  1189. if (getenv("NNN_BMS")) {
  1190. dprintf(fd, "BOOKMARKS\n");
  1191. for (; i < MAX_BM; ++i)
  1192. if (bookmark[i].key)
  1193. dprintf(fd, " %s: %s\n",
  1194. bookmark[i].key, bookmark[i].loc);
  1195. else
  1196. break;
  1197. dprintf(fd, "\n");
  1198. }
  1199. if (editor)
  1200. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1201. if (desktop_manager)
  1202. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1203. if (idletimeout)
  1204. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1205. if (copier)
  1206. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1207. dprintf(fd, "\n");
  1208. close(fd);
  1209. exitcurses();
  1210. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1211. unlink(tmp);
  1212. initcurses();
  1213. return 0;
  1214. }
  1215. static int
  1216. sum_bsizes(const char *fpath, const struct stat *sb,
  1217. int typeflag, struct FTW *ftwbuf)
  1218. {
  1219. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1220. ent_blocks += sb->st_blocks;
  1221. ++num_files;
  1222. return 0;
  1223. }
  1224. static int
  1225. getorder(size_t size)
  1226. {
  1227. switch (size) {
  1228. case 4096:
  1229. return 12;
  1230. case 512:
  1231. return 9;
  1232. case 8192:
  1233. return 13;
  1234. case 16384:
  1235. return 14;
  1236. case 32768:
  1237. return 15;
  1238. case 65536:
  1239. return 16;
  1240. case 131072:
  1241. return 17;
  1242. case 262144:
  1243. return 18;
  1244. case 524288:
  1245. return 19;
  1246. case 1048576:
  1247. return 20;
  1248. case 2048:
  1249. return 11;
  1250. case 1024:
  1251. return 10;
  1252. default:
  1253. return 0;
  1254. }
  1255. }
  1256. static int
  1257. dentfill(char *path, struct entry **dents,
  1258. int (*filter)(regex_t *, char *), regex_t *re)
  1259. {
  1260. static DIR *dirp;
  1261. static struct dirent *dp;
  1262. static struct stat sb;
  1263. static int fd, n;
  1264. n = 0;
  1265. if (cfg.blkorder) {
  1266. num_files = 0;
  1267. dir_blocks = 0;
  1268. }
  1269. dirp = opendir(path);
  1270. if (dirp == NULL)
  1271. return 0;
  1272. fd = dirfd(dirp);
  1273. while ((dp = readdir(dirp)) != NULL) {
  1274. /* Skip self and parent */
  1275. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  1276. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  1277. continue;
  1278. if (filter(re, dp->d_name) == 0) {
  1279. if (!cfg.blkorder)
  1280. continue;
  1281. if (fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1282. continue;
  1283. if (S_ISDIR(sb.st_mode)) {
  1284. ent_blocks = 0;
  1285. mkpath(path, dp->d_name, g_buf, PATH_MAX);
  1286. if (nftw(g_buf, sum_bsizes, open_max,
  1287. FTW_MOUNT | FTW_PHYS) == -1) {
  1288. printmsg("nftw(3) failed");
  1289. dir_blocks += sb.st_blocks;
  1290. } else
  1291. dir_blocks += ent_blocks;
  1292. } else {
  1293. if (sb.st_blocks)
  1294. dir_blocks += sb.st_blocks;
  1295. ++num_files;
  1296. }
  1297. continue;
  1298. }
  1299. if (fstatat(fd, dp->d_name, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1300. if (*dents)
  1301. free(*dents);
  1302. printerr(1, "fstatat");
  1303. }
  1304. if (n == total_dents) {
  1305. total_dents += 64;
  1306. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1307. if (*dents == NULL)
  1308. printerr(1, "realloc");
  1309. }
  1310. xstrlcpy((*dents)[n].name, dp->d_name, NAME_MAX);
  1311. (*dents)[n].mode = sb.st_mode;
  1312. (*dents)[n].t = sb.st_mtime;
  1313. (*dents)[n].size = sb.st_size;
  1314. if (cfg.blkorder) {
  1315. if (S_ISDIR(sb.st_mode)) {
  1316. ent_blocks = 0;
  1317. mkpath(path, dp->d_name, g_buf, PATH_MAX);
  1318. if (nftw(g_buf, sum_bsizes, open_max,
  1319. FTW_MOUNT | FTW_PHYS) == -1) {
  1320. printmsg("nftw(3) failed");
  1321. (*dents)[n].blocks = sb.st_blocks;
  1322. } else
  1323. (*dents)[n].blocks = ent_blocks;
  1324. } else {
  1325. (*dents)[n].blocks = sb.st_blocks;
  1326. ++num_files;
  1327. }
  1328. if ((*dents)[n].blocks)
  1329. dir_blocks += (*dents)[n].blocks;
  1330. }
  1331. ++n;
  1332. }
  1333. if (cfg.blkorder) {
  1334. static struct statvfs svb;
  1335. if (statvfs(path, &svb) == -1)
  1336. fs_free = 0;
  1337. else
  1338. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1339. }
  1340. /* Should never be null */
  1341. if (closedir(dirp) == -1) {
  1342. if (*dents)
  1343. free(*dents);
  1344. printerr(1, "closedir");
  1345. }
  1346. return n;
  1347. }
  1348. static void
  1349. dentfree(struct entry *dents)
  1350. {
  1351. free(dents);
  1352. }
  1353. /* Return the position of the matching entry or 0 otherwise */
  1354. static int
  1355. dentfind(struct entry *dents, int n, char *path)
  1356. {
  1357. if (!path)
  1358. return 0;
  1359. static int i;
  1360. static char *p;
  1361. p = basename(path);
  1362. DPRINTF_S(p);
  1363. for (i = 0; i < n; ++i)
  1364. if (strcmp(p, dents[i].name) == 0)
  1365. return i;
  1366. return 0;
  1367. }
  1368. static int
  1369. populate(char *path, char *oldpath, char *fltr)
  1370. {
  1371. static regex_t re;
  1372. /* Can fail when permissions change while browsing */
  1373. if (canopendir(path) == 0)
  1374. return -1;
  1375. /* Search filter */
  1376. if (setfilter(&re, fltr) != 0)
  1377. return -1;
  1378. if (cfg.blkorder) {
  1379. printmsg("Calculating...");
  1380. refresh();
  1381. }
  1382. ndents = dentfill(path, &dents, visible, &re);
  1383. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1384. /* Find cur from history */
  1385. cur = dentfind(dents, ndents, oldpath);
  1386. return 0;
  1387. }
  1388. static void
  1389. redraw(char *path)
  1390. {
  1391. static int nlines, i;
  1392. static size_t ncols;
  1393. nlines = MIN(LINES - 4, ndents);
  1394. /* Clean screen */
  1395. erase();
  1396. /* Strip trailing slashes */
  1397. for (i = strlen(path) - 1; i > 0; --i)
  1398. if (path[i] == '/')
  1399. path[i] = '\0';
  1400. else
  1401. break;
  1402. DPRINTF_D(cur);
  1403. DPRINTF_S(path);
  1404. /* No text wrapping in cwd line */
  1405. if (!realpath(path, g_buf)) {
  1406. printmsg("Cannot resolve path");
  1407. return;
  1408. }
  1409. ncols = COLS;
  1410. if (ncols > PATH_MAX)
  1411. ncols = PATH_MAX;
  1412. g_buf[ncols - strlen(CWD) - 1] = '\0';
  1413. printw(CWD "%s\n\n", g_buf);
  1414. /* Print listing */
  1415. if (cur < (nlines >> 1)) {
  1416. for (i = 0; i < nlines; ++i)
  1417. printptr(&dents[i], i == cur);
  1418. } else if (cur >= ndents - (nlines >> 1)) {
  1419. for (i = ndents - nlines; i < ndents; ++i)
  1420. printptr(&dents[i], i == cur);
  1421. } else {
  1422. static int odd;
  1423. odd = ISODD(nlines);
  1424. nlines >>= 1;
  1425. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1426. printptr(&dents[i], i == cur);
  1427. }
  1428. if (cfg.showdetail) {
  1429. if (ndents) {
  1430. static char ind[2] = "\0\0";
  1431. static char sort[17];
  1432. if (cfg.mtimeorder)
  1433. sprintf(sort, "by time ");
  1434. else if (cfg.sizeorder)
  1435. sprintf(sort, "by size ");
  1436. else
  1437. sort[0] = '\0';
  1438. if (S_ISDIR(dents[cur].mode))
  1439. ind[0] = '/';
  1440. else if (S_ISLNK(dents[cur].mode))
  1441. ind[0] = '@';
  1442. else if (S_ISSOCK(dents[cur].mode))
  1443. ind[0] = '=';
  1444. else if (S_ISFIFO(dents[cur].mode))
  1445. ind[0] = '|';
  1446. else if (dents[cur].mode & 0100)
  1447. ind[0] = '*';
  1448. else
  1449. ind[0] = '\0';
  1450. if (!cfg.blkorder)
  1451. sprintf(g_buf, "total %d %s[%s%s]", ndents, sort,
  1452. replace_escape(dents[cur].name), ind);
  1453. else {
  1454. i = sprintf(g_buf, "du: %s (%lu files) ",
  1455. coolsize(dir_blocks << 9), num_files);
  1456. sprintf(g_buf + i, "vol: %s free [%s%s]", coolsize(fs_free),
  1457. replace_escape(dents[cur].name), ind);
  1458. }
  1459. printmsg(g_buf);
  1460. } else
  1461. printmsg("0 items");
  1462. }
  1463. }
  1464. static void
  1465. browse(char *ipath, char *ifilter)
  1466. {
  1467. char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1468. char lastdir[PATH_MAX];
  1469. char fltr[LINE_MAX];
  1470. char *mime, *dir, *tmp, *run, *env;
  1471. struct stat sb;
  1472. int r, fd, presel;
  1473. enum action sel = SEL_RUNARG + 1;
  1474. xstrlcpy(path, ipath, PATH_MAX);
  1475. xstrlcpy(fltr, ifilter, LINE_MAX);
  1476. oldpath[0] = '\0';
  1477. newpath[0] = '\0';
  1478. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1479. if (cfg.filtermode)
  1480. presel = FILTER;
  1481. else
  1482. presel = 0;
  1483. begin:
  1484. if (populate(path, oldpath, fltr) == -1) {
  1485. printwarn();
  1486. goto nochange;
  1487. }
  1488. for (;;) {
  1489. redraw(path);
  1490. nochange:
  1491. /* Exit if parent has exited */
  1492. if (getppid() == 1)
  1493. _exit(0);
  1494. sel = nextsel(&run, &env, &presel);
  1495. switch (sel) {
  1496. case SEL_CDQUIT:
  1497. {
  1498. char *tmpfile = "/tmp/nnn";
  1499. tmp = getenv("NNN_TMPFILE");
  1500. if (tmp)
  1501. tmpfile = tmp;
  1502. FILE *fp = fopen(tmpfile, "w");
  1503. if (fp) {
  1504. fprintf(fp, "cd \"%s\"", path);
  1505. fclose(fp);
  1506. }
  1507. /* Fall through to exit */
  1508. } // fallthrough
  1509. case SEL_QUIT:
  1510. dentfree(dents);
  1511. return;
  1512. case SEL_BACK:
  1513. /* There is no going back */
  1514. if (path[0] == '/' && path[1] == '\0') {
  1515. printmsg("You are at /");
  1516. goto nochange;
  1517. }
  1518. dir = xdirname(path);
  1519. if (canopendir(dir) == 0) {
  1520. printwarn();
  1521. goto nochange;
  1522. }
  1523. /* Save history */
  1524. xstrlcpy(oldpath, path, PATH_MAX);
  1525. /* Save last working directory */
  1526. xstrlcpy(lastdir, path, PATH_MAX);
  1527. xstrlcpy(path, dir, PATH_MAX);
  1528. /* Reset filter */
  1529. xstrlcpy(fltr, ifilter, LINE_MAX);
  1530. if (cfg.filtermode)
  1531. presel = FILTER;
  1532. goto begin;
  1533. case SEL_GOIN:
  1534. /* Cannot descend in empty directories */
  1535. if (ndents == 0)
  1536. goto begin;
  1537. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1538. DPRINTF_S(newpath);
  1539. /* Get path info */
  1540. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1541. if (fd == -1) {
  1542. printwarn();
  1543. goto nochange;
  1544. }
  1545. r = fstat(fd, &sb);
  1546. if (r == -1) {
  1547. printwarn();
  1548. close(fd);
  1549. goto nochange;
  1550. }
  1551. close(fd);
  1552. DPRINTF_U(sb.st_mode);
  1553. switch (sb.st_mode & S_IFMT) {
  1554. case S_IFDIR:
  1555. if (canopendir(newpath) == 0) {
  1556. printwarn();
  1557. goto nochange;
  1558. }
  1559. /* Save last working directory */
  1560. xstrlcpy(lastdir, path, PATH_MAX);
  1561. xstrlcpy(path, newpath, PATH_MAX);
  1562. oldpath[0] = '\0';
  1563. /* Reset filter */
  1564. xstrlcpy(fltr, ifilter, LINE_MAX);
  1565. if (cfg.filtermode)
  1566. presel = FILTER;
  1567. goto begin;
  1568. case S_IFREG:
  1569. {
  1570. /* If NNN_USE_EDITOR is set,
  1571. * open text in EDITOR
  1572. */
  1573. if (editor) {
  1574. mime = getmime(dents[cur].name);
  1575. if (mime) {
  1576. spawn(editor, newpath, NULL,
  1577. NULL, SP_NORMAL);
  1578. continue;
  1579. }
  1580. /* Recognize and open plain
  1581. * text files with vi
  1582. */
  1583. if (get_output(g_buf, MAX_CMD_LEN,
  1584. "file", "-bi",
  1585. newpath, 0) == NULL)
  1586. continue;
  1587. if (strstr(g_buf, "text/") == g_buf) {
  1588. spawn(editor, newpath, NULL,
  1589. NULL, SP_NORMAL);
  1590. continue;
  1591. }
  1592. }
  1593. /* Invoke desktop opener as last resort */
  1594. spawn(utils[0], newpath, NULL, NULL, SP_NOTRACE);
  1595. continue;
  1596. }
  1597. default:
  1598. printmsg("Unsupported file");
  1599. goto nochange;
  1600. }
  1601. case SEL_FLTR:
  1602. presel = readln(path);
  1603. xstrlcpy(fltr, ifilter, LINE_MAX);
  1604. DPRINTF_S(fltr);
  1605. /* Save current */
  1606. if (ndents > 0)
  1607. mkpath(path, dents[cur].name, oldpath,
  1608. PATH_MAX);
  1609. goto nochange;
  1610. case SEL_MFLTR:
  1611. cfg.filtermode ^= 1;
  1612. if (cfg.filtermode)
  1613. presel = FILTER;
  1614. else
  1615. printmsg("navigate-as-you-type off");
  1616. goto nochange;
  1617. case SEL_SEARCH:
  1618. spawn(player, path, "search", NULL, SP_NORMAL);
  1619. break;
  1620. case SEL_NEXT:
  1621. if (cur < ndents - 1)
  1622. ++cur;
  1623. else if (ndents)
  1624. /* Roll over, set cursor to first entry */
  1625. cur = 0;
  1626. break;
  1627. case SEL_PREV:
  1628. if (cur > 0)
  1629. --cur;
  1630. else if (ndents)
  1631. /* Roll over, set cursor to last entry */
  1632. cur = ndents - 1;
  1633. break;
  1634. case SEL_PGDN:
  1635. if (cur < ndents - 1)
  1636. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1637. break;
  1638. case SEL_PGUP:
  1639. if (cur > 0)
  1640. cur -= MIN((LINES - 4) / 2, cur);
  1641. break;
  1642. case SEL_HOME:
  1643. cur = 0;
  1644. break;
  1645. case SEL_END:
  1646. cur = ndents - 1;
  1647. break;
  1648. case SEL_CD:
  1649. {
  1650. static char *input;
  1651. static int truecd;
  1652. /* Save the program start dir */
  1653. tmp = getcwd(newpath, PATH_MAX);
  1654. if (tmp == NULL) {
  1655. printwarn();
  1656. goto nochange;
  1657. }
  1658. /* Switch to current path for readline(3) */
  1659. if (chdir(path) == -1) {
  1660. printwarn();
  1661. goto nochange;
  1662. }
  1663. exitcurses();
  1664. tmp = readline("chdir: ");
  1665. initcurses();
  1666. /* Change back to program start dir */
  1667. if (chdir(newpath) == -1)
  1668. printwarn();
  1669. if (tmp[0] == '\0')
  1670. break;
  1671. /* Add to readline(3) history */
  1672. add_history(tmp);
  1673. input = tmp;
  1674. tmp = strstrip(tmp);
  1675. if (tmp[0] == '\0') {
  1676. free(input);
  1677. break;
  1678. }
  1679. truecd = 0;
  1680. if (tmp[0] == '~') {
  1681. /* Expand ~ to HOME absolute path */
  1682. char *home = getenv("HOME");
  1683. if (home)
  1684. snprintf(newpath, PATH_MAX, "%s%s",
  1685. home, tmp + 1);
  1686. else {
  1687. free(input);
  1688. printmsg("HOME not set");
  1689. goto nochange;
  1690. }
  1691. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1692. if (lastdir[0] == '\0') {
  1693. free(input);
  1694. break;
  1695. }
  1696. /* Switch to last visited dir */
  1697. xstrlcpy(newpath, lastdir, PATH_MAX);
  1698. truecd = 1;
  1699. } else if ((r = all_dots(tmp))) {
  1700. if (r == 1) {
  1701. /* Always in the current dir */
  1702. free(input);
  1703. break;
  1704. }
  1705. --r;
  1706. dir = path;
  1707. for (fd = 0; fd < r; ++fd) {
  1708. /* Reached / ? */
  1709. if (path[0] == '/' && path[1] == '\0') {
  1710. /* If it's a cd .. at / */
  1711. if (fd == 0) {
  1712. printmsg("You are at /");
  1713. free(input);
  1714. goto nochange;
  1715. }
  1716. /* Can't cd beyond / anyway */
  1717. break;
  1718. }
  1719. dir = xdirname(dir);
  1720. if (canopendir(dir) == 0) {
  1721. printwarn();
  1722. free(input);
  1723. goto nochange;
  1724. }
  1725. }
  1726. truecd = 1;
  1727. /* Save the path in case of cd ..
  1728. * We mark the current dir in parent dir
  1729. */
  1730. if (r == 1) {
  1731. xstrlcpy(oldpath, path, PATH_MAX);
  1732. truecd = 2;
  1733. }
  1734. xstrlcpy(newpath, dir, PATH_MAX);
  1735. } else
  1736. mkpath(path, tmp, newpath, PATH_MAX);
  1737. free(input);
  1738. if (canopendir(newpath) == 0) {
  1739. printwarn();
  1740. break;
  1741. }
  1742. if (truecd == 0) {
  1743. /* Probable change in dir */
  1744. /* No-op if it's the same directory */
  1745. if (strcmp(path, newpath) == 0)
  1746. break;
  1747. oldpath[0] = '\0';
  1748. } else if (truecd == 1)
  1749. /* Sure change in dir */
  1750. oldpath[0] = '\0';
  1751. /* Save last working directory */
  1752. xstrlcpy(lastdir, path, PATH_MAX);
  1753. /* Save the newly opted dir in path */
  1754. xstrlcpy(path, newpath, PATH_MAX);
  1755. /* Reset filter */
  1756. xstrlcpy(fltr, ifilter, LINE_MAX);
  1757. DPRINTF_S(path);
  1758. if (cfg.filtermode)
  1759. presel = FILTER;
  1760. goto begin;
  1761. }
  1762. case SEL_CDHOME:
  1763. tmp = getenv("HOME");
  1764. if (tmp == NULL) {
  1765. clearprompt();
  1766. goto nochange;
  1767. }
  1768. if (canopendir(tmp) == 0) {
  1769. printwarn();
  1770. goto nochange;
  1771. }
  1772. if (strcmp(path, tmp) == 0)
  1773. break;
  1774. /* Save last working directory */
  1775. xstrlcpy(lastdir, path, PATH_MAX);
  1776. xstrlcpy(path, tmp, PATH_MAX);
  1777. oldpath[0] = '\0';
  1778. /* Reset filter */
  1779. xstrlcpy(fltr, ifilter, LINE_MAX);
  1780. DPRINTF_S(path);
  1781. if (cfg.filtermode)
  1782. presel = FILTER;
  1783. goto begin;
  1784. case SEL_CDBEGIN:
  1785. if (canopendir(ipath) == 0) {
  1786. printwarn();
  1787. goto nochange;
  1788. }
  1789. if (strcmp(path, ipath) == 0)
  1790. break;
  1791. /* Save last working directory */
  1792. xstrlcpy(lastdir, path, PATH_MAX);
  1793. xstrlcpy(path, ipath, PATH_MAX);
  1794. oldpath[0] = '\0';
  1795. /* Reset filter */
  1796. xstrlcpy(fltr, ifilter, LINE_MAX);
  1797. DPRINTF_S(path);
  1798. if (cfg.filtermode)
  1799. presel = FILTER;
  1800. goto begin;
  1801. case SEL_CDLAST:
  1802. if (lastdir[0] == '\0')
  1803. break;
  1804. if (canopendir(lastdir) == 0) {
  1805. printwarn();
  1806. goto nochange;
  1807. }
  1808. xstrlcpy(newpath, lastdir, PATH_MAX);
  1809. xstrlcpy(lastdir, path, PATH_MAX);
  1810. xstrlcpy(path, newpath, PATH_MAX);
  1811. oldpath[0] = '\0';
  1812. /* Reset filter */
  1813. xstrlcpy(fltr, ifilter, LINE_MAX);
  1814. DPRINTF_S(path);
  1815. if (cfg.filtermode)
  1816. presel = FILTER;
  1817. goto begin;
  1818. case SEL_CDBM:
  1819. printprompt("key: ");
  1820. tmp = readinput();
  1821. if (tmp == NULL) {
  1822. clearprompt();
  1823. goto nochange;
  1824. }
  1825. clearprompt();
  1826. for (r = 0; bookmark[r].key && r < MAX_BM; ++r) {
  1827. if (strcmp(bookmark[r].key, tmp) == 0) {
  1828. if (bookmark[r].loc[0] == '~') {
  1829. /* Expand ~ to HOME */
  1830. char *home = getenv("HOME");
  1831. if (home)
  1832. snprintf(newpath,
  1833. PATH_MAX,
  1834. "%s%s",
  1835. home,
  1836. bookmark[r].loc
  1837. + 1);
  1838. else {
  1839. printmsg("HOME not set");
  1840. goto nochange;
  1841. }
  1842. } else
  1843. mkpath(path, bookmark[r].loc,
  1844. newpath, PATH_MAX);
  1845. if (canopendir(newpath) == 0) {
  1846. printwarn();
  1847. goto nochange;
  1848. }
  1849. if (strcmp(path, newpath) == 0)
  1850. break;
  1851. oldpath[0] = '\0';
  1852. break;
  1853. }
  1854. }
  1855. if (!bookmark[r].key) {
  1856. printmsg("No matching bookmark");
  1857. goto nochange;
  1858. }
  1859. /* Save last working directory */
  1860. xstrlcpy(lastdir, path, PATH_MAX);
  1861. /* Save the newly opted dir in path */
  1862. xstrlcpy(path, newpath, PATH_MAX);
  1863. /* Reset filter */
  1864. xstrlcpy(fltr, ifilter, LINE_MAX);
  1865. DPRINTF_S(path);
  1866. if (cfg.filtermode)
  1867. presel = FILTER;
  1868. goto begin;
  1869. case SEL_TOGGLEDOT:
  1870. cfg.showhidden ^= 1;
  1871. initfilter(cfg.showhidden, &ifilter);
  1872. xstrlcpy(fltr, ifilter, LINE_MAX);
  1873. goto begin;
  1874. case SEL_DETAIL:
  1875. cfg.showdetail ^= 1;
  1876. cfg.showdetail ? (printptr = &printent_long)
  1877. : (printptr = &printent);
  1878. /* Save current */
  1879. if (ndents > 0)
  1880. mkpath(path, dents[cur].name, oldpath,
  1881. PATH_MAX);
  1882. goto begin;
  1883. case SEL_STATS:
  1884. {
  1885. struct stat sb;
  1886. if (ndents > 0) {
  1887. mkpath(path, dents[cur].name, oldpath,
  1888. PATH_MAX);
  1889. r = lstat(oldpath, &sb);
  1890. if (r == -1) {
  1891. if (dents)
  1892. dentfree(dents);
  1893. printerr(1, "lstat");
  1894. } else {
  1895. r = show_stats(oldpath, dents[cur].name,
  1896. &sb);
  1897. if (r < 0) {
  1898. printmsg(strerror(errno));
  1899. goto nochange;
  1900. }
  1901. }
  1902. }
  1903. break;
  1904. }
  1905. case SEL_MEDIA:
  1906. if (ndents > 0) {
  1907. mkpath(path, dents[cur].name, oldpath,
  1908. PATH_MAX);
  1909. if (show_mediainfo(oldpath, NULL) == -1) {
  1910. printmsg("mediainfo missing");
  1911. goto nochange;
  1912. }
  1913. }
  1914. break;
  1915. case SEL_FMEDIA:
  1916. if (ndents > 0) {
  1917. mkpath(path, dents[cur].name, oldpath,
  1918. PATH_MAX);
  1919. if (show_mediainfo(oldpath, "-f") == -1) {
  1920. printmsg("mediainfo missing");
  1921. goto nochange;
  1922. }
  1923. }
  1924. break;
  1925. case SEL_DFB:
  1926. if (!desktop_manager) {
  1927. printmsg("NNN_DE_FILE_MANAGER not set");
  1928. goto nochange;
  1929. }
  1930. spawn(desktop_manager, path, NULL, path, SP_NOTRACE | SP_NOWAIT);
  1931. break;
  1932. case SEL_FSIZE:
  1933. cfg.sizeorder ^= 1;
  1934. cfg.mtimeorder = 0;
  1935. cfg.blkorder = 0;
  1936. /* Save current */
  1937. if (ndents > 0)
  1938. mkpath(path, dents[cur].name, oldpath,
  1939. PATH_MAX);
  1940. goto begin;
  1941. case SEL_BSIZE:
  1942. cfg.blkorder ^= 1;
  1943. if (cfg.blkorder) {
  1944. cfg.showdetail = 1;
  1945. printptr = &printent_long;
  1946. }
  1947. cfg.mtimeorder = 0;
  1948. cfg.sizeorder = 0;
  1949. /* Save current */
  1950. if (ndents > 0)
  1951. mkpath(path, dents[cur].name, oldpath,
  1952. PATH_MAX);
  1953. goto begin;
  1954. case SEL_MTIME:
  1955. cfg.mtimeorder ^= 1;
  1956. cfg.sizeorder = 0;
  1957. cfg.blkorder = 0;
  1958. /* Save current */
  1959. if (ndents > 0)
  1960. mkpath(path, dents[cur].name, oldpath,
  1961. PATH_MAX);
  1962. goto begin;
  1963. case SEL_REDRAW:
  1964. /* Save current */
  1965. if (ndents > 0)
  1966. mkpath(path, dents[cur].name, oldpath,
  1967. PATH_MAX);
  1968. goto begin;
  1969. case SEL_COPY:
  1970. if (copier && ndents) {
  1971. if (strcmp(path, "/") == 0)
  1972. snprintf(newpath, PATH_MAX, "/%s",
  1973. dents[cur].name);
  1974. else
  1975. snprintf(newpath, PATH_MAX, "%s/%s",
  1976. path, dents[cur].name);
  1977. spawn(copier, newpath, NULL, NULL, SP_NONE);
  1978. printmsg(newpath);
  1979. } else if (!copier)
  1980. printmsg("NNN_COPIER is not set");
  1981. goto nochange;
  1982. case SEL_HELP:
  1983. show_help();
  1984. break;
  1985. case SEL_RUN:
  1986. run = xgetenv(env, run);
  1987. spawn(run, NULL, NULL, path, SP_NORMAL | SP_MARKER);
  1988. /* Repopulate as directory content may have changed */
  1989. goto begin;
  1990. case SEL_RUNARG:
  1991. run = xgetenv(env, run);
  1992. spawn(run, dents[cur].name, NULL, path, SP_NORMAL);
  1993. break;
  1994. }
  1995. /* Screensaver */
  1996. if (idletimeout != 0 && idle == idletimeout) {
  1997. idle = 0;
  1998. spawn(player, "", "screensaver", NULL, SP_NORMAL | SP_SIGINT);
  1999. }
  2000. }
  2001. }
  2002. static void
  2003. usage(void)
  2004. {
  2005. printf("usage: nnn [-l] [-i] [-p custom_nlay] [-S] [-v] [-h] [PATH]\n\n\
  2006. The missing terminal file browser for X.\n\n\
  2007. positional arguments:\n\
  2008. PATH directory to open [default: current dir]\n\n\
  2009. optional arguments:\n\
  2010. -l start in light mode (fewer details)\n\
  2011. -i start in navigate-as-you-type mode\n\
  2012. -p path to custom nlay\n\
  2013. -S start in disk usage analyzer mode\n\
  2014. -v show program version and exit\n\
  2015. -h show this help and exit\n\n\
  2016. Version: %s\n\
  2017. License: BSD 2-Clause\n\
  2018. Webpage: https://github.com/jarun/nnn\n", VERSION);
  2019. exit(0);
  2020. }
  2021. int
  2022. main(int argc, char *argv[])
  2023. {
  2024. char cwd[PATH_MAX], *ipath;
  2025. char *ifilter, *bmstr;
  2026. int opt;
  2027. /* Confirm we are in a terminal */
  2028. if (!isatty(0) || !isatty(1)) {
  2029. fprintf(stderr, "stdin or stdout is not a tty\n");
  2030. exit(1);
  2031. }
  2032. while ((opt = getopt(argc, argv, "dlSip:vh")) != -1) {
  2033. switch (opt) {
  2034. case 'S':
  2035. cfg.blkorder = 1;
  2036. break;
  2037. case 'l':
  2038. cfg.showdetail = 0;
  2039. printptr = &printent;
  2040. break;
  2041. case 'i':
  2042. cfg.filtermode = 1;
  2043. break;
  2044. case 'p':
  2045. player = optarg;
  2046. break;
  2047. case 'v':
  2048. printf("%s\n", VERSION);
  2049. return 0;
  2050. case 'd':
  2051. fprintf(stderr, "Option -d is deprecated and will be removed, detail view mode is default now.\n");
  2052. break;
  2053. case 'h': // fallthrough
  2054. default:
  2055. usage();
  2056. }
  2057. }
  2058. if (argc == optind) {
  2059. /* Start in the current directory */
  2060. ipath = getcwd(cwd, PATH_MAX);
  2061. if (ipath == NULL)
  2062. ipath = "/";
  2063. } else {
  2064. ipath = realpath(argv[optind], cwd);
  2065. if (!ipath) {
  2066. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2067. exit(1);
  2068. }
  2069. }
  2070. open_max = max_openfds();
  2071. if (getuid() == 0)
  2072. cfg.showhidden = 1;
  2073. initfilter(cfg.showhidden, &ifilter);
  2074. /* Parse bookmarks string, if available */
  2075. bmstr = getenv("NNN_BMS");
  2076. if (bmstr)
  2077. parsebmstr(bmstr);
  2078. /* Edit text in EDITOR, if opted */
  2079. if (getenv("NNN_USE_EDITOR"))
  2080. editor = xgetenv("EDITOR", "vi");
  2081. /* Set player if not set already */
  2082. if (!player)
  2083. player = utils[1];
  2084. /* Get the desktop file browser, if set */
  2085. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2086. /* Get screensaver wait time, if set; copier used as tmp var */
  2087. copier = getenv("NNN_IDLE_TIMEOUT");
  2088. if (copier)
  2089. idletimeout = abs(atoi(copier));
  2090. /* Get the default copier, if set */
  2091. copier = getenv("NNN_COPIER");
  2092. signal(SIGINT, SIG_IGN);
  2093. /* Test initial path */
  2094. if (canopendir(ipath) == 0) {
  2095. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2096. exit(1);
  2097. }
  2098. #ifdef DEBUGMODE
  2099. enabledbg();
  2100. #endif
  2101. /* Set locale */
  2102. setlocale(LC_ALL, "");
  2103. initcurses();
  2104. browse(ipath, ifilter);
  2105. exitcurses();
  2106. #ifdef DEBUGMODE
  2107. disabledbg();
  2108. #endif
  2109. exit(0);
  2110. }