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.
 
 
 
 
 
 

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