My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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