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

2489 строки
51 KiB

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