My build of nnn with minor changes
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

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