My build of nnn with minor changes
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

2202 linhas
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. cur = oldcur; // fallthrough
  651. case CONTROL('Q'):
  652. goto end;
  653. default:
  654. wln[len++] = (wchar_t)*ch;
  655. wln[len] = '\0';
  656. wcstombs(ln, wln, LINE_MAX << 2);
  657. ndents = total;
  658. if (matches(pln) == -1)
  659. continue;
  660. redraw(path);
  661. printprompt(ln);
  662. }
  663. } else {
  664. switch(*ch) {
  665. case KEY_DC: // fallthrough
  666. case KEY_BACKSPACE:
  667. if (len == 1) {
  668. cur = oldcur;
  669. *ch = CONTROL('L');
  670. goto end;
  671. }
  672. if (len == 2)
  673. cur = oldcur;
  674. wln[--len] = '\0';
  675. wcstombs(ln, wln, LINE_MAX << 2);
  676. ndents = total;
  677. if (matches(pln) == -1)
  678. continue;
  679. redraw(path);
  680. printprompt(ln);
  681. break;
  682. case KEY_DOWN: // fallthrough
  683. case KEY_UP: // fallthrough
  684. case KEY_LEFT: // fallthrough
  685. case KEY_RIGHT:
  686. if (len == 1)
  687. cur = oldcur; // fallthrough
  688. default:
  689. goto end;
  690. }
  691. }
  692. }
  693. end:
  694. noecho();
  695. curs_set(FALSE);
  696. timeout(1000);
  697. /* Return keys for navigation etc. */
  698. return *ch;
  699. }
  700. static int
  701. canopendir(char *path)
  702. {
  703. static DIR *dirp;
  704. dirp = opendir(path);
  705. if (dirp == NULL)
  706. return 0;
  707. closedir(dirp);
  708. return 1;
  709. }
  710. /*
  711. * Returns "dir/name or "/name"
  712. */
  713. static char *
  714. mkpath(char *dir, char *name, char *out, size_t n)
  715. {
  716. /* Handle absolute path */
  717. if (name[0] == '/')
  718. xstrlcpy(out, name, n);
  719. else {
  720. /* Handle root case */
  721. if (strcmp(dir, "/") == 0)
  722. snprintf(out, n, "/%s", name);
  723. else
  724. snprintf(out, n, "%s/%s", dir, name);
  725. }
  726. return out;
  727. }
  728. static char *
  729. replace_escape(const char *str)
  730. {
  731. static char buffer[PATH_MAX];
  732. static wchar_t wbuf[PATH_MAX];
  733. static wchar_t *buf;
  734. buffer[0] = '\0';
  735. buf = wbuf;
  736. /* Convert multi-byte to wide char */
  737. mbstowcs(wbuf, str, PATH_MAX);
  738. while (*buf) {
  739. if (*buf <= '\x1f' || *buf == '\x7f')
  740. *buf = '\?';
  741. buf++;
  742. }
  743. /* Convert wide char to multi-byte */
  744. wcstombs(buffer, wbuf, PATH_MAX);
  745. return buffer;
  746. }
  747. static void
  748. printent(struct entry *ent, int active)
  749. {
  750. static int ncols;
  751. if (COLS > PATH_MAX + 16)
  752. ncols = PATH_MAX + 16;
  753. else
  754. ncols = COLS;
  755. if (S_ISDIR(ent->mode))
  756. snprintf(g_buf, ncols, "%s%s/", CURSYM(active),
  757. replace_escape(ent->name));
  758. else if (S_ISLNK(ent->mode))
  759. snprintf(g_buf, ncols, "%s%s@", CURSYM(active),
  760. replace_escape(ent->name));
  761. else if (S_ISSOCK(ent->mode))
  762. snprintf(g_buf, ncols, "%s%s=", CURSYM(active),
  763. replace_escape(ent->name));
  764. else if (S_ISFIFO(ent->mode))
  765. snprintf(g_buf, ncols, "%s%s|", CURSYM(active),
  766. replace_escape(ent->name));
  767. else if (ent->mode & S_IXUSR)
  768. snprintf(g_buf, ncols, "%s%s*", CURSYM(active),
  769. replace_escape(ent->name));
  770. else
  771. snprintf(g_buf, ncols, "%s%s", CURSYM(active),
  772. replace_escape(ent->name));
  773. printw("%s\n", g_buf);
  774. }
  775. static void (*printptr)(struct entry *ent, int active) = &printent;
  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 char
  873. get_fileind(mode_t mode, char *desc)
  874. {
  875. static char c;
  876. if (S_ISREG(mode)) {
  877. c = '-';
  878. sprintf(desc, "%s", "regular file");
  879. if (mode & S_IXUSR)
  880. strcat(desc, ", executable");
  881. } else if (S_ISDIR(mode)) {
  882. c = 'd';
  883. sprintf(desc, "%s", "directory");
  884. } else if (S_ISBLK(mode)) {
  885. c = 'b';
  886. sprintf(desc, "%s", "block special device");
  887. } else if (S_ISCHR(mode)) {
  888. c = 'c';
  889. sprintf(desc, "%s", "character special device");
  890. #ifdef S_ISFIFO
  891. } else if (S_ISFIFO(mode)) {
  892. c = 'p';
  893. sprintf(desc, "%s", "FIFO");
  894. #endif /* S_ISFIFO */
  895. #ifdef S_ISLNK
  896. } else if (S_ISLNK(mode)) {
  897. c = 'l';
  898. sprintf(desc, "%s", "symbolic link");
  899. #endif /* S_ISLNK */
  900. #ifdef S_ISSOCK
  901. } else if (S_ISSOCK(mode)) {
  902. c = 's';
  903. sprintf(desc, "%s", "socket");
  904. #endif /* S_ISSOCK */
  905. #ifdef S_ISDOOR
  906. /* Solaris 2.6, etc. */
  907. } else if (S_ISDOOR(mode)) {
  908. c = 'D';
  909. desc[0] = '\0';
  910. #endif /* S_ISDOOR */
  911. } else {
  912. /* Unknown type -- possibly a regular file? */
  913. c = '?';
  914. desc[0] = '\0';
  915. }
  916. return(c);
  917. }
  918. /* Convert a mode field into "ls -l" type perms field. */
  919. static char *
  920. get_lsperms(mode_t mode, char *desc)
  921. {
  922. static const char *rwx[] = {"---", "--x", "-w-", "-wx",
  923. "r--", "r-x", "rw-", "rwx"};
  924. static char bits[11];
  925. bits[0] = get_fileind(mode, desc);
  926. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  927. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  928. strcpy(&bits[7], rwx[(mode & 7)]);
  929. if (mode & S_ISUID)
  930. bits[3] = (mode & S_IXUSR) ? 's' : 'S';
  931. if (mode & S_ISGID)
  932. bits[6] = (mode & S_IXGRP) ? 's' : 'l';
  933. if (mode & S_ISVTX)
  934. bits[9] = (mode & S_IXOTH) ? 't' : 'T';
  935. bits[10] = '\0';
  936. return(bits);
  937. }
  938. /*
  939. * Gets only a single line (that's what we need
  940. * for now) or shows full command output in pager.
  941. *
  942. * If pager is valid, returns NULL
  943. */
  944. static char *
  945. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  946. {
  947. pid_t pid;
  948. int pipefd[2];
  949. FILE* pf;
  950. int status;
  951. char *ret = NULL;
  952. if (pipe(pipefd) == -1)
  953. printerr(1, "pipe(2)");
  954. pid = fork();
  955. if (pid == 0) {
  956. /* In child */
  957. close(pipefd[0]);
  958. dup2(pipefd[1], STDOUT_FILENO);
  959. dup2(pipefd[1], STDERR_FILENO);
  960. execlp(file, file, arg1, arg2, NULL);
  961. _exit(1);
  962. }
  963. /* In parent */
  964. waitpid(pid, &status, 0);
  965. close(pipefd[1]);
  966. if (!pager) {
  967. if ((pf = fdopen(pipefd[0], "r"))) {
  968. ret = fgets(buf, bytes, pf);
  969. close(pipefd[0]);
  970. }
  971. return ret;
  972. }
  973. pid = fork();
  974. if (pid == 0) {
  975. /* Show in pager in child */
  976. dup2(pipefd[0], STDIN_FILENO);
  977. execlp("less", "less", NULL);
  978. close(pipefd[0]);
  979. _exit(1);
  980. }
  981. /* In parent */
  982. waitpid(pid, &status, 0);
  983. return NULL;
  984. }
  985. /*
  986. * Follows the stat(1) output closely
  987. */
  988. static int
  989. show_stats(char* fpath, char* fname, struct stat *sb)
  990. {
  991. char *perms = get_lsperms(sb->st_mode, g_buf);
  992. char *p, *begin = g_buf;
  993. char tmp[] = "/tmp/nnnXXXXXX";
  994. int fd = mkstemp(tmp);
  995. if (fd == -1)
  996. return -1;
  997. /* Show file name or 'symlink' -> 'target' */
  998. if (perms[0] == 'l') {
  999. /* Note that MAX_CMD_LEN > PATH_MAX */
  1000. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1001. if (len != -1) {
  1002. g_buf[len] = '\0';
  1003. dprintf(fd, " File: '%s' -> ",
  1004. replace_escape(fname));
  1005. dprintf(fd, "'%s'",
  1006. replace_escape(g_buf));
  1007. }
  1008. } else
  1009. dprintf(fd, " File: '%s'", replace_escape(fname));
  1010. /* Show size, blocks, file type */
  1011. #ifdef __APPLE__
  1012. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1013. #else
  1014. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1015. #endif
  1016. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1017. /* Show containing device, inode, hardlink count */
  1018. #ifdef __APPLE__
  1019. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1020. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1021. #else
  1022. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1023. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1024. #endif
  1025. g_buf, sb->st_ino, sb->st_nlink);
  1026. /* Show major, minor number for block or char device */
  1027. if (perms[0] == 'b' || perms[0] == 'c')
  1028. dprintf(fd, " Device type: %x,%x",
  1029. major(sb->st_rdev), minor(sb->st_rdev));
  1030. /* Show permissions, owner, group */
  1031. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1032. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  1033. perms,
  1034. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  1035. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1036. /* Show last access time */
  1037. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1038. dprintf(fd, "\n\n Access: %s", g_buf);
  1039. /* Show last modification time */
  1040. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1041. dprintf(fd, "\n Modify: %s", g_buf);
  1042. /* Show last status change time */
  1043. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1044. dprintf(fd, "\n Change: %s", g_buf);
  1045. if (S_ISREG(sb->st_mode)) {
  1046. /* Show file(1) output */
  1047. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1048. if (p) {
  1049. dprintf(fd, "\n\n ");
  1050. while (*p) {
  1051. if (*p == ',') {
  1052. *p = '\0';
  1053. dprintf(fd, " %s\n", begin);
  1054. begin = p + 1;
  1055. }
  1056. p++;
  1057. }
  1058. dprintf(fd, " %s", begin);
  1059. }
  1060. dprintf(fd, "\n\n");
  1061. } else
  1062. dprintf(fd, "\n\n\n");
  1063. close(fd);
  1064. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1065. unlink(tmp);
  1066. return 0;
  1067. }
  1068. static int
  1069. show_mediainfo(char* fpath, char *arg)
  1070. {
  1071. if (get_output(g_buf, MAX_CMD_LEN, "which", "mediainfo", NULL, 0) == NULL)
  1072. return -1;
  1073. exitcurses();
  1074. get_output(NULL, 0, "mediainfo", fpath, arg, 1);
  1075. initcurses();
  1076. return 0;
  1077. }
  1078. static int
  1079. show_help(void)
  1080. {
  1081. static char helpstr[] = ("echo \"\
  1082. Key | Function\n\
  1083. -+-\n\
  1084. Up, k, ^P | Previous entry\n\
  1085. Down, j, ^N | Next entry\n\
  1086. PgUp, ^U | Scroll half page up\n\
  1087. PgDn, ^D | Scroll half page down\n\
  1088. Home, g, ^, ^A | Jump to first entry\n\
  1089. End, G, $, ^E | Jump to last entry\n\
  1090. Right, Enter, l, ^M | Open file or enter dir\n\
  1091. Left, Bksp, h, ^H | Go to parent dir\n\
  1092. Insert | Toggle navigate-as-you-type mode\n\
  1093. ~ | Jump to HOME dir\n\
  1094. & | Jump to initial dir\n\
  1095. - | Jump to last visited dir\n\
  1096. / | Filter dir contents\n\
  1097. ^/ | Search dir in desktop search tool\n\
  1098. . | Toggle hide .dot files\n\
  1099. c | Show change dir prompt\n\
  1100. d | Toggle detail view\n\
  1101. D | Toggle current file details screen\n\
  1102. m | Show concise mediainfo\n\
  1103. M | Show full mediainfo\n\
  1104. s | Toggle sort by file size\n\
  1105. S | Toggle disk usage analyzer mode\n\
  1106. t | Toggle sort by modified time\n\
  1107. ! | Spawn SHELL in PWD (fallback sh)\n\
  1108. e | Edit entry in EDITOR (fallback vi)\n\
  1109. o | Open dir in NNN_DE_FILE_MANAGER\n\
  1110. p | Open entry in PAGER (fallback less)\n\
  1111. ^K | Invoke file path copier\n\
  1112. ^L | Force a redraw\n\
  1113. ? | Toggle help screen\n\
  1114. Q | Quit and change directory\n\
  1115. q, ^Q | Quit\n\n\" | less");
  1116. return system(helpstr);
  1117. }
  1118. static int
  1119. sum_bsizes(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
  1120. {
  1121. if (typeflag == FTW_F || typeflag == FTW_D)
  1122. blk_size += sb->st_blocks;
  1123. return 0;
  1124. }
  1125. static int
  1126. getorder(size_t size)
  1127. {
  1128. switch (size) {
  1129. case 4096:
  1130. return 12;
  1131. case 512:
  1132. return 9;
  1133. case 8192:
  1134. return 13;
  1135. case 16384:
  1136. return 14;
  1137. case 32768:
  1138. return 15;
  1139. case 65536:
  1140. return 16;
  1141. case 131072:
  1142. return 17;
  1143. case 262144:
  1144. return 18;
  1145. case 524288:
  1146. return 19;
  1147. case 1048576:
  1148. return 20;
  1149. case 2048:
  1150. return 11;
  1151. case 1024:
  1152. return 10;
  1153. default:
  1154. return 0;
  1155. }
  1156. }
  1157. static int
  1158. dentfill(char *path, struct entry **dents,
  1159. int (*filter)(regex_t *, char *), regex_t *re)
  1160. {
  1161. static char newpath[PATH_MAX];
  1162. static DIR *dirp;
  1163. static struct dirent *dp;
  1164. static struct stat sb;
  1165. static int n;
  1166. n = 0;
  1167. dirp = opendir(path);
  1168. if (dirp == NULL)
  1169. return 0;
  1170. while ((dp = readdir(dirp)) != NULL) {
  1171. /* Skip self and parent */
  1172. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  1173. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  1174. continue;
  1175. if (filter(re, dp->d_name) == 0)
  1176. continue;
  1177. if (n == total_dents) {
  1178. total_dents += 64;
  1179. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1180. if (*dents == NULL)
  1181. printerr(1, "realloc");
  1182. }
  1183. xstrlcpy((*dents)[n].name, dp->d_name, NAME_MAX);
  1184. /* Get mode flags */
  1185. mkpath(path, dp->d_name, newpath, PATH_MAX);
  1186. if (lstat(newpath, &sb) == -1) {
  1187. if (*dents)
  1188. free(*dents);
  1189. printerr(1, "lstat");
  1190. }
  1191. (*dents)[n].mode = sb.st_mode;
  1192. (*dents)[n].t = sb.st_mtime;
  1193. (*dents)[n].size = sb.st_size;
  1194. if (bsizeorder) {
  1195. if (S_ISDIR(sb.st_mode)) {
  1196. blk_size = 0;
  1197. if (nftw(newpath, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1198. printmsg("nftw(3) failed");
  1199. (*dents)[n].bsize = sb.st_blocks;
  1200. } else
  1201. (*dents)[n].bsize = blk_size;
  1202. } else
  1203. (*dents)[n].bsize = sb.st_blocks;
  1204. }
  1205. n++;
  1206. }
  1207. if (bsizeorder) {
  1208. static struct statvfs svb;
  1209. if (statvfs(path, &svb) == -1)
  1210. fs_free = 0;
  1211. else
  1212. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1213. }
  1214. /* Should never be null */
  1215. if (closedir(dirp) == -1) {
  1216. if (*dents)
  1217. free(*dents);
  1218. printerr(1, "closedir");
  1219. }
  1220. return n;
  1221. }
  1222. static void
  1223. dentfree(struct entry *dents)
  1224. {
  1225. free(dents);
  1226. }
  1227. /* Return the position of the matching entry or 0 otherwise */
  1228. static int
  1229. dentfind(struct entry *dents, int n, char *path)
  1230. {
  1231. if (!path)
  1232. return 0;
  1233. static int i;
  1234. static char *p;
  1235. p = basename(path);
  1236. DPRINTF_S(p);
  1237. for (i = 0; i < n; i++)
  1238. if (strcmp(p, dents[i].name) == 0)
  1239. return i;
  1240. return 0;
  1241. }
  1242. static int
  1243. populate(char *path, char *oldpath, char *fltr)
  1244. {
  1245. static regex_t re;
  1246. /* Can fail when permissions change while browsing */
  1247. if (canopendir(path) == 0)
  1248. return -1;
  1249. /* Search filter */
  1250. if (setfilter(&re, fltr) != 0)
  1251. return -1;
  1252. ndents = dentfill(path, &dents, visible, &re);
  1253. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1254. /* Find cur from history */
  1255. cur = dentfind(dents, ndents, oldpath);
  1256. return 0;
  1257. }
  1258. static void
  1259. redraw(char *path)
  1260. {
  1261. static char cwd[PATH_MAX];
  1262. static int nlines, i;
  1263. static size_t ncols;
  1264. nlines = MIN(LINES - 4, ndents);
  1265. /* Clean screen */
  1266. erase();
  1267. /* Strip trailing slashes */
  1268. for (i = strlen(path) - 1; i > 0; i--)
  1269. if (path[i] == '/')
  1270. path[i] = '\0';
  1271. else
  1272. break;
  1273. DPRINTF_D(cur);
  1274. DPRINTF_S(path);
  1275. /* No text wrapping in cwd line */
  1276. if (!realpath(path, cwd)) {
  1277. printmsg("Cannot resolve path");
  1278. return;
  1279. }
  1280. ncols = COLS;
  1281. if (ncols > PATH_MAX)
  1282. ncols = PATH_MAX;
  1283. cwd[ncols - strlen(CWD) - 1] = '\0';
  1284. printw(CWD "%s\n\n", cwd);
  1285. /* Print listing */
  1286. if (cur < (nlines >> 1)) {
  1287. for (i = 0; i < nlines; i++)
  1288. printptr(&dents[i], i == cur);
  1289. } else if (cur >= ndents - (nlines >> 1)) {
  1290. for (i = ndents - nlines; i < ndents; i++)
  1291. printptr(&dents[i], i == cur);
  1292. } else {
  1293. static int odd;
  1294. odd = ISODD(nlines);
  1295. nlines >>= 1;
  1296. for (i = cur - nlines; i < cur + nlines + odd; i++)
  1297. printptr(&dents[i], i == cur);
  1298. }
  1299. if (showdetail) {
  1300. if (ndents) {
  1301. static char ind[2] = "\0\0";
  1302. static char sort[17];
  1303. if (mtimeorder)
  1304. sprintf(sort, "by time ");
  1305. else if (sizeorder)
  1306. sprintf(sort, "by size ");
  1307. else
  1308. sort[0] = '\0';
  1309. if (S_ISDIR(dents[cur].mode))
  1310. ind[0] = '/';
  1311. else if (S_ISLNK(dents[cur].mode))
  1312. ind[0] = '@';
  1313. else if (S_ISSOCK(dents[cur].mode))
  1314. ind[0] = '=';
  1315. else if (S_ISFIFO(dents[cur].mode))
  1316. ind[0] = '|';
  1317. else if (dents[cur].mode & S_IXUSR)
  1318. ind[0] = '*';
  1319. else
  1320. ind[0] = '\0';
  1321. if (!bsizeorder)
  1322. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  1323. replace_escape(dents[cur].name), ind);
  1324. else
  1325. sprintf(cwd, "total %d by disk usage, %s free [%s%s]",
  1326. ndents, coolsize(fs_free),
  1327. replace_escape(dents[cur].name), ind);
  1328. printmsg(cwd);
  1329. } else
  1330. printmsg("0 items");
  1331. }
  1332. }
  1333. static void
  1334. browse(char *ipath, char *ifilter)
  1335. {
  1336. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1337. static char lastdir[PATH_MAX];
  1338. static char fltr[LINE_MAX];
  1339. char *mime, *dir, *tmp, *run, *env;
  1340. struct stat sb;
  1341. int r, fd, presel;
  1342. enum action sel = SEL_RUNARG + 1;
  1343. xstrlcpy(path, ipath, PATH_MAX);
  1344. xstrlcpy(fltr, ifilter, LINE_MAX);
  1345. oldpath[0] = '\0';
  1346. newpath[0] = '\0';
  1347. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1348. if (filtermode)
  1349. presel = FILTER;
  1350. else
  1351. presel = 0;
  1352. begin:
  1353. if (populate(path, oldpath, fltr) == -1) {
  1354. printwarn();
  1355. goto nochange;
  1356. }
  1357. for (;;) {
  1358. redraw(path);
  1359. nochange:
  1360. /* Exit if parent has exited */
  1361. if (getppid() == 1)
  1362. _exit(0);
  1363. sel = nextsel(&run, &env, &presel);
  1364. switch (sel) {
  1365. case SEL_CDQUIT:
  1366. {
  1367. char *tmpfile = "/tmp/nnn";
  1368. if ((tmp = getenv("NNN_TMPFILE")) != NULL)
  1369. tmpfile = tmp;
  1370. FILE *fp = fopen(tmpfile, "w");
  1371. if (fp) {
  1372. fprintf(fp, "cd \"%s\"", path);
  1373. fclose(fp);
  1374. }
  1375. /* Fall through to exit */
  1376. } // fallthrough
  1377. case SEL_QUIT:
  1378. dentfree(dents);
  1379. return;
  1380. case SEL_BACK:
  1381. /* There is no going back */
  1382. if (path[0] == '/' && path[1] == '\0') {
  1383. printmsg("You are at /");
  1384. goto nochange;
  1385. }
  1386. dir = xdirname(path);
  1387. if (canopendir(dir) == 0) {
  1388. printwarn();
  1389. goto nochange;
  1390. }
  1391. /* Save history */
  1392. xstrlcpy(oldpath, path, PATH_MAX);
  1393. /* Save last working directory */
  1394. xstrlcpy(lastdir, path, PATH_MAX);
  1395. xstrlcpy(path, dir, PATH_MAX);
  1396. /* Reset filter */
  1397. xstrlcpy(fltr, ifilter, LINE_MAX);
  1398. if (filtermode)
  1399. presel = FILTER;
  1400. goto begin;
  1401. case SEL_GOIN:
  1402. /* Cannot descend in empty directories */
  1403. if (ndents == 0)
  1404. goto begin;
  1405. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1406. DPRINTF_S(newpath);
  1407. /* Get path info */
  1408. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1409. if (fd == -1) {
  1410. printwarn();
  1411. goto nochange;
  1412. }
  1413. r = fstat(fd, &sb);
  1414. if (r == -1) {
  1415. printwarn();
  1416. close(fd);
  1417. goto nochange;
  1418. }
  1419. close(fd);
  1420. DPRINTF_U(sb.st_mode);
  1421. switch (sb.st_mode & S_IFMT) {
  1422. case S_IFDIR:
  1423. if (canopendir(newpath) == 0) {
  1424. printwarn();
  1425. goto nochange;
  1426. }
  1427. /* Save last working directory */
  1428. xstrlcpy(lastdir, path, PATH_MAX);
  1429. xstrlcpy(path, newpath, PATH_MAX);
  1430. oldpath[0] = '\0';
  1431. /* Reset filter */
  1432. xstrlcpy(fltr, ifilter, LINE_MAX);
  1433. if (filtermode)
  1434. presel = FILTER;
  1435. goto begin;
  1436. case S_IFREG:
  1437. {
  1438. /* If NNN_USE_EDITOR is set, open text in EDITOR */
  1439. if (editor) {
  1440. mime = getmime(dents[cur].name);
  1441. if (mime) {
  1442. exitcurses();
  1443. spawn(editor, newpath, NULL, NULL, 0);
  1444. initcurses();
  1445. continue;
  1446. }
  1447. /* Recognize and open plain text files with vi */
  1448. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi",
  1449. newpath, 0) == NULL)
  1450. continue;
  1451. if (strstr(g_buf, "text/") == g_buf) {
  1452. exitcurses();
  1453. spawn(editor, newpath, NULL, NULL, 0);
  1454. initcurses();
  1455. continue;
  1456. }
  1457. }
  1458. /* Invoke desktop opener as last resort */
  1459. spawn(utils[0], newpath, NULL, NULL, 4);
  1460. continue;
  1461. }
  1462. default:
  1463. printmsg("Unsupported file");
  1464. goto nochange;
  1465. }
  1466. case SEL_FLTR:
  1467. presel = readln(path);
  1468. xstrlcpy(fltr, ifilter, LINE_MAX);
  1469. DPRINTF_S(fltr);
  1470. /* Save current */
  1471. if (ndents > 0)
  1472. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1473. goto nochange;
  1474. case SEL_MFLTR:
  1475. filtermode = !filtermode;
  1476. if (filtermode)
  1477. presel = FILTER;
  1478. else
  1479. printmsg("navigate-as-you-type off");
  1480. goto nochange;
  1481. case SEL_SEARCH:
  1482. exitcurses();
  1483. spawn(player, path, "search", NULL, 0);
  1484. initcurses();
  1485. break;
  1486. case SEL_NEXT:
  1487. if (cur < ndents - 1)
  1488. cur++;
  1489. else if (ndents)
  1490. /* Roll over, set cursor to first entry */
  1491. cur = 0;
  1492. break;
  1493. case SEL_PREV:
  1494. if (cur > 0)
  1495. cur--;
  1496. else if (ndents)
  1497. /* Roll over, set cursor to last entry */
  1498. cur = ndents - 1;
  1499. break;
  1500. case SEL_PGDN:
  1501. if (cur < ndents - 1)
  1502. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1503. break;
  1504. case SEL_PGUP:
  1505. if (cur > 0)
  1506. cur -= MIN((LINES - 4) / 2, cur);
  1507. break;
  1508. case SEL_HOME:
  1509. cur = 0;
  1510. break;
  1511. case SEL_END:
  1512. cur = ndents - 1;
  1513. break;
  1514. case SEL_CD:
  1515. {
  1516. static char *tmp, *input;
  1517. static int truecd;
  1518. /* Save the program start dir */
  1519. tmp = getcwd(newpath, PATH_MAX);
  1520. if (tmp == NULL) {
  1521. printwarn();
  1522. goto nochange;
  1523. }
  1524. /* Switch to current path for readline(3) */
  1525. if (chdir(path) == -1) {
  1526. printwarn();
  1527. goto nochange;
  1528. }
  1529. exitcurses();
  1530. tmp = readline("chdir: ");
  1531. initcurses();
  1532. /* Change back to program start dir */
  1533. if (chdir(newpath) == -1)
  1534. printwarn();
  1535. if (tmp[0] == '\0')
  1536. break;
  1537. else
  1538. /* Add to readline(3) history */
  1539. add_history(tmp);
  1540. input = tmp;
  1541. tmp = strstrip(tmp);
  1542. if (tmp[0] == '\0') {
  1543. free(input);
  1544. break;
  1545. }
  1546. truecd = 0;
  1547. if (tmp[0] == '~') {
  1548. /* Expand ~ to HOME absolute path */
  1549. char *home = getenv("HOME");
  1550. if (home)
  1551. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  1552. else {
  1553. free(input);
  1554. break;
  1555. }
  1556. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1557. if (lastdir[0] == '\0') {
  1558. free(input);
  1559. break;
  1560. }
  1561. /* Switch to last visited dir */
  1562. xstrlcpy(newpath, lastdir, PATH_MAX);
  1563. truecd = 1;
  1564. } else if ((r = all_dots(tmp))) {
  1565. if (r == 1) {
  1566. /* Always in the current dir */
  1567. free(input);
  1568. break;
  1569. }
  1570. r--;
  1571. dir = path;
  1572. for (fd = 0; fd < r; fd++) {
  1573. /* Reached / ? */
  1574. if (strcmp(path, "/") == 0 ||
  1575. strchr(path, '/') == NULL) {
  1576. /* If it's a cd .. at / */
  1577. if (fd == 0) {
  1578. printmsg("You are at /");
  1579. free(input);
  1580. goto nochange;
  1581. }
  1582. /* Can't cd beyond / anyway */
  1583. break;
  1584. } else {
  1585. dir = xdirname(dir);
  1586. if (canopendir(dir) == 0) {
  1587. printwarn();
  1588. free(input);
  1589. goto nochange;
  1590. }
  1591. }
  1592. }
  1593. truecd = 1;
  1594. /* Save the path in case of cd ..
  1595. We mark the current dir in parent dir */
  1596. if (r == 1) {
  1597. xstrlcpy(oldpath, path, PATH_MAX);
  1598. truecd = 2;
  1599. }
  1600. xstrlcpy(newpath, dir, PATH_MAX);
  1601. } else
  1602. mkpath(path, tmp, newpath, PATH_MAX);
  1603. if (canopendir(newpath) == 0) {
  1604. printwarn();
  1605. free(input);
  1606. break;
  1607. }
  1608. if (truecd == 0) {
  1609. /* Probable change in dir */
  1610. /* No-op if it's the same directory */
  1611. if (strcmp(path, newpath) == 0) {
  1612. free(input);
  1613. break;
  1614. }
  1615. oldpath[0] = '\0';
  1616. } else if (truecd == 1)
  1617. /* Sure change in dir */
  1618. oldpath[0] = '\0';
  1619. /* Save last working directory */
  1620. xstrlcpy(lastdir, path, PATH_MAX);
  1621. /* Save the newly opted dir in path */
  1622. xstrlcpy(path, newpath, PATH_MAX);
  1623. /* Reset filter */
  1624. xstrlcpy(fltr, ifilter, LINE_MAX);
  1625. DPRINTF_S(path);
  1626. free(input);
  1627. if (filtermode)
  1628. presel = FILTER;
  1629. goto begin;
  1630. }
  1631. case SEL_CDHOME:
  1632. tmp = getenv("HOME");
  1633. if (tmp == NULL) {
  1634. clearprompt();
  1635. goto nochange;
  1636. }
  1637. if (canopendir(tmp) == 0) {
  1638. printwarn();
  1639. goto nochange;
  1640. }
  1641. if (strcmp(path, tmp) == 0)
  1642. break;
  1643. /* Save last working directory */
  1644. xstrlcpy(lastdir, path, PATH_MAX);
  1645. xstrlcpy(path, tmp, PATH_MAX);
  1646. oldpath[0] = '\0';
  1647. /* Reset filter */
  1648. xstrlcpy(fltr, ifilter, LINE_MAX);
  1649. DPRINTF_S(path);
  1650. if (filtermode)
  1651. presel = FILTER;
  1652. goto begin;
  1653. case SEL_CDBEGIN:
  1654. if (canopendir(ipath) == 0) {
  1655. printwarn();
  1656. goto nochange;
  1657. }
  1658. if (strcmp(path, ipath) == 0)
  1659. break;
  1660. /* Save last working directory */
  1661. xstrlcpy(lastdir, path, PATH_MAX);
  1662. xstrlcpy(path, ipath, PATH_MAX);
  1663. oldpath[0] = '\0';
  1664. /* Reset filter */
  1665. xstrlcpy(fltr, ifilter, LINE_MAX);
  1666. DPRINTF_S(path);
  1667. if (filtermode)
  1668. presel = FILTER;
  1669. goto begin;
  1670. case SEL_CDLAST:
  1671. if (lastdir[0] == '\0')
  1672. break;
  1673. if (canopendir(lastdir) == 0) {
  1674. printwarn();
  1675. goto nochange;
  1676. }
  1677. xstrlcpy(newpath, lastdir, PATH_MAX);
  1678. xstrlcpy(lastdir, path, PATH_MAX);
  1679. xstrlcpy(path, newpath, PATH_MAX);
  1680. oldpath[0] = '\0';
  1681. /* Reset filter */
  1682. xstrlcpy(fltr, ifilter, LINE_MAX);
  1683. DPRINTF_S(path);
  1684. if (filtermode)
  1685. presel = FILTER;
  1686. goto begin;
  1687. case SEL_TOGGLEDOT:
  1688. showhidden ^= 1;
  1689. initfilter(showhidden, &ifilter);
  1690. xstrlcpy(fltr, ifilter, LINE_MAX);
  1691. goto begin;
  1692. case SEL_DETAIL:
  1693. showdetail = !showdetail;
  1694. showdetail ? (printptr = &printent_long)
  1695. : (printptr = &printent);
  1696. /* Save current */
  1697. if (ndents > 0)
  1698. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1699. goto begin;
  1700. case SEL_STATS:
  1701. {
  1702. struct stat sb;
  1703. if (ndents > 0) {
  1704. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1705. r = lstat(oldpath, &sb);
  1706. if (r == -1) {
  1707. if (dents)
  1708. dentfree(dents);
  1709. printerr(1, "lstat");
  1710. } else {
  1711. exitcurses();
  1712. r = show_stats(oldpath, dents[cur].name, &sb);
  1713. initcurses();
  1714. if (r < 0) {
  1715. printmsg(strerror(errno));
  1716. goto nochange;
  1717. }
  1718. }
  1719. }
  1720. break;
  1721. }
  1722. case SEL_MEDIA:
  1723. if (ndents > 0) {
  1724. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1725. if(show_mediainfo(oldpath, NULL) == -1) {
  1726. printmsg("mediainfo missing");
  1727. goto nochange;
  1728. }
  1729. }
  1730. break;
  1731. case SEL_FMEDIA:
  1732. if (ndents > 0) {
  1733. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1734. if(show_mediainfo(oldpath, "-f") == -1) {
  1735. printmsg("mediainfo missing");
  1736. goto nochange;
  1737. }
  1738. }
  1739. break;
  1740. case SEL_DFB:
  1741. if (!desktop_manager) {
  1742. printmsg("NNN_DE_FILE_MANAGER not set");
  1743. goto nochange;
  1744. }
  1745. spawn(desktop_manager, path, NULL, path, 2);
  1746. break;
  1747. case SEL_FSIZE:
  1748. sizeorder = !sizeorder;
  1749. mtimeorder = 0;
  1750. bsizeorder = 0;
  1751. /* Save current */
  1752. if (ndents > 0)
  1753. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1754. goto begin;
  1755. case SEL_BSIZE:
  1756. bsizeorder = !bsizeorder;
  1757. if (bsizeorder) {
  1758. showdetail = 1;
  1759. printptr = &printent_long;
  1760. }
  1761. mtimeorder = 0;
  1762. sizeorder = 0;
  1763. /* Save current */
  1764. if (ndents > 0)
  1765. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1766. goto begin;
  1767. case SEL_MTIME:
  1768. mtimeorder = !mtimeorder;
  1769. sizeorder = 0;
  1770. bsizeorder = 0;
  1771. /* Save current */
  1772. if (ndents > 0)
  1773. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1774. goto begin;
  1775. case SEL_REDRAW:
  1776. /* Save current */
  1777. if (ndents > 0)
  1778. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1779. goto begin;
  1780. case SEL_COPY:
  1781. if (copier && ndents) {
  1782. if (strcmp(path, "/") == 0)
  1783. snprintf(newpath, PATH_MAX, "/%s",
  1784. dents[cur].name);
  1785. else
  1786. snprintf(newpath, PATH_MAX, "%s/%s",
  1787. path, dents[cur].name);
  1788. spawn(copier, newpath, NULL, NULL, 0);
  1789. printmsg(newpath);
  1790. } else if (!copier)
  1791. printmsg("NNN_COPIER is not set");
  1792. goto nochange;
  1793. case SEL_HELP:
  1794. exitcurses();
  1795. show_help();
  1796. initcurses();
  1797. break;
  1798. case SEL_RUN:
  1799. run = xgetenv(env, run);
  1800. exitcurses();
  1801. spawn(run, NULL, NULL, path, 1);
  1802. initcurses();
  1803. /* Repopulate as directory content may have changed */
  1804. goto begin;
  1805. case SEL_RUNARG:
  1806. run = xgetenv(env, run);
  1807. exitcurses();
  1808. spawn(run, dents[cur].name, NULL, path, 0);
  1809. initcurses();
  1810. break;
  1811. }
  1812. /* Screensaver */
  1813. if (idletimeout != 0 && idle == idletimeout) {
  1814. idle = 0;
  1815. exitcurses();
  1816. spawn(player, "", "screensaver", NULL, 8);
  1817. initcurses();
  1818. }
  1819. }
  1820. }
  1821. static void
  1822. usage(void)
  1823. {
  1824. fprintf(stdout, "usage: nnn [-d] [-i] [-p custom_nlay] [-S] [-v] [-h] [PATH]\n\n\
  1825. The missing terminal file browser for X.\n\n\
  1826. positional arguments:\n\
  1827. PATH directory to open [default: current dir]\n\n\
  1828. optional arguments:\n\
  1829. -d start in detail view mode\n\
  1830. -i start in navigate-as-you-type mode\n\
  1831. -p path to custom nlay\n\
  1832. -S start in disk usage analyzer mode\n\
  1833. -v show program version and exit\n\
  1834. -h show this help and exit\n\n\
  1835. Version: %s\n\
  1836. License: BSD 2-Clause\n\
  1837. Webpage: https://github.com/jarun/nnn\n", VERSION);
  1838. exit(0);
  1839. }
  1840. int
  1841. main(int argc, char *argv[])
  1842. {
  1843. char cwd[PATH_MAX], *ipath;
  1844. char *ifilter;
  1845. int opt = 0;
  1846. /* Confirm we are in a terminal */
  1847. if (!isatty(0) || !isatty(1)) {
  1848. fprintf(stderr, "stdin or stdout is not a tty\n");
  1849. exit(1);
  1850. }
  1851. while ((opt = getopt(argc, argv, "dSip:vh")) != -1) {
  1852. switch (opt) {
  1853. case 'S':
  1854. bsizeorder = 1; // fallthrough
  1855. case 'd':
  1856. /* Open in detail mode, if set */
  1857. showdetail = 1;
  1858. printptr = &printent_long;
  1859. break;
  1860. case 'i':
  1861. filtermode = 1;
  1862. break;
  1863. case 'p':
  1864. player = optarg;
  1865. break;
  1866. case 'v':
  1867. fprintf(stdout, "%s\n", VERSION);
  1868. return 0;
  1869. case 'h': // fallthrough
  1870. default:
  1871. usage();
  1872. }
  1873. }
  1874. if (argc == optind) {
  1875. /* Start in the current directory */
  1876. ipath = getcwd(cwd, PATH_MAX);
  1877. if (ipath == NULL)
  1878. ipath = "/";
  1879. } else {
  1880. ipath = realpath(argv[optind], cwd);
  1881. if (!ipath) {
  1882. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1883. exit(1);
  1884. }
  1885. }
  1886. open_max = max_openfds();
  1887. if (getuid() == 0)
  1888. showhidden = 1;
  1889. initfilter(showhidden, &ifilter);
  1890. /* Edit text in EDITOR, if opted */
  1891. if (getenv("NNN_USE_EDITOR"))
  1892. editor = xgetenv("EDITOR", "vi");
  1893. /* Set player if not set already */
  1894. if (!player)
  1895. player = utils[1];
  1896. /* Get the desktop file browser, if set */
  1897. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  1898. /* Get screensaver wait time, if set; copier used as tmp var */
  1899. copier = getenv("NNN_IDLE_TIMEOUT");
  1900. if (copier)
  1901. idletimeout = abs(atoi(copier));
  1902. /* Get the default copier, if set */
  1903. copier = getenv("NNN_COPIER");
  1904. signal(SIGINT, SIG_IGN);
  1905. /* Test initial path */
  1906. if (canopendir(ipath) == 0) {
  1907. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1908. exit(1);
  1909. }
  1910. /* Set locale */
  1911. setlocale(LC_ALL, "");
  1912. initcurses();
  1913. browse(ipath, ifilter);
  1914. exitcurses();
  1915. exit(0);
  1916. }