My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2146 lines
44 KiB

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