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.
 
 
 
 
 
 

2156 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 <limits.h>
  14. #ifdef __gnu_hurd__
  15. #define PATH_MAX 4096
  16. #endif
  17. #include <locale.h>
  18. #include <pwd.h>
  19. #include <regex.h>
  20. #include <signal.h>
  21. #include <stdarg.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <string.h>
  25. #include <time.h>
  26. #include <unistd.h>
  27. #include <wchar.h>
  28. #include <readline/readline.h>
  29. #ifndef __USE_XOPEN_EXTENDED
  30. #define __USE_XOPEN_EXTENDED 1
  31. #endif
  32. #include <ftw.h>
  33. #ifdef DEBUG
  34. static int
  35. xprintf(int fd, const char *fmt, ...)
  36. {
  37. char buf[BUFSIZ];
  38. int r;
  39. va_list ap;
  40. va_start(ap, fmt);
  41. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  42. if (r > 0)
  43. r = write(fd, buf, r);
  44. va_end(ap);
  45. return r;
  46. }
  47. #define DEBUG_FD 8
  48. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  49. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  50. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  51. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=0x%p\n", x)
  52. #else
  53. #define DPRINTF_D(x)
  54. #define DPRINTF_U(x)
  55. #define DPRINTF_S(x)
  56. #define DPRINTF_P(x)
  57. #endif /* DEBUG */
  58. #define VERSION "v1.1"
  59. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  60. #undef MIN
  61. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  62. #define ISODD(x) ((x) & 1)
  63. #define CONTROL(c) ((c) ^ 0x40)
  64. #define TOUPPER(ch) \
  65. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  66. #define MAX_CMD_LEN 5120
  67. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  68. struct assoc {
  69. char *regex; /* Regex to match on filename */
  70. char *mime; /* File type */
  71. };
  72. /* Supported actions */
  73. enum action {
  74. SEL_QUIT = 1,
  75. SEL_CDQUIT,
  76. SEL_BACK,
  77. SEL_GOIN,
  78. SEL_FLTR,
  79. SEL_SEARCH,
  80. SEL_NEXT,
  81. SEL_PREV,
  82. SEL_PGDN,
  83. SEL_PGUP,
  84. SEL_HOME,
  85. SEL_END,
  86. SEL_CD,
  87. SEL_CDHOME,
  88. SEL_CDBEGIN,
  89. SEL_CDLAST,
  90. SEL_TOGGLEDOT,
  91. SEL_DETAIL,
  92. SEL_STATS,
  93. SEL_MEDIA,
  94. SEL_FMEDIA,
  95. SEL_DFB,
  96. SEL_FSIZE,
  97. SEL_BSIZE,
  98. SEL_MTIME,
  99. SEL_REDRAW,
  100. SEL_COPY,
  101. SEL_HELP,
  102. SEL_RUN,
  103. SEL_RUNARG,
  104. };
  105. struct key {
  106. int sym; /* Key pressed */
  107. enum action act; /* Action */
  108. char *run; /* Program to run */
  109. char *env; /* Environment variable to run */
  110. };
  111. #include "config.h"
  112. typedef struct entry {
  113. char name[NAME_MAX];
  114. mode_t mode;
  115. time_t t;
  116. off_t size;
  117. off_t bsize;
  118. } *pEntry;
  119. typedef unsigned long ulong;
  120. /* Externs */
  121. #ifdef __APPLE__
  122. extern int add_history(const char *);
  123. #else
  124. extern void add_history(const char *string);
  125. #endif
  126. extern int wget_wch(WINDOW *, wint_t *);
  127. /* Global context */
  128. static struct entry *dents;
  129. static int ndents, cur, total_dents;
  130. static int idle;
  131. static char *opener;
  132. static char *fb_opener;
  133. static char *player;
  134. static char *copier;
  135. static char *desktop_manager;
  136. static off_t blk_size;
  137. static size_t fs_free;
  138. static int open_max;
  139. static const double div_2_pow_10 = 1.0 / 1024.0;
  140. /* For use in functions which are isolated and don't return the buffer */
  141. static char g_buf[MAX_CMD_LEN];
  142. /*
  143. * Layout:
  144. * .---------
  145. * | cwd: /mnt/path
  146. * |
  147. * | file0
  148. * | file1
  149. * | > file2
  150. * | file3
  151. * | file4
  152. * ...
  153. * | filen
  154. * |
  155. * | Permission denied
  156. * '------
  157. */
  158. static void printmsg(char *);
  159. static void printwarn(void);
  160. static void printerr(int, char *);
  161. static int dentfind(struct entry *dents, int n, char *path);
  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. static int
  535. fill(struct entry **dents,
  536. int (*filter)(regex_t *, char *), regex_t *re)
  537. {
  538. static struct entry _dent;
  539. static int count, n;
  540. for (count = 0, n = 0; count < ndents; count++) {
  541. if (filter(re, (*dents)[count].name) == 0)
  542. continue;
  543. if (n != count) {
  544. /* Copy to tmp */
  545. xstrlcpy(_dent.name, (*dents)[n].name, NAME_MAX);
  546. _dent.mode = (*dents)[n].mode;
  547. _dent.t = (*dents)[n].t;
  548. _dent.size = (*dents)[n].size;
  549. _dent.bsize = (*dents)[n].bsize;
  550. /* Copy count to n */
  551. xstrlcpy((*dents)[n].name, (*dents)[count].name, NAME_MAX);
  552. (*dents)[n].mode = (*dents)[count].mode;
  553. (*dents)[n].t = (*dents)[count].t;
  554. (*dents)[n].size = (*dents)[count].size;
  555. (*dents)[n].bsize = (*dents)[count].bsize;
  556. /* Copy tmp to count */
  557. xstrlcpy((*dents)[count].name, _dent.name, NAME_MAX);
  558. (*dents)[count].mode = _dent.mode;
  559. (*dents)[count].t = _dent.t;
  560. (*dents)[count].size = _dent.size;
  561. (*dents)[count].bsize = _dent.bsize;
  562. }
  563. n++;
  564. }
  565. return n;
  566. }
  567. static int
  568. matches(char *fltr)
  569. {
  570. static regex_t re;
  571. /* Search filter */
  572. if (setfilter(&re, fltr) != 0)
  573. return -1;
  574. ndents = fill(&dents, visible, &re);
  575. qsort(dents, ndents, sizeof(*dents), entrycmp);
  576. return 0;
  577. }
  578. static int
  579. readln(char *path)
  580. {
  581. static char ln[LINE_MAX << 2];
  582. static wchar_t wln[LINE_MAX];
  583. static wint_t ch[2] = {0};
  584. int r, total = ndents;
  585. int oldcur = cur;
  586. int len = 1;
  587. char *pln = ln + 1;
  588. memset(wln, 0, LINE_MAX << 2);
  589. wln[0] = '/';
  590. ln[0] = '/';
  591. ln[1] = '\0';
  592. cur = 0;
  593. timeout(-1);
  594. echo();
  595. curs_set(TRUE);
  596. printprompt(ln);
  597. while ((r = wget_wch(stdscr, ch)) != ERR) {
  598. if (r == OK) {
  599. switch(*ch) {
  600. case '\r': // with nonl(), this is ENTER key value
  601. if (len == 1) {
  602. cur = oldcur;
  603. *ch = CONTROL('L');
  604. goto end;
  605. }
  606. if (matches(pln) == -1)
  607. goto end;
  608. redraw(path);
  609. goto end;
  610. case 127: // handle DEL
  611. if (len == 1) {
  612. cur = oldcur;
  613. *ch = CONTROL('L');
  614. goto end;
  615. }
  616. if (len == 2)
  617. cur = oldcur;
  618. wln[--len] = '\0';
  619. wcstombs(ln, wln, LINE_MAX << 2);
  620. ndents = total;
  621. if (matches(pln) == -1)
  622. continue;
  623. redraw(path);
  624. printprompt(ln);
  625. break;
  626. default:
  627. wln[len++] = (wchar_t)*ch;
  628. wln[len] = '\0';
  629. wcstombs(ln, wln, LINE_MAX << 2);
  630. ndents = total;
  631. if (matches(pln) == -1)
  632. continue;
  633. redraw(path);
  634. printprompt(ln);
  635. }
  636. } else {
  637. switch(*ch) {
  638. case KEY_DC:
  639. case KEY_BACKSPACE:
  640. if (len == 1) {
  641. cur = oldcur;
  642. *ch = CONTROL('L');
  643. goto end;
  644. }
  645. if (len == 2)
  646. cur = oldcur;
  647. wln[--len] = '\0';
  648. wcstombs(ln, wln, LINE_MAX << 2);
  649. ndents = total;
  650. if (matches(pln) == -1)
  651. continue;
  652. redraw(path);
  653. printprompt(ln);
  654. break;
  655. default:
  656. goto end;
  657. }
  658. }
  659. }
  660. end:
  661. noecho();
  662. curs_set(FALSE);
  663. timeout(1000);
  664. return *ch;
  665. }
  666. static int
  667. canopendir(char *path)
  668. {
  669. static DIR *dirp;
  670. dirp = opendir(path);
  671. if (dirp == NULL)
  672. return 0;
  673. closedir(dirp);
  674. return 1;
  675. }
  676. /*
  677. * Returns "dir/name or "/name"
  678. */
  679. static char *
  680. mkpath(char *dir, char *name, char *out, size_t n)
  681. {
  682. /* Handle absolute path */
  683. if (name[0] == '/')
  684. xstrlcpy(out, name, n);
  685. else {
  686. /* Handle root case */
  687. if (strcmp(dir, "/") == 0)
  688. snprintf(out, n, "/%s", name);
  689. else
  690. snprintf(out, n, "%s/%s", dir, name);
  691. }
  692. return out;
  693. }
  694. static char *
  695. replace_escape(const char *str)
  696. {
  697. static char buffer[PATH_MAX];
  698. static wchar_t wbuf[PATH_MAX];
  699. static wchar_t *buf;
  700. buffer[0] = '\0';
  701. buf = wbuf;
  702. /* Convert multi-byte to wide char */
  703. mbstowcs(wbuf, str, PATH_MAX);
  704. while (*buf) {
  705. if (*buf <= '\x1f' || *buf == '\x7f')
  706. *buf = '\?';
  707. buf++;
  708. }
  709. /* Convert wide char to multi-byte */
  710. wcstombs(buffer, wbuf, PATH_MAX);
  711. return buffer;
  712. }
  713. static void
  714. printent(struct entry *ent, int active)
  715. {
  716. static int ncols;
  717. if (COLS > PATH_MAX + 16)
  718. ncols = PATH_MAX + 16;
  719. else
  720. ncols = COLS;
  721. if (S_ISDIR(ent->mode))
  722. snprintf(g_buf, ncols, "%s%s/", CURSYM(active),
  723. replace_escape(ent->name));
  724. else if (S_ISLNK(ent->mode))
  725. snprintf(g_buf, ncols, "%s%s@", CURSYM(active),
  726. replace_escape(ent->name));
  727. else if (S_ISSOCK(ent->mode))
  728. snprintf(g_buf, ncols, "%s%s=", CURSYM(active),
  729. replace_escape(ent->name));
  730. else if (S_ISFIFO(ent->mode))
  731. snprintf(g_buf, ncols, "%s%s|", CURSYM(active),
  732. replace_escape(ent->name));
  733. else if (ent->mode & S_IXUSR)
  734. snprintf(g_buf, ncols, "%s%s*", CURSYM(active),
  735. replace_escape(ent->name));
  736. else
  737. snprintf(g_buf, ncols, "%s%s", CURSYM(active),
  738. replace_escape(ent->name));
  739. printw("%s\n", g_buf);
  740. }
  741. static void (*printptr)(struct entry *ent, int active) = &printent;
  742. static char*
  743. coolsize(off_t size)
  744. {
  745. static const char *size_units[] = {"B", "K", "M", "G", "T", "P", "E", "Z", "Y"};
  746. static char size_buf[12]; /* Buffer to hold human readable size */
  747. static int i;
  748. static off_t fsize, tmp;
  749. static long double rem;
  750. i = 0;
  751. fsize = size;
  752. rem = 0;
  753. while (fsize > 1024) {
  754. tmp = fsize;
  755. //fsize *= div_2_pow_10;
  756. fsize >>= 10;
  757. rem = tmp - (fsize << 10);
  758. i++;
  759. }
  760. snprintf(size_buf, 12, "%.*Lf%s", i, fsize + rem * div_2_pow_10, size_units[i]);
  761. return size_buf;
  762. }
  763. static void
  764. printent_long(struct entry *ent, int active)
  765. {
  766. static int ncols;
  767. static char buf[18];
  768. if (COLS > PATH_MAX + 32)
  769. ncols = PATH_MAX + 32;
  770. else
  771. ncols = COLS;
  772. strftime(buf, 18, "%d %m %Y %H:%M", localtime(&ent->t));
  773. if (active)
  774. attron(A_REVERSE);
  775. if (!bsizeorder) {
  776. if (S_ISDIR(ent->mode))
  777. snprintf(g_buf, ncols, "%s%-16.16s / %s/",
  778. CURSYM(active), buf, replace_escape(ent->name));
  779. else if (S_ISLNK(ent->mode))
  780. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  781. CURSYM(active), buf, replace_escape(ent->name));
  782. else if (S_ISSOCK(ent->mode))
  783. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  784. CURSYM(active), buf, replace_escape(ent->name));
  785. else if (S_ISFIFO(ent->mode))
  786. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  787. CURSYM(active), buf, replace_escape(ent->name));
  788. else if (S_ISBLK(ent->mode))
  789. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  790. CURSYM(active), buf, replace_escape(ent->name));
  791. else if (S_ISCHR(ent->mode))
  792. snprintf(g_buf, ncols, "%s%-16.16s c %s",
  793. CURSYM(active), buf, replace_escape(ent->name));
  794. else if (ent->mode & S_IXUSR)
  795. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  796. CURSYM(active), buf, coolsize(ent->size),
  797. replace_escape(ent->name));
  798. else
  799. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  800. CURSYM(active), buf, coolsize(ent->size),
  801. replace_escape(ent->name));
  802. } else {
  803. if (S_ISDIR(ent->mode))
  804. snprintf(g_buf, ncols, "%s%-16.16s %8.8s/ %s/",
  805. CURSYM(active), buf, coolsize(ent->bsize << 9),
  806. replace_escape(ent->name));
  807. else if (S_ISLNK(ent->mode))
  808. snprintf(g_buf, ncols, "%s%-16.16s @ %s@",
  809. CURSYM(active), buf,
  810. replace_escape(ent->name));
  811. else if (S_ISSOCK(ent->mode))
  812. snprintf(g_buf, ncols, "%s%-16.16s = %s=",
  813. CURSYM(active), buf,
  814. replace_escape(ent->name));
  815. else if (S_ISFIFO(ent->mode))
  816. snprintf(g_buf, ncols, "%s%-16.16s | %s|",
  817. CURSYM(active), buf,
  818. replace_escape(ent->name));
  819. else if (S_ISBLK(ent->mode))
  820. snprintf(g_buf, ncols, "%s%-16.16s b %s",
  821. CURSYM(active), buf,
  822. 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,
  826. replace_escape(ent->name));
  827. else if (ent->mode & S_IXUSR)
  828. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*",
  829. CURSYM(active), buf, coolsize(ent->bsize << 9),
  830. replace_escape(ent->name));
  831. else
  832. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s",
  833. CURSYM(active), buf, coolsize(ent->bsize << 9),
  834. replace_escape(ent->name));
  835. }
  836. printw("%s\n", g_buf);
  837. if (active)
  838. attroff(A_REVERSE);
  839. }
  840. static char
  841. get_fileind(mode_t mode, char *desc)
  842. {
  843. static char c;
  844. if (S_ISREG(mode)) {
  845. c = '-';
  846. sprintf(desc, "%s", "regular file");
  847. if (mode & S_IXUSR)
  848. strcat(desc, ", executable");
  849. } else if (S_ISDIR(mode)) {
  850. c = 'd';
  851. sprintf(desc, "%s", "directory");
  852. } else if (S_ISBLK(mode)) {
  853. c = 'b';
  854. sprintf(desc, "%s", "block special device");
  855. } else if (S_ISCHR(mode)) {
  856. c = 'c';
  857. sprintf(desc, "%s", "character special device");
  858. #ifdef S_ISFIFO
  859. } else if (S_ISFIFO(mode)) {
  860. c = 'p';
  861. sprintf(desc, "%s", "FIFO");
  862. #endif /* S_ISFIFO */
  863. #ifdef S_ISLNK
  864. } else if (S_ISLNK(mode)) {
  865. c = 'l';
  866. sprintf(desc, "%s", "symbolic link");
  867. #endif /* S_ISLNK */
  868. #ifdef S_ISSOCK
  869. } else if (S_ISSOCK(mode)) {
  870. c = 's';
  871. sprintf(desc, "%s", "socket");
  872. #endif /* S_ISSOCK */
  873. #ifdef S_ISDOOR
  874. /* Solaris 2.6, etc. */
  875. } else if (S_ISDOOR(mode)) {
  876. c = 'D';
  877. desc[0] = '\0';
  878. #endif /* S_ISDOOR */
  879. } else {
  880. /* Unknown type -- possibly a regular file? */
  881. c = '?';
  882. desc[0] = '\0';
  883. }
  884. return(c);
  885. }
  886. /* Convert a mode field into "ls -l" type perms field. */
  887. static char *
  888. get_lsperms(mode_t mode, char *desc)
  889. {
  890. static const char *rwx[] = {"---", "--x", "-w-", "-wx",
  891. "r--", "r-x", "rw-", "rwx"};
  892. static char bits[11];
  893. bits[0] = get_fileind(mode, desc);
  894. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  895. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  896. strcpy(&bits[7], rwx[(mode & 7)]);
  897. if (mode & S_ISUID)
  898. bits[3] = (mode & S_IXUSR) ? 's' : 'S';
  899. if (mode & S_ISGID)
  900. bits[6] = (mode & S_IXGRP) ? 's' : 'l';
  901. if (mode & S_ISVTX)
  902. bits[9] = (mode & S_IXOTH) ? 't' : 'T';
  903. bits[10] = '\0';
  904. return(bits);
  905. }
  906. /*
  907. * Gets only a single line (that's what we need
  908. * for now) or shows full command output in pager.
  909. *
  910. * If pager is valid, returns NULL
  911. */
  912. static char *
  913. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  914. {
  915. pid_t pid;
  916. int pipefd[2];
  917. FILE* pf;
  918. int status;
  919. char *ret = NULL;
  920. if (pipe(pipefd) == -1)
  921. printerr(1, "pipe(2)");
  922. pid = fork();
  923. if (pid == 0) {
  924. /* In child */
  925. close(pipefd[0]);
  926. dup2(pipefd[1], STDOUT_FILENO);
  927. dup2(pipefd[1], STDERR_FILENO);
  928. execlp(file, file, arg1, arg2, NULL);
  929. _exit(1);
  930. }
  931. /* In parent */
  932. waitpid(pid, &status, 0);
  933. close(pipefd[1]);
  934. if (!pager) {
  935. if ((pf = fdopen(pipefd[0], "r"))) {
  936. ret = fgets(buf, bytes, pf);
  937. close(pipefd[0]);
  938. }
  939. return ret;
  940. }
  941. pid = fork();
  942. if (pid == 0) {
  943. /* Show in pager in child */
  944. dup2(pipefd[0], STDIN_FILENO);
  945. execlp("less", "less", NULL);
  946. close(pipefd[0]);
  947. _exit(1);
  948. }
  949. /* In parent */
  950. waitpid(pid, &status, 0);
  951. return NULL;
  952. }
  953. /*
  954. * Follows the stat(1) output closely
  955. */
  956. static int
  957. show_stats(char* fpath, char* fname, struct stat *sb)
  958. {
  959. char *perms = get_lsperms(sb->st_mode, g_buf);
  960. char *p, *begin = g_buf;
  961. char tmp[] = "/tmp/nnnXXXXXX";
  962. int fd = mkstemp(tmp);
  963. if (fd == -1)
  964. return -1;
  965. /* Show file name or 'symlink' -> 'target' */
  966. if (perms[0] == 'l') {
  967. /* Note that MAX_CMD_LEN > PATH_MAX */
  968. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  969. if (len != -1) {
  970. g_buf[len] = '\0';
  971. dprintf(fd, " File: '%s' -> ",
  972. replace_escape(fname));
  973. dprintf(fd, "'%s'",
  974. replace_escape(g_buf));
  975. }
  976. } else
  977. dprintf(fd, " File: '%s'", replace_escape(fname));
  978. /* Show size, blocks, file type */
  979. #ifdef __APPLE__
  980. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  981. #else
  982. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  983. #endif
  984. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  985. /* Show containing device, inode, hardlink count */
  986. #ifdef __APPLE__
  987. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  988. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  989. #else
  990. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  991. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  992. #endif
  993. g_buf, sb->st_ino, sb->st_nlink);
  994. /* Show major, minor number for block or char device */
  995. if (perms[0] == 'b' || perms[0] == 'c')
  996. dprintf(fd, " Device type: %x,%x",
  997. major(sb->st_rdev), minor(sb->st_rdev));
  998. /* Show permissions, owner, group */
  999. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  1000. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  1001. perms,
  1002. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  1003. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1004. /* Show last access time */
  1005. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1006. dprintf(fd, "\n\n Access: %s", g_buf);
  1007. /* Show last modification time */
  1008. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1009. dprintf(fd, "\n Modify: %s", g_buf);
  1010. /* Show last status change time */
  1011. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1012. dprintf(fd, "\n Change: %s", g_buf);
  1013. if (S_ISREG(sb->st_mode)) {
  1014. /* Show file(1) output */
  1015. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1016. if (p) {
  1017. dprintf(fd, "\n\n ");
  1018. while (*p) {
  1019. if (*p == ',') {
  1020. *p = '\0';
  1021. dprintf(fd, " %s\n", begin);
  1022. begin = p + 1;
  1023. }
  1024. p++;
  1025. }
  1026. dprintf(fd, " %s", begin);
  1027. }
  1028. dprintf(fd, "\n\n");
  1029. } else
  1030. dprintf(fd, "\n\n\n");
  1031. close(fd);
  1032. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1033. unlink(tmp);
  1034. return 0;
  1035. }
  1036. static int
  1037. show_mediainfo(char* fpath, char *arg)
  1038. {
  1039. if (get_output(g_buf, MAX_CMD_LEN, "which", "mediainfo", NULL, 0) == NULL)
  1040. return -1;
  1041. exitcurses();
  1042. get_output(NULL, 0, "mediainfo", fpath, arg, 1);
  1043. initcurses();
  1044. return 0;
  1045. }
  1046. static int
  1047. show_help(void)
  1048. {
  1049. static char helpstr[] = ("echo \"\
  1050. Key | Function\n\
  1051. -+-\n\
  1052. Up, k, ^P | Previous entry\n\
  1053. Down, j, ^N | Next entry\n\
  1054. PgUp, ^U | Scroll half page up\n\
  1055. PgDn, ^D | Scroll half page down\n\
  1056. Home, g, ^, ^A | Jump to first entry\n\
  1057. End, G, $, ^E | Jump to last entry\n\
  1058. Right, Enter, l, ^M | Open file or enter dir\n\
  1059. Left, Bksp, h, ^H | Go to parent dir\n\
  1060. ~ | Jump to HOME dir\n\
  1061. & | Jump to initial dir\n\
  1062. - | Jump to last visited dir\n\
  1063. o | Open dir in NNN_DE_FILE_MANAGER\n\
  1064. / | Filter dir contents\n\
  1065. ^/ | Search dir in catfish\n\
  1066. c | Show change dir prompt\n\
  1067. d | Toggle detail view\n\
  1068. D | Toggle current file details screen\n\
  1069. m | Show concise mediainfo\n\
  1070. M | Show full mediainfo\n\
  1071. . | Toggle hide .dot files\n\
  1072. s | Toggle sort by file size\n\
  1073. S | Toggle disk usage analyzer mode\n\
  1074. t | Toggle sort by modified time\n\
  1075. ! | Spawn SHELL in PWD (fallback sh)\n\
  1076. z | Run top\n\
  1077. e | Edit entry in EDITOR (fallback vi)\n\
  1078. p | Open entry in PAGER (fallback less)\n\
  1079. ^K | Invoke file name copier\n\
  1080. ^L | Force a redraw\n\
  1081. ? | Toggle help screen\n\
  1082. q | Quit\n\
  1083. Q | Quit and change directory\n\n\" | less");
  1084. return system(helpstr);
  1085. }
  1086. static int
  1087. sum_bsizes(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
  1088. {
  1089. if(typeflag == FTW_F || typeflag == FTW_D)
  1090. blk_size += sb->st_blocks;
  1091. return 0;
  1092. }
  1093. static int
  1094. getorder(size_t size)
  1095. {
  1096. switch (size) {
  1097. case 4096:
  1098. return 12;
  1099. case 512:
  1100. return 9;
  1101. case 8192:
  1102. return 13;
  1103. case 16384:
  1104. return 14;
  1105. case 32768:
  1106. return 15;
  1107. case 65536:
  1108. return 16;
  1109. case 131072:
  1110. return 17;
  1111. case 262144:
  1112. return 18;
  1113. case 524288:
  1114. return 19;
  1115. case 1048576:
  1116. return 20;
  1117. case 2048:
  1118. return 11;
  1119. case 1024:
  1120. return 10;
  1121. default:
  1122. return 0;
  1123. }
  1124. }
  1125. static int
  1126. dentfill(char *path, struct entry **dents,
  1127. int (*filter)(regex_t *, char *), regex_t *re)
  1128. {
  1129. static char newpath[PATH_MAX];
  1130. static DIR *dirp;
  1131. static struct dirent *dp;
  1132. static struct stat sb;
  1133. static struct statvfs svb;
  1134. static int r, n;
  1135. r = 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. r = lstat(newpath, &sb);
  1156. if (r == -1) {
  1157. if (*dents)
  1158. free(*dents);
  1159. printerr(1, "lstat");
  1160. }
  1161. (*dents)[n].mode = sb.st_mode;
  1162. (*dents)[n].t = sb.st_mtime;
  1163. (*dents)[n].size = sb.st_size;
  1164. if (bsizeorder) {
  1165. if (S_ISDIR(sb.st_mode)) {
  1166. blk_size = 0;
  1167. if (nftw(newpath, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1168. printmsg("nftw(3) failed");
  1169. (*dents)[n].bsize = sb.st_blocks;
  1170. } else
  1171. (*dents)[n].bsize = blk_size;
  1172. } else
  1173. (*dents)[n].bsize = sb.st_blocks;
  1174. }
  1175. n++;
  1176. }
  1177. if (bsizeorder) {
  1178. r = statvfs(path, &svb);
  1179. if (r == -1)
  1180. fs_free = 0;
  1181. else
  1182. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1183. }
  1184. /* Should never be null */
  1185. r = closedir(dirp);
  1186. if (r == -1) {
  1187. if (*dents)
  1188. free(*dents);
  1189. printerr(1, "closedir");
  1190. }
  1191. return n;
  1192. }
  1193. static void
  1194. dentfree(struct entry *dents)
  1195. {
  1196. free(dents);
  1197. }
  1198. /* Return the position of the matching entry or 0 otherwise */
  1199. static int
  1200. dentfind(struct entry *dents, int n, char *path)
  1201. {
  1202. if (!path)
  1203. return 0;
  1204. static int i;
  1205. static char *p;
  1206. p = xmemrchr(path, '/', strlen(path));
  1207. if (!p)
  1208. p = path;
  1209. else
  1210. /* We are assuming an entry with actual
  1211. name ending in '/' will not appear */
  1212. p++;
  1213. DPRINTF_S(p);
  1214. for (i = 0; i < n; i++)
  1215. if (strcmp(p, dents[i].name) == 0)
  1216. return i;
  1217. return 0;
  1218. }
  1219. static int
  1220. populate(char *path, char *oldpath, char *fltr)
  1221. {
  1222. static regex_t re;
  1223. static int r;
  1224. /* Can fail when permissions change while browsing */
  1225. if (canopendir(path) == 0)
  1226. return -1;
  1227. /* Search filter */
  1228. r = setfilter(&re, fltr);
  1229. if (r != 0)
  1230. return -1;
  1231. ndents = dentfill(path, &dents, visible, &re);
  1232. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1233. /* Find cur from history */
  1234. cur = dentfind(dents, ndents, oldpath);
  1235. return 0;
  1236. }
  1237. static void
  1238. redraw(char *path)
  1239. {
  1240. static char cwd[PATH_MAX];
  1241. static int nlines, odd;
  1242. static int i;
  1243. static size_t ncols;
  1244. nlines = MIN(LINES - 4, ndents);
  1245. /* Clean screen */
  1246. erase();
  1247. /* Strip trailing slashes */
  1248. for (i = strlen(path) - 1; i > 0; i--)
  1249. if (path[i] == '/')
  1250. path[i] = '\0';
  1251. else
  1252. break;
  1253. DPRINTF_D(cur);
  1254. DPRINTF_S(path);
  1255. /* No text wrapping in cwd line */
  1256. if (!realpath(path, cwd)) {
  1257. printmsg("Cannot resolve path");
  1258. return;
  1259. }
  1260. ncols = COLS;
  1261. if (ncols > PATH_MAX)
  1262. ncols = PATH_MAX;
  1263. cwd[ncols - strlen(CWD) - 1] = '\0';
  1264. printw(CWD "%s\n\n", cwd);
  1265. /* Print listing */
  1266. odd = ISODD(nlines);
  1267. if (cur < (nlines >> 1)) {
  1268. for (i = 0; i < nlines; i++)
  1269. printptr(&dents[i], i == cur);
  1270. } else if (cur >= ndents - (nlines >> 1)) {
  1271. for (i = ndents - nlines; i < ndents; i++)
  1272. printptr(&dents[i], i == cur);
  1273. } else {
  1274. nlines >>= 1;
  1275. for (i = cur - nlines; i < cur + nlines + odd; i++)
  1276. printptr(&dents[i], i == cur);
  1277. }
  1278. if (showdetail) {
  1279. if (ndents) {
  1280. static char ind[2] = "\0\0";
  1281. static char sort[17];
  1282. if (mtimeorder)
  1283. sprintf(sort, "by time ");
  1284. else if (sizeorder)
  1285. sprintf(sort, "by size ");
  1286. else
  1287. sort[0] = '\0';
  1288. if (S_ISDIR(dents[cur].mode))
  1289. ind[0] = '/';
  1290. else if (S_ISLNK(dents[cur].mode))
  1291. ind[0] = '@';
  1292. else if (S_ISSOCK(dents[cur].mode))
  1293. ind[0] = '=';
  1294. else if (S_ISFIFO(dents[cur].mode))
  1295. ind[0] = '|';
  1296. else if (dents[cur].mode & S_IXUSR)
  1297. ind[0] = '*';
  1298. else
  1299. ind[0] = '\0';
  1300. if (!bsizeorder)
  1301. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  1302. replace_escape(dents[cur].name), ind);
  1303. else
  1304. sprintf(cwd, "total %d by disk usage, %s free [%s%s]",
  1305. ndents, coolsize(fs_free),
  1306. replace_escape(dents[cur].name), ind);
  1307. printmsg(cwd);
  1308. } else
  1309. printmsg("0 items");
  1310. }
  1311. }
  1312. static void
  1313. browse(char *ipath, char *ifilter)
  1314. {
  1315. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1316. static char lastdir[PATH_MAX];
  1317. static char fltr[LINE_MAX];
  1318. char *mime, *dir, *tmp, *run, *env;
  1319. struct stat sb;
  1320. int r, fd, filtered = FALSE;
  1321. enum action sel = SEL_RUNARG + 1;
  1322. xstrlcpy(path, ipath, PATH_MAX);
  1323. xstrlcpy(fltr, ifilter, LINE_MAX);
  1324. oldpath[0] = '\0';
  1325. newpath[0] = '\0';
  1326. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1327. begin:
  1328. if (populate(path, oldpath, fltr) == -1) {
  1329. printwarn();
  1330. goto nochange;
  1331. }
  1332. for (;;) {
  1333. redraw(path);
  1334. nochange:
  1335. /* Exit if parent has exited */
  1336. if (getppid() == 1)
  1337. _exit(0);
  1338. sel = nextsel(&run, &env, &filtered);
  1339. switch (sel) {
  1340. case SEL_CDQUIT:
  1341. {
  1342. char *tmpfile = "/tmp/nnn";
  1343. if ((tmp = getenv("NNN_TMPFILE")) != NULL)
  1344. tmpfile = tmp;
  1345. FILE *fp = fopen(tmpfile, "w");
  1346. if (fp) {
  1347. fprintf(fp, "cd \"%s\"", path);
  1348. fclose(fp);
  1349. }
  1350. }
  1351. case SEL_QUIT:
  1352. dentfree(dents);
  1353. return;
  1354. case SEL_BACK:
  1355. /* There is no going back */
  1356. if (strcmp(path, "/") == 0 ||
  1357. strchr(path, '/') == NULL) {
  1358. printmsg("You are at /");
  1359. goto nochange;
  1360. }
  1361. dir = xdirname(path);
  1362. if (canopendir(dir) == 0) {
  1363. printwarn();
  1364. goto nochange;
  1365. }
  1366. /* Save history */
  1367. xstrlcpy(oldpath, path, PATH_MAX);
  1368. /* Save last working directory */
  1369. xstrlcpy(lastdir, path, PATH_MAX);
  1370. xstrlcpy(path, dir, PATH_MAX);
  1371. /* Reset filter */
  1372. xstrlcpy(fltr, ifilter, LINE_MAX);
  1373. goto begin;
  1374. case SEL_GOIN:
  1375. /* Cannot descend in empty directories */
  1376. if (ndents == 0)
  1377. goto begin;
  1378. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1379. DPRINTF_S(newpath);
  1380. /* Get path info */
  1381. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1382. if (fd == -1) {
  1383. printwarn();
  1384. goto nochange;
  1385. }
  1386. r = fstat(fd, &sb);
  1387. if (r == -1) {
  1388. printwarn();
  1389. close(fd);
  1390. goto nochange;
  1391. }
  1392. close(fd);
  1393. DPRINTF_U(sb.st_mode);
  1394. switch (sb.st_mode & S_IFMT) {
  1395. case S_IFDIR:
  1396. if (canopendir(newpath) == 0) {
  1397. printwarn();
  1398. goto nochange;
  1399. }
  1400. /* Save last working directory */
  1401. xstrlcpy(lastdir, path, PATH_MAX);
  1402. xstrlcpy(path, newpath, PATH_MAX);
  1403. oldpath[0] = '\0';
  1404. /* Reset filter */
  1405. xstrlcpy(fltr, ifilter, LINE_MAX);
  1406. goto begin;
  1407. case S_IFREG:
  1408. {
  1409. /* If NNN_OPENER is set, use it */
  1410. if (opener) {
  1411. spawn(opener, newpath, NULL, NULL, 4);
  1412. continue;
  1413. }
  1414. /* Play with nlay if identified */
  1415. mime = getmime(dents[cur].name);
  1416. if (mime) {
  1417. exitcurses();
  1418. if (player)
  1419. spawn(player, newpath, mime, NULL, 0);
  1420. else
  1421. spawn("nlay", newpath, mime, NULL, 0);
  1422. initcurses();
  1423. continue;
  1424. }
  1425. /* If nlay doesn't handle it, open plain text
  1426. files with vi, then try NNN_FALLBACK_OPENER */
  1427. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi",
  1428. newpath, 0) == NULL)
  1429. continue;
  1430. if (strstr(g_buf, "text/") == g_buf) {
  1431. exitcurses();
  1432. run = xgetenv("EDITOR", "vi");
  1433. spawn(run, newpath, NULL, NULL, 0);
  1434. initcurses();
  1435. continue;
  1436. } else if (fb_opener) {
  1437. spawn(fb_opener, newpath, NULL, NULL, 4);
  1438. continue;
  1439. }
  1440. printmsg("No association");
  1441. goto nochange;
  1442. }
  1443. default:
  1444. printmsg("Unsupported file");
  1445. goto nochange;
  1446. }
  1447. case SEL_FLTR:
  1448. filtered = readln(path);
  1449. xstrlcpy(fltr, ifilter, LINE_MAX);
  1450. DPRINTF_S(fltr);
  1451. /* Save current */
  1452. if (ndents > 0)
  1453. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1454. goto nochange;
  1455. case SEL_SEARCH:
  1456. exitcurses();
  1457. if (player)
  1458. spawn(player, path, "search", NULL, 0);
  1459. else
  1460. spawn("nlay", path, "search", NULL, 0);
  1461. initcurses();
  1462. break;
  1463. case SEL_NEXT:
  1464. if (cur < ndents - 1)
  1465. cur++;
  1466. else if (ndents)
  1467. /* Roll over, set cursor to first entry */
  1468. cur = 0;
  1469. break;
  1470. case SEL_PREV:
  1471. if (cur > 0)
  1472. cur--;
  1473. else if (ndents)
  1474. /* Roll over, set cursor to last entry */
  1475. cur = ndents - 1;
  1476. break;
  1477. case SEL_PGDN:
  1478. if (cur < ndents - 1)
  1479. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1480. break;
  1481. case SEL_PGUP:
  1482. if (cur > 0)
  1483. cur -= MIN((LINES - 4) / 2, cur);
  1484. break;
  1485. case SEL_HOME:
  1486. cur = 0;
  1487. break;
  1488. case SEL_END:
  1489. cur = ndents - 1;
  1490. break;
  1491. case SEL_CD:
  1492. {
  1493. static char *tmp, *input;
  1494. static int truecd;
  1495. /* Save the program start dir */
  1496. tmp = getcwd(newpath, PATH_MAX);
  1497. if (tmp == NULL) {
  1498. printwarn();
  1499. goto nochange;
  1500. }
  1501. /* Switch to current path for readline(3) */
  1502. if (chdir(path) == -1) {
  1503. printwarn();
  1504. goto nochange;
  1505. }
  1506. exitcurses();
  1507. tmp = readline("chdir: ");
  1508. initcurses();
  1509. /* Change back to program start dir */
  1510. if (chdir(newpath) == -1)
  1511. printwarn();
  1512. if (tmp[0] == '\0')
  1513. break;
  1514. else
  1515. /* Add to readline(3) history */
  1516. add_history(tmp);
  1517. input = tmp;
  1518. tmp = strstrip(tmp);
  1519. if (tmp[0] == '\0') {
  1520. free(input);
  1521. break;
  1522. }
  1523. truecd = 0;
  1524. if (tmp[0] == '~') {
  1525. /* Expand ~ to HOME absolute path */
  1526. char *home = getenv("HOME");
  1527. if (home)
  1528. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  1529. else {
  1530. free(input);
  1531. break;
  1532. }
  1533. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1534. if (lastdir[0] == '\0') {
  1535. free(input);
  1536. break;
  1537. }
  1538. /* Switch to last visited dir */
  1539. xstrlcpy(newpath, lastdir, PATH_MAX);
  1540. truecd = 1;
  1541. } else if ((r = all_dots(tmp))) {
  1542. if (r == 1) {
  1543. /* Always in the current dir */
  1544. free(input);
  1545. break;
  1546. }
  1547. r--;
  1548. dir = path;
  1549. for (fd = 0; fd < r; fd++) {
  1550. /* Reached / ? */
  1551. if (strcmp(path, "/") == 0 ||
  1552. strchr(path, '/') == NULL) {
  1553. /* If it's a cd .. at / */
  1554. if (fd == 0) {
  1555. printmsg("You are at /");
  1556. free(input);
  1557. goto nochange;
  1558. }
  1559. /* Can't cd beyond / anyway */
  1560. break;
  1561. } else {
  1562. dir = xdirname(dir);
  1563. if (canopendir(dir) == 0) {
  1564. printwarn();
  1565. free(input);
  1566. goto nochange;
  1567. }
  1568. }
  1569. }
  1570. truecd = 1;
  1571. /* Save the path in case of cd ..
  1572. We mark the current dir in parent dir */
  1573. if (r == 1) {
  1574. xstrlcpy(oldpath, path, PATH_MAX);
  1575. truecd = 2;
  1576. }
  1577. xstrlcpy(newpath, dir, PATH_MAX);
  1578. } else
  1579. mkpath(path, tmp, newpath, PATH_MAX);
  1580. if (canopendir(newpath) == 0) {
  1581. printwarn();
  1582. free(input);
  1583. break;
  1584. }
  1585. if (truecd == 0) {
  1586. /* Probable change in dir */
  1587. /* No-op if it's the same directory */
  1588. if (strcmp(path, newpath) == 0) {
  1589. free(input);
  1590. break;
  1591. }
  1592. oldpath[0] = '\0';
  1593. } else if (truecd == 1)
  1594. /* Sure change in dir */
  1595. oldpath[0] = '\0';
  1596. /* Save last working directory */
  1597. xstrlcpy(lastdir, path, PATH_MAX);
  1598. /* Save the newly opted dir in path */
  1599. xstrlcpy(path, newpath, PATH_MAX);
  1600. /* Reset filter */
  1601. xstrlcpy(fltr, ifilter, LINE_MAX);
  1602. DPRINTF_S(path);
  1603. free(input);
  1604. goto begin;
  1605. }
  1606. case SEL_CDHOME:
  1607. tmp = getenv("HOME");
  1608. if (tmp == NULL) {
  1609. clearprompt();
  1610. goto nochange;
  1611. }
  1612. if (canopendir(tmp) == 0) {
  1613. printwarn();
  1614. goto nochange;
  1615. }
  1616. if (strcmp(path, tmp) == 0)
  1617. break;
  1618. /* Save last working directory */
  1619. xstrlcpy(lastdir, path, PATH_MAX);
  1620. xstrlcpy(path, tmp, PATH_MAX);
  1621. oldpath[0] = '\0';
  1622. /* Reset filter */
  1623. xstrlcpy(fltr, ifilter, LINE_MAX);
  1624. DPRINTF_S(path);
  1625. goto begin;
  1626. case SEL_CDBEGIN:
  1627. if (canopendir(ipath) == 0) {
  1628. printwarn();
  1629. goto nochange;
  1630. }
  1631. if (strcmp(path, ipath) == 0)
  1632. break;
  1633. /* Save last working directory */
  1634. xstrlcpy(lastdir, path, PATH_MAX);
  1635. xstrlcpy(path, ipath, PATH_MAX);
  1636. oldpath[0] = '\0';
  1637. /* Reset filter */
  1638. xstrlcpy(fltr, ifilter, LINE_MAX);
  1639. DPRINTF_S(path);
  1640. goto begin;
  1641. case SEL_CDLAST:
  1642. if (lastdir[0] == '\0')
  1643. break;
  1644. if (canopendir(lastdir) == 0) {
  1645. printwarn();
  1646. goto nochange;
  1647. }
  1648. xstrlcpy(newpath, lastdir, PATH_MAX);
  1649. xstrlcpy(lastdir, path, PATH_MAX);
  1650. xstrlcpy(path, newpath, PATH_MAX);
  1651. oldpath[0] = '\0';
  1652. /* Reset filter */
  1653. xstrlcpy(fltr, ifilter, LINE_MAX);
  1654. DPRINTF_S(path);
  1655. goto begin;
  1656. case SEL_TOGGLEDOT:
  1657. showhidden ^= 1;
  1658. initfilter(showhidden, &ifilter);
  1659. xstrlcpy(fltr, ifilter, LINE_MAX);
  1660. goto begin;
  1661. case SEL_DETAIL:
  1662. showdetail = !showdetail;
  1663. showdetail ? (printptr = &printent_long)
  1664. : (printptr = &printent);
  1665. /* Save current */
  1666. if (ndents > 0)
  1667. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1668. goto begin;
  1669. case SEL_STATS:
  1670. {
  1671. struct stat sb;
  1672. if (ndents > 0) {
  1673. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1674. r = lstat(oldpath, &sb);
  1675. if (r == -1) {
  1676. if (dents)
  1677. dentfree(dents);
  1678. printerr(1, "lstat");
  1679. } else {
  1680. exitcurses();
  1681. r = show_stats(oldpath, dents[cur].name, &sb);
  1682. initcurses();
  1683. if (r < 0) {
  1684. printmsg(strerror(errno));
  1685. goto nochange;
  1686. }
  1687. }
  1688. }
  1689. break;
  1690. }
  1691. case SEL_MEDIA:
  1692. if (ndents > 0) {
  1693. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1694. if(show_mediainfo(oldpath, NULL) == -1) {
  1695. printmsg("mediainfo missing");
  1696. goto nochange;
  1697. }
  1698. }
  1699. break;
  1700. case SEL_FMEDIA:
  1701. if (ndents > 0) {
  1702. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1703. if(show_mediainfo(oldpath, "-f") == -1) {
  1704. printmsg("mediainfo missing");
  1705. goto nochange;
  1706. }
  1707. }
  1708. break;
  1709. case SEL_DFB:
  1710. if (!desktop_manager) {
  1711. printmsg("NNN_DE_FILE_MANAGER not set");
  1712. goto nochange;
  1713. }
  1714. spawn(desktop_manager, path, NULL, path, 2);
  1715. break;
  1716. case SEL_FSIZE:
  1717. sizeorder = !sizeorder;
  1718. mtimeorder = 0;
  1719. bsizeorder = 0;
  1720. /* Save current */
  1721. if (ndents > 0)
  1722. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1723. goto begin;
  1724. case SEL_BSIZE:
  1725. bsizeorder = !bsizeorder;
  1726. if (bsizeorder) {
  1727. showdetail = 1;
  1728. printptr = &printent_long;
  1729. }
  1730. mtimeorder = 0;
  1731. sizeorder = 0;
  1732. /* Save current */
  1733. if (ndents > 0)
  1734. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1735. goto begin;
  1736. case SEL_MTIME:
  1737. mtimeorder = !mtimeorder;
  1738. sizeorder = 0;
  1739. bsizeorder = 0;
  1740. /* Save current */
  1741. if (ndents > 0)
  1742. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1743. goto begin;
  1744. case SEL_REDRAW:
  1745. /* Save current */
  1746. if (ndents > 0)
  1747. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1748. goto begin;
  1749. case SEL_COPY:
  1750. if (copier && ndents) {
  1751. if (strcmp(path, "/") == 0)
  1752. snprintf(newpath, PATH_MAX, "/%s",
  1753. dents[cur].name);
  1754. else
  1755. snprintf(newpath, PATH_MAX, "%s/%s",
  1756. path, dents[cur].name);
  1757. spawn(copier, newpath, NULL, NULL, 0);
  1758. printmsg(newpath);
  1759. } else if (!copier)
  1760. printmsg("NNN_COPIER is not set");
  1761. goto nochange;
  1762. case SEL_HELP:
  1763. exitcurses();
  1764. show_help();
  1765. initcurses();
  1766. break;
  1767. case SEL_RUN:
  1768. run = xgetenv(env, run);
  1769. exitcurses();
  1770. spawn(run, NULL, NULL, path, 1);
  1771. initcurses();
  1772. /* Repopulate as directory content may have changed */
  1773. goto begin;
  1774. case SEL_RUNARG:
  1775. run = xgetenv(env, run);
  1776. exitcurses();
  1777. spawn(run, dents[cur].name, NULL, path, 0);
  1778. initcurses();
  1779. break;
  1780. }
  1781. /* Screensaver */
  1782. if (idletimeout != 0 && idle == idletimeout) {
  1783. idle = 0;
  1784. exitcurses();
  1785. spawn(idlecmd, NULL, NULL, NULL, 0);
  1786. initcurses();
  1787. }
  1788. }
  1789. }
  1790. static void
  1791. usage(void)
  1792. {
  1793. fprintf(stdout, "usage: nnn [-d] [-p custom_nlay] [-S] [-v] [-h] [PATH]\n\n\
  1794. The missing terminal file browser for X.\n\n\
  1795. positional arguments:\n\
  1796. PATH directory to open [default: current dir]\n\n\
  1797. optional arguments:\n\
  1798. -d start in detail view mode\n\
  1799. -p path to custom nlay\n\
  1800. -S start in disk usage analyzer mode\n\
  1801. -v show program version and exit\n\
  1802. -h show this help and exit\n\n\
  1803. Version: %s\n\
  1804. License: BSD 2-Clause\n\
  1805. Webpage: https://github.com/jarun/nnn\n", VERSION);
  1806. exit(0);
  1807. }
  1808. int
  1809. main(int argc, char *argv[])
  1810. {
  1811. char cwd[PATH_MAX], *ipath;
  1812. char *ifilter;
  1813. int opt = 0;
  1814. /* Confirm we are in a terminal */
  1815. if (!isatty(0) || !isatty(1)) {
  1816. fprintf(stderr, "stdin or stdout is not a tty\n");
  1817. exit(1);
  1818. }
  1819. if (argc > 3)
  1820. usage();
  1821. while ((opt = getopt(argc, argv, "dSp:vh")) != -1) {
  1822. switch (opt) {
  1823. case 'S':
  1824. bsizeorder = 1;
  1825. case 'd':
  1826. /* Open in detail mode, if set */
  1827. showdetail = 1;
  1828. printptr = &printent_long;
  1829. break;
  1830. case 'p':
  1831. player = optarg;
  1832. break;
  1833. case 'v':
  1834. fprintf(stdout, "%s\n", VERSION);
  1835. return 0;
  1836. case 'h':
  1837. default:
  1838. usage();
  1839. }
  1840. }
  1841. if (argc == optind) {
  1842. /* Start in the current directory */
  1843. ipath = getcwd(cwd, PATH_MAX);
  1844. if (ipath == NULL)
  1845. ipath = "/";
  1846. } else {
  1847. ipath = realpath(argv[optind], cwd);
  1848. if (!ipath) {
  1849. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1850. exit(1);
  1851. }
  1852. }
  1853. open_max = max_openfds();
  1854. if (getuid() == 0)
  1855. showhidden = 1;
  1856. initfilter(showhidden, &ifilter);
  1857. /* Get the default desktop mime opener, if set */
  1858. opener = getenv("NNN_OPENER");
  1859. /* Get the fallback desktop mime opener, if set */
  1860. fb_opener = getenv("NNN_FALLBACK_OPENER");
  1861. /* Get the desktop file browser, if set */
  1862. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  1863. /* Get the default copier, if set */
  1864. copier = getenv("NNN_COPIER");
  1865. signal(SIGINT, SIG_IGN);
  1866. /* Test initial path */
  1867. if (canopendir(ipath) == 0) {
  1868. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1869. exit(1);
  1870. }
  1871. /* Set locale */
  1872. setlocale(LC_ALL, "");
  1873. initcurses();
  1874. browse(ipath, ifilter);
  1875. exitcurses();
  1876. exit(0);
  1877. }