My build of nnn with minor changes
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

2145 líneas
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, unsigned char ch, size_t n)
  193. {
  194. static unsigned char *p;
  195. if (!s || !n)
  196. return NULL;
  197. p = (unsigned char *)s + n - 1;
  198. while (n--)
  199. if ((*p--) == ch)
  200. return ++p;
  201. return NULL;
  202. }
  203. /*
  204. * The following dirname(3) implementation does not
  205. * modify the input. We use a copy of the original.
  206. *
  207. * Modified from the glibc (GNU LGPL) version.
  208. */
  209. static char *
  210. xdirname(const char *path)
  211. {
  212. static char buf[PATH_MAX];
  213. static char *last_slash;
  214. xstrlcpy(buf, path, PATH_MAX);
  215. /* Find last '/'. */
  216. last_slash = strrchr(buf, '/');
  217. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  218. /* Determine whether all remaining characters are slashes. */
  219. char *runp;
  220. for (runp = last_slash; runp != buf; --runp)
  221. if (runp[-1] != '/')
  222. break;
  223. /* The '/' is the last character, we have to look further. */
  224. if (runp != buf)
  225. last_slash = xmemrchr(buf, '/', runp - buf);
  226. }
  227. if (last_slash != NULL) {
  228. /* Determine whether all remaining characters are slashes. */
  229. char *runp;
  230. for (runp = last_slash; runp != buf; --runp)
  231. if (runp[-1] != '/')
  232. break;
  233. /* Terminate the buffer. */
  234. if (runp == buf) {
  235. /* The last slash is the first character in the string.
  236. We have to return "/". As a special case we have to
  237. return "//" if there are exactly two slashes at the
  238. beginning of the string. See XBD 4.10 Path Name
  239. Resolution for more information. */
  240. if (last_slash == buf + 1)
  241. ++last_slash;
  242. else
  243. last_slash = buf + 1;
  244. } else
  245. last_slash = runp;
  246. last_slash[0] = '\0';
  247. } else {
  248. /* This assignment is ill-designed but the XPG specs require to
  249. return a string containing "." in any case no directory part
  250. is found and so a static and constant string is required. */
  251. buf[0] = '.';
  252. buf[1] = '\0';
  253. }
  254. return buf;
  255. }
  256. /*
  257. * Return number of dots of all chars in a string are dots, else 0
  258. */
  259. static int
  260. all_dots(const char* ptr)
  261. {
  262. if (!ptr)
  263. return FALSE;
  264. int count = 0;
  265. while (*ptr == '.') {
  266. count++;
  267. ptr++;
  268. }
  269. if (*ptr)
  270. return 0;
  271. return count;
  272. }
  273. /*
  274. * Spawns a child process. Behaviour can be controlled using flag:
  275. * Limited to 2 arguments to a program
  276. * flag works on bit set:
  277. * - 0b1: draw a marker to indicate nnn spawned e.g., a shell
  278. * - 0b10: do not wait in parent for child process e.g. DE file manager
  279. * - 0b100: suppress stdout and stderr
  280. */
  281. static void
  282. spawn(char *file, char *arg1, char *arg2, char *dir, unsigned char flag)
  283. {
  284. pid_t pid;
  285. int status;
  286. pid = fork();
  287. if (pid == 0) {
  288. if (dir != NULL)
  289. status = chdir(dir);
  290. /* Show a marker (to indicate nnn spawned shell) */
  291. if (flag & 0b1)
  292. fprintf(stdout, "\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  293. /* Suppress stdout and stderr */
  294. if (flag & 0b100) {
  295. int fd = open("/dev/null", O_WRONLY, S_IWUSR);
  296. dup2(fd, 1);
  297. dup2(fd, 2);
  298. close(fd);
  299. }
  300. execlp(file, file, arg1, arg2, NULL);
  301. _exit(1);
  302. } else {
  303. if (!(flag & 0b10))
  304. /* Ignore interruptions */
  305. while (waitpid(pid, &status, 0) == -1)
  306. DPRINTF_D(status);
  307. DPRINTF_D(pid);
  308. }
  309. }
  310. static char *
  311. xgetenv(char *name, char *fallback)
  312. {
  313. char *value;
  314. if (name == NULL)
  315. return fallback;
  316. value = getenv(name);
  317. return value && value[0] ? value : fallback;
  318. }
  319. /*
  320. * We assume none of the strings are NULL.
  321. *
  322. * Let's have the logic to sort numeric names in numeric order.
  323. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  324. *
  325. * If the absolute numeric values are same, we fallback to alphasort.
  326. */
  327. static int
  328. xstricmp(char *s1, char *s2)
  329. {
  330. static char *c1, *c2;
  331. c1 = s1;
  332. while (isspace(*c1))
  333. c1++;
  334. if (*c1 == '-' || *c1 == '+')
  335. c1++;
  336. while (*c1 >= '0' && *c1 <= '9')
  337. c1++;
  338. c2 = s2;
  339. while (isspace(*c2))
  340. c2++;
  341. if (*c2 == '-' || *c2 == '+')
  342. c2++;
  343. while(*c2 >= '0' && *c2 <= '9')
  344. c2++;
  345. if (*c1 == '\0' && *c2 == '\0') {
  346. static long long num1, num2;
  347. num1 = strtoll(s1, &c1, 10);
  348. num2 = strtoll(s2, &c2, 10);
  349. if (num1 != num2) {
  350. if (num1 > num2)
  351. return 1;
  352. else
  353. return -1;
  354. }
  355. } else if (*c1 == '\0' && *c2 != '\0')
  356. return -1;
  357. else if (*c1 != '\0' && *c2 == '\0')
  358. return 1;
  359. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  360. s1++, s2++;
  361. /* In case of alphabetically same names, make sure
  362. lower case one comes before upper case one */
  363. if (!*s1 && !*s2)
  364. return 1;
  365. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  366. }
  367. /* Trim all whitespace from both ends, / from end */
  368. static char *
  369. strstrip(char *s)
  370. {
  371. if (!s || !*s)
  372. return s;
  373. size_t len = strlen(s) - 1;
  374. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  375. len--;
  376. s[len + 1] = '\0';
  377. while (*s && isspace(*s))
  378. s++;
  379. return s;
  380. }
  381. static char *
  382. getmime(char *file)
  383. {
  384. regex_t regex;
  385. unsigned int i;
  386. static unsigned int len = LEN(assocs);
  387. for (i = 0; i < len; i++) {
  388. if (regcomp(&regex, assocs[i].regex,
  389. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  390. continue;
  391. if (regexec(&regex, file, 0, NULL, 0) == 0)
  392. return assocs[i].mime;
  393. }
  394. return NULL;
  395. }
  396. static int
  397. setfilter(regex_t *regex, char *filter)
  398. {
  399. static size_t len;
  400. static int r;
  401. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  402. if (r != 0) {
  403. len = COLS;
  404. if (len > LINE_MAX)
  405. len = LINE_MAX;
  406. regerror(r, regex, g_buf, len);
  407. printmsg(g_buf);
  408. }
  409. return r;
  410. }
  411. static void
  412. initfilter(int dot, char **ifilter)
  413. {
  414. *ifilter = dot ? "." : "^[^.]";
  415. }
  416. static int
  417. visible(regex_t *regex, char *file)
  418. {
  419. return regexec(regex, file, 0, NULL, 0) == 0;
  420. }
  421. static int
  422. entrycmp(const void *va, const void *vb)
  423. {
  424. static pEntry pa, pb;
  425. pa = (pEntry)va;
  426. pb = (pEntry)vb;
  427. /* Sort directories first */
  428. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  429. return 1;
  430. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  431. return -1;
  432. /* Do the actual sorting */
  433. if (mtimeorder)
  434. return pb->t - pa->t;
  435. if (sizeorder) {
  436. if (pb->size > pa->size)
  437. return 1;
  438. else if (pb->size < pa->size)
  439. return -1;
  440. }
  441. if (bsizeorder) {
  442. if (pb->bsize > pa->bsize)
  443. return 1;
  444. else if (pb->bsize < pa->bsize)
  445. return -1;
  446. }
  447. return xstricmp(pa->name, pb->name);
  448. }
  449. static void
  450. initcurses(void)
  451. {
  452. if (initscr() == NULL) {
  453. char *term = getenv("TERM");
  454. if (term != NULL)
  455. fprintf(stderr, "error opening terminal: %s\n", term);
  456. else
  457. fprintf(stderr, "failed to initialize curses\n");
  458. exit(1);
  459. }
  460. cbreak();
  461. noecho();
  462. nonl();
  463. intrflush(stdscr, FALSE);
  464. keypad(stdscr, TRUE);
  465. curs_set(FALSE); /* Hide cursor */
  466. start_color();
  467. use_default_colors();
  468. timeout(1000); /* One second */
  469. }
  470. static void
  471. exitcurses(void)
  472. {
  473. endwin(); /* Restore terminal */
  474. }
  475. /* Messages show up at the bottom */
  476. static void
  477. printmsg(char *msg)
  478. {
  479. move(LINES - 1, 0);
  480. printw("%s\n", msg);
  481. }
  482. /* Display warning as a message */
  483. static void
  484. printwarn(void)
  485. {
  486. printmsg(strerror(errno));
  487. }
  488. /* Kill curses and display error before exiting */
  489. static void
  490. printerr(int ret, char *prefix)
  491. {
  492. exitcurses();
  493. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  494. exit(ret);
  495. }
  496. /* Clear the last line */
  497. static void
  498. clearprompt(void)
  499. {
  500. printmsg("");
  501. }
  502. /* Print prompt on the last line */
  503. static void
  504. printprompt(char *str)
  505. {
  506. clearprompt();
  507. printw(str);
  508. }
  509. /* Returns SEL_* if key is bound and 0 otherwise.
  510. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}) */
  511. static int
  512. nextsel(char **run, char **env, int *ch)
  513. {
  514. int c = *ch;
  515. unsigned int i;
  516. static unsigned int len = LEN(bindings);
  517. if (c == 0)
  518. c = getch();
  519. else
  520. *ch = 0;
  521. if (c == -1)
  522. idle++;
  523. else
  524. idle = 0;
  525. for (i = 0; i < len; i++)
  526. if (c == bindings[i].sym) {
  527. *run = bindings[i].run;
  528. *env = bindings[i].env;
  529. return bindings[i].act;
  530. }
  531. return 0;
  532. }
  533. /*
  534. * Move non-matching entries to the end
  535. */
  536. static void
  537. fill(struct entry **dents,
  538. int (*filter)(regex_t *, char *), regex_t *re)
  539. {
  540. static int count;
  541. for (count = 0; count < ndents; count++) {
  542. if (filter(re, (*dents)[count].name) == 0) {
  543. if (count != --ndents) {
  544. static struct entry _dent;
  545. /* Copy count to tmp */
  546. xstrlcpy(_dent.name, (*dents)[count].name, NAME_MAX);
  547. _dent.mode = (*dents)[count].mode;
  548. _dent.t = (*dents)[count].t;
  549. _dent.size = (*dents)[count].size;
  550. _dent.bsize = (*dents)[count].bsize;
  551. /* Copy ndents - 1 to count */
  552. xstrlcpy((*dents)[count].name, (*dents)[ndents].name, NAME_MAX);
  553. (*dents)[count].mode = (*dents)[ndents].mode;
  554. (*dents)[count].t = (*dents)[ndents].t;
  555. (*dents)[count].size = (*dents)[ndents].size;
  556. (*dents)[count].bsize = (*dents)[ndents].bsize;
  557. /* Copy tmp to ndents - 1 */
  558. xstrlcpy((*dents)[ndents].name, _dent.name, NAME_MAX);
  559. (*dents)[ndents].mode = _dent.mode;
  560. (*dents)[ndents].t = _dent.t;
  561. (*dents)[ndents].size = _dent.size;
  562. (*dents)[ndents].bsize = _dent.bsize;
  563. count--;
  564. }
  565. continue;
  566. }
  567. }
  568. }
  569. static int
  570. matches(char *fltr)
  571. {
  572. static regex_t re;
  573. /* Search filter */
  574. if (setfilter(&re, fltr) != 0)
  575. return -1;
  576. fill(&dents, visible, &re);
  577. qsort(dents, ndents, sizeof(*dents), entrycmp);
  578. return 0;
  579. }
  580. static int
  581. readln(char *path)
  582. {
  583. static char ln[LINE_MAX << 2];
  584. static wchar_t wln[LINE_MAX];
  585. static wint_t ch[2] = {0};
  586. int r, total = ndents;
  587. int oldcur = cur;
  588. int len = 1;
  589. char *pln = ln + 1;
  590. memset(wln, 0, LINE_MAX << 2);
  591. wln[0] = '/';
  592. ln[0] = '/';
  593. ln[1] = '\0';
  594. cur = 0;
  595. timeout(-1);
  596. echo();
  597. curs_set(TRUE);
  598. printprompt(ln);
  599. while ((r = wget_wch(stdscr, ch)) != ERR) {
  600. if (r == OK) {
  601. switch(*ch) {
  602. case '\r': // with nonl(), this is ENTER key value
  603. if (len == 1) {
  604. cur = oldcur;
  605. *ch = CONTROL('L');
  606. goto end;
  607. }
  608. if (matches(pln) == -1)
  609. goto end;
  610. redraw(path);
  611. goto end;
  612. case 127: // handle DEL
  613. if (len == 1) {
  614. cur = oldcur;
  615. *ch = CONTROL('L');
  616. goto end;
  617. }
  618. if (len == 2)
  619. cur = oldcur;
  620. wln[--len] = '\0';
  621. wcstombs(ln, wln, LINE_MAX << 2);
  622. ndents = total;
  623. if (matches(pln) == -1)
  624. continue;
  625. redraw(path);
  626. printprompt(ln);
  627. break;
  628. default:
  629. wln[len++] = (wchar_t)*ch;
  630. wln[len] = '\0';
  631. wcstombs(ln, wln, LINE_MAX << 2);
  632. ndents = total;
  633. if (matches(pln) == -1)
  634. continue;
  635. redraw(path);
  636. printprompt(ln);
  637. }
  638. } else {
  639. switch(*ch) {
  640. case KEY_DC:
  641. case KEY_BACKSPACE:
  642. if (len == 1) {
  643. cur = oldcur;
  644. *ch = CONTROL('L');
  645. goto end;
  646. }
  647. if (len == 2)
  648. cur = oldcur;
  649. wln[--len] = '\0';
  650. wcstombs(ln, wln, LINE_MAX << 2);
  651. ndents = total;
  652. if (matches(pln) == -1)
  653. continue;
  654. redraw(path);
  655. printprompt(ln);
  656. break;
  657. default:
  658. goto end;
  659. }
  660. }
  661. }
  662. end:
  663. noecho();
  664. curs_set(FALSE);
  665. timeout(1000);
  666. return *ch;
  667. }
  668. static int
  669. canopendir(char *path)
  670. {
  671. static DIR *dirp;
  672. dirp = opendir(path);
  673. if (dirp == NULL)
  674. return 0;
  675. closedir(dirp);
  676. return 1;
  677. }
  678. /*
  679. * Returns "dir/name or "/name"
  680. */
  681. static char *
  682. mkpath(char *dir, char *name, char *out, size_t n)
  683. {
  684. /* Handle absolute path */
  685. if (name[0] == '/')
  686. xstrlcpy(out, name, n);
  687. else {
  688. /* Handle root case */
  689. if (strcmp(dir, "/") == 0)
  690. snprintf(out, n, "/%s", name);
  691. else
  692. snprintf(out, n, "%s/%s", dir, name);
  693. }
  694. return out;
  695. }
  696. static char *
  697. replace_escape(const char *str)
  698. {
  699. static char buffer[PATH_MAX];
  700. static wchar_t wbuf[PATH_MAX];
  701. static wchar_t *buf;
  702. buffer[0] = '\0';
  703. buf = wbuf;
  704. /* Convert multi-byte to wide char */
  705. mbstowcs(wbuf, str, PATH_MAX);
  706. while (*buf) {
  707. if (*buf <= '\x1f' || *buf == '\x7f')
  708. *buf = '\?';
  709. buf++;
  710. }
  711. /* Convert wide char to multi-byte */
  712. wcstombs(buffer, wbuf, PATH_MAX);
  713. return buffer;
  714. }
  715. static void
  716. printent(struct entry *ent, int active)
  717. {
  718. static int ncols;
  719. if (COLS > PATH_MAX + 16)
  720. ncols = PATH_MAX + 16;
  721. else
  722. ncols = COLS;
  723. if (S_ISDIR(ent->mode))
  724. snprintf(g_buf, ncols, "%s%s/", CURSYM(active),
  725. replace_escape(ent->name));
  726. else if (S_ISLNK(ent->mode))
  727. snprintf(g_buf, ncols, "%s%s@", CURSYM(active),
  728. replace_escape(ent->name));
  729. else if (S_ISSOCK(ent->mode))
  730. snprintf(g_buf, ncols, "%s%s=", CURSYM(active),
  731. replace_escape(ent->name));
  732. else if (S_ISFIFO(ent->mode))
  733. snprintf(g_buf, ncols, "%s%s|", CURSYM(active),
  734. replace_escape(ent->name));
  735. else if (ent->mode & S_IXUSR)
  736. snprintf(g_buf, ncols, "%s%s*", CURSYM(active),
  737. replace_escape(ent->name));
  738. else
  739. snprintf(g_buf, ncols, "%s%s", CURSYM(active),
  740. replace_escape(ent->name));
  741. printw("%s\n", g_buf);
  742. }
  743. static void (*printptr)(struct entry *ent, int active) = &printent;
  744. static char*
  745. coolsize(off_t size)
  746. {
  747. static const char *size_units[] = {"B", "K", "M", "G", "T", "P", "E", "Z", "Y"};
  748. static char size_buf[12]; /* Buffer to hold human readable size */
  749. static int i;
  750. static off_t tmp;
  751. static long double rem;
  752. i = 0;
  753. rem = 0;
  754. while (size > 1024) {
  755. tmp = size;
  756. size >>= 10;
  757. rem = tmp - (size << 10);
  758. i++;
  759. }
  760. snprintf(size_buf, 12, "%.*Lf%s", i, size + 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 int n;
  1134. n = 0;
  1135. dirp = opendir(path);
  1136. if (dirp == NULL)
  1137. return 0;
  1138. while ((dp = readdir(dirp)) != NULL) {
  1139. /* Skip self and parent */
  1140. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  1141. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  1142. continue;
  1143. if (filter(re, dp->d_name) == 0)
  1144. continue;
  1145. if (n == total_dents) {
  1146. total_dents += 64;
  1147. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1148. if (*dents == NULL)
  1149. printerr(1, "realloc");
  1150. }
  1151. xstrlcpy((*dents)[n].name, dp->d_name, NAME_MAX);
  1152. /* Get mode flags */
  1153. mkpath(path, dp->d_name, newpath, PATH_MAX);
  1154. if (lstat(newpath, &sb) == -1) {
  1155. if (*dents)
  1156. free(*dents);
  1157. printerr(1, "lstat");
  1158. }
  1159. (*dents)[n].mode = sb.st_mode;
  1160. (*dents)[n].t = sb.st_mtime;
  1161. (*dents)[n].size = sb.st_size;
  1162. if (bsizeorder) {
  1163. if (S_ISDIR(sb.st_mode)) {
  1164. blk_size = 0;
  1165. if (nftw(newpath, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1166. printmsg("nftw(3) failed");
  1167. (*dents)[n].bsize = sb.st_blocks;
  1168. } else
  1169. (*dents)[n].bsize = blk_size;
  1170. } else
  1171. (*dents)[n].bsize = sb.st_blocks;
  1172. }
  1173. n++;
  1174. }
  1175. if (bsizeorder) {
  1176. static struct statvfs svb;
  1177. if (statvfs(path, &svb) == -1)
  1178. fs_free = 0;
  1179. else
  1180. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1181. }
  1182. /* Should never be null */
  1183. if (closedir(dirp) == -1) {
  1184. if (*dents)
  1185. free(*dents);
  1186. printerr(1, "closedir");
  1187. }
  1188. return n;
  1189. }
  1190. static void
  1191. dentfree(struct entry *dents)
  1192. {
  1193. free(dents);
  1194. }
  1195. /* Return the position of the matching entry or 0 otherwise */
  1196. static int
  1197. dentfind(struct entry *dents, int n, char *path)
  1198. {
  1199. if (!path)
  1200. return 0;
  1201. static int i;
  1202. static char *p;
  1203. p = basename(path);
  1204. DPRINTF_S(p);
  1205. for (i = 0; i < n; i++)
  1206. if (strcmp(p, dents[i].name) == 0)
  1207. return i;
  1208. return 0;
  1209. }
  1210. static int
  1211. populate(char *path, char *oldpath, char *fltr)
  1212. {
  1213. static regex_t re;
  1214. /* Can fail when permissions change while browsing */
  1215. if (canopendir(path) == 0)
  1216. return -1;
  1217. /* Search filter */
  1218. if (setfilter(&re, fltr) != 0)
  1219. return -1;
  1220. ndents = dentfill(path, &dents, visible, &re);
  1221. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1222. /* Find cur from history */
  1223. cur = dentfind(dents, ndents, oldpath);
  1224. return 0;
  1225. }
  1226. static void
  1227. redraw(char *path)
  1228. {
  1229. static char cwd[PATH_MAX];
  1230. static int nlines, i;
  1231. static size_t ncols;
  1232. nlines = MIN(LINES - 4, ndents);
  1233. /* Clean screen */
  1234. erase();
  1235. /* Strip trailing slashes */
  1236. for (i = strlen(path) - 1; i > 0; i--)
  1237. if (path[i] == '/')
  1238. path[i] = '\0';
  1239. else
  1240. break;
  1241. DPRINTF_D(cur);
  1242. DPRINTF_S(path);
  1243. /* No text wrapping in cwd line */
  1244. if (!realpath(path, cwd)) {
  1245. printmsg("Cannot resolve path");
  1246. return;
  1247. }
  1248. ncols = COLS;
  1249. if (ncols > PATH_MAX)
  1250. ncols = PATH_MAX;
  1251. cwd[ncols - strlen(CWD) - 1] = '\0';
  1252. printw(CWD "%s\n\n", cwd);
  1253. /* Print listing */
  1254. if (cur < (nlines >> 1)) {
  1255. for (i = 0; i < nlines; i++)
  1256. printptr(&dents[i], i == cur);
  1257. } else if (cur >= ndents - (nlines >> 1)) {
  1258. for (i = ndents - nlines; i < ndents; i++)
  1259. printptr(&dents[i], i == cur);
  1260. } else {
  1261. static int odd;
  1262. odd = ISODD(nlines);
  1263. nlines >>= 1;
  1264. for (i = cur - nlines; i < cur + nlines + odd; i++)
  1265. printptr(&dents[i], i == cur);
  1266. }
  1267. if (showdetail) {
  1268. if (ndents) {
  1269. static char ind[2] = "\0\0";
  1270. static char sort[17];
  1271. if (mtimeorder)
  1272. sprintf(sort, "by time ");
  1273. else if (sizeorder)
  1274. sprintf(sort, "by size ");
  1275. else
  1276. sort[0] = '\0';
  1277. if (S_ISDIR(dents[cur].mode))
  1278. ind[0] = '/';
  1279. else if (S_ISLNK(dents[cur].mode))
  1280. ind[0] = '@';
  1281. else if (S_ISSOCK(dents[cur].mode))
  1282. ind[0] = '=';
  1283. else if (S_ISFIFO(dents[cur].mode))
  1284. ind[0] = '|';
  1285. else if (dents[cur].mode & S_IXUSR)
  1286. ind[0] = '*';
  1287. else
  1288. ind[0] = '\0';
  1289. if (!bsizeorder)
  1290. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  1291. replace_escape(dents[cur].name), ind);
  1292. else
  1293. sprintf(cwd, "total %d by disk usage, %s free [%s%s]",
  1294. ndents, coolsize(fs_free),
  1295. replace_escape(dents[cur].name), ind);
  1296. printmsg(cwd);
  1297. } else
  1298. printmsg("0 items");
  1299. }
  1300. }
  1301. static void
  1302. browse(char *ipath, char *ifilter)
  1303. {
  1304. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1305. static char lastdir[PATH_MAX];
  1306. static char fltr[LINE_MAX];
  1307. char *mime, *dir, *tmp, *run, *env;
  1308. struct stat sb;
  1309. int r, fd, filtered = FALSE;
  1310. enum action sel = SEL_RUNARG + 1;
  1311. xstrlcpy(path, ipath, PATH_MAX);
  1312. xstrlcpy(fltr, ifilter, LINE_MAX);
  1313. oldpath[0] = '\0';
  1314. newpath[0] = '\0';
  1315. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1316. begin:
  1317. if (populate(path, oldpath, fltr) == -1) {
  1318. printwarn();
  1319. goto nochange;
  1320. }
  1321. for (;;) {
  1322. redraw(path);
  1323. nochange:
  1324. /* Exit if parent has exited */
  1325. if (getppid() == 1)
  1326. _exit(0);
  1327. sel = nextsel(&run, &env, &filtered);
  1328. switch (sel) {
  1329. case SEL_CDQUIT:
  1330. {
  1331. char *tmpfile = "/tmp/nnn";
  1332. if ((tmp = getenv("NNN_TMPFILE")) != NULL)
  1333. tmpfile = tmp;
  1334. FILE *fp = fopen(tmpfile, "w");
  1335. if (fp) {
  1336. fprintf(fp, "cd \"%s\"", path);
  1337. fclose(fp);
  1338. }
  1339. /* Fall through to exit */
  1340. }
  1341. case SEL_QUIT:
  1342. dentfree(dents);
  1343. return;
  1344. case SEL_BACK:
  1345. /* There is no going back */
  1346. if (path[0] == '/' && path[1] == '\0') {
  1347. printmsg("You are at /");
  1348. goto nochange;
  1349. }
  1350. dir = xdirname(path);
  1351. if (canopendir(dir) == 0) {
  1352. printwarn();
  1353. goto nochange;
  1354. }
  1355. /* Save history */
  1356. xstrlcpy(oldpath, path, PATH_MAX);
  1357. /* Save last working directory */
  1358. xstrlcpy(lastdir, path, PATH_MAX);
  1359. xstrlcpy(path, dir, PATH_MAX);
  1360. /* Reset filter */
  1361. xstrlcpy(fltr, ifilter, LINE_MAX);
  1362. goto begin;
  1363. case SEL_GOIN:
  1364. /* Cannot descend in empty directories */
  1365. if (ndents == 0)
  1366. goto begin;
  1367. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1368. DPRINTF_S(newpath);
  1369. /* Get path info */
  1370. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1371. if (fd == -1) {
  1372. printwarn();
  1373. goto nochange;
  1374. }
  1375. r = fstat(fd, &sb);
  1376. if (r == -1) {
  1377. printwarn();
  1378. close(fd);
  1379. goto nochange;
  1380. }
  1381. close(fd);
  1382. DPRINTF_U(sb.st_mode);
  1383. switch (sb.st_mode & S_IFMT) {
  1384. case S_IFDIR:
  1385. if (canopendir(newpath) == 0) {
  1386. printwarn();
  1387. goto nochange;
  1388. }
  1389. /* Save last working directory */
  1390. xstrlcpy(lastdir, path, PATH_MAX);
  1391. xstrlcpy(path, newpath, PATH_MAX);
  1392. oldpath[0] = '\0';
  1393. /* Reset filter */
  1394. xstrlcpy(fltr, ifilter, LINE_MAX);
  1395. goto begin;
  1396. case S_IFREG:
  1397. {
  1398. /* If NNN_OPENER is set, use it */
  1399. if (opener) {
  1400. spawn(opener, newpath, NULL, NULL, 4);
  1401. continue;
  1402. }
  1403. /* Play with nlay if identified */
  1404. mime = getmime(dents[cur].name);
  1405. if (mime) {
  1406. exitcurses();
  1407. if (player)
  1408. spawn(player, newpath, mime, NULL, 0);
  1409. else
  1410. spawn("nlay", newpath, mime, NULL, 0);
  1411. initcurses();
  1412. continue;
  1413. }
  1414. /* If nlay doesn't handle it, open plain text
  1415. files with vi, then try NNN_FALLBACK_OPENER */
  1416. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi",
  1417. newpath, 0) == NULL)
  1418. continue;
  1419. if (strstr(g_buf, "text/") == g_buf) {
  1420. exitcurses();
  1421. run = xgetenv("EDITOR", "vi");
  1422. spawn(run, newpath, NULL, NULL, 0);
  1423. initcurses();
  1424. continue;
  1425. } else if (fb_opener) {
  1426. spawn(fb_opener, newpath, NULL, NULL, 4);
  1427. continue;
  1428. }
  1429. printmsg("No association");
  1430. goto nochange;
  1431. }
  1432. default:
  1433. printmsg("Unsupported file");
  1434. goto nochange;
  1435. }
  1436. case SEL_FLTR:
  1437. filtered = readln(path);
  1438. xstrlcpy(fltr, ifilter, LINE_MAX);
  1439. DPRINTF_S(fltr);
  1440. /* Save current */
  1441. if (ndents > 0)
  1442. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1443. goto nochange;
  1444. case SEL_SEARCH:
  1445. exitcurses();
  1446. if (player)
  1447. spawn(player, path, "search", NULL, 0);
  1448. else
  1449. spawn("nlay", path, "search", NULL, 0);
  1450. initcurses();
  1451. break;
  1452. case SEL_NEXT:
  1453. if (cur < ndents - 1)
  1454. cur++;
  1455. else if (ndents)
  1456. /* Roll over, set cursor to first entry */
  1457. cur = 0;
  1458. break;
  1459. case SEL_PREV:
  1460. if (cur > 0)
  1461. cur--;
  1462. else if (ndents)
  1463. /* Roll over, set cursor to last entry */
  1464. cur = ndents - 1;
  1465. break;
  1466. case SEL_PGDN:
  1467. if (cur < ndents - 1)
  1468. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1469. break;
  1470. case SEL_PGUP:
  1471. if (cur > 0)
  1472. cur -= MIN((LINES - 4) / 2, cur);
  1473. break;
  1474. case SEL_HOME:
  1475. cur = 0;
  1476. break;
  1477. case SEL_END:
  1478. cur = ndents - 1;
  1479. break;
  1480. case SEL_CD:
  1481. {
  1482. static char *tmp, *input;
  1483. static int truecd;
  1484. /* Save the program start dir */
  1485. tmp = getcwd(newpath, PATH_MAX);
  1486. if (tmp == NULL) {
  1487. printwarn();
  1488. goto nochange;
  1489. }
  1490. /* Switch to current path for readline(3) */
  1491. if (chdir(path) == -1) {
  1492. printwarn();
  1493. goto nochange;
  1494. }
  1495. exitcurses();
  1496. tmp = readline("chdir: ");
  1497. initcurses();
  1498. /* Change back to program start dir */
  1499. if (chdir(newpath) == -1)
  1500. printwarn();
  1501. if (tmp[0] == '\0')
  1502. break;
  1503. else
  1504. /* Add to readline(3) history */
  1505. add_history(tmp);
  1506. input = tmp;
  1507. tmp = strstrip(tmp);
  1508. if (tmp[0] == '\0') {
  1509. free(input);
  1510. break;
  1511. }
  1512. truecd = 0;
  1513. if (tmp[0] == '~') {
  1514. /* Expand ~ to HOME absolute path */
  1515. char *home = getenv("HOME");
  1516. if (home)
  1517. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  1518. else {
  1519. free(input);
  1520. break;
  1521. }
  1522. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1523. if (lastdir[0] == '\0') {
  1524. free(input);
  1525. break;
  1526. }
  1527. /* Switch to last visited dir */
  1528. xstrlcpy(newpath, lastdir, PATH_MAX);
  1529. truecd = 1;
  1530. } else if ((r = all_dots(tmp))) {
  1531. if (r == 1) {
  1532. /* Always in the current dir */
  1533. free(input);
  1534. break;
  1535. }
  1536. r--;
  1537. dir = path;
  1538. for (fd = 0; fd < r; fd++) {
  1539. /* Reached / ? */
  1540. if (strcmp(path, "/") == 0 ||
  1541. strchr(path, '/') == NULL) {
  1542. /* If it's a cd .. at / */
  1543. if (fd == 0) {
  1544. printmsg("You are at /");
  1545. free(input);
  1546. goto nochange;
  1547. }
  1548. /* Can't cd beyond / anyway */
  1549. break;
  1550. } else {
  1551. dir = xdirname(dir);
  1552. if (canopendir(dir) == 0) {
  1553. printwarn();
  1554. free(input);
  1555. goto nochange;
  1556. }
  1557. }
  1558. }
  1559. truecd = 1;
  1560. /* Save the path in case of cd ..
  1561. We mark the current dir in parent dir */
  1562. if (r == 1) {
  1563. xstrlcpy(oldpath, path, PATH_MAX);
  1564. truecd = 2;
  1565. }
  1566. xstrlcpy(newpath, dir, PATH_MAX);
  1567. } else
  1568. mkpath(path, tmp, newpath, PATH_MAX);
  1569. if (canopendir(newpath) == 0) {
  1570. printwarn();
  1571. free(input);
  1572. break;
  1573. }
  1574. if (truecd == 0) {
  1575. /* Probable change in dir */
  1576. /* No-op if it's the same directory */
  1577. if (strcmp(path, newpath) == 0) {
  1578. free(input);
  1579. break;
  1580. }
  1581. oldpath[0] = '\0';
  1582. } else if (truecd == 1)
  1583. /* Sure change in dir */
  1584. oldpath[0] = '\0';
  1585. /* Save last working directory */
  1586. xstrlcpy(lastdir, path, PATH_MAX);
  1587. /* Save the newly opted dir in path */
  1588. xstrlcpy(path, newpath, PATH_MAX);
  1589. /* Reset filter */
  1590. xstrlcpy(fltr, ifilter, LINE_MAX);
  1591. DPRINTF_S(path);
  1592. free(input);
  1593. goto begin;
  1594. }
  1595. case SEL_CDHOME:
  1596. tmp = getenv("HOME");
  1597. if (tmp == NULL) {
  1598. clearprompt();
  1599. goto nochange;
  1600. }
  1601. if (canopendir(tmp) == 0) {
  1602. printwarn();
  1603. goto nochange;
  1604. }
  1605. if (strcmp(path, tmp) == 0)
  1606. break;
  1607. /* Save last working directory */
  1608. xstrlcpy(lastdir, path, PATH_MAX);
  1609. xstrlcpy(path, tmp, PATH_MAX);
  1610. oldpath[0] = '\0';
  1611. /* Reset filter */
  1612. xstrlcpy(fltr, ifilter, LINE_MAX);
  1613. DPRINTF_S(path);
  1614. goto begin;
  1615. case SEL_CDBEGIN:
  1616. if (canopendir(ipath) == 0) {
  1617. printwarn();
  1618. goto nochange;
  1619. }
  1620. if (strcmp(path, ipath) == 0)
  1621. break;
  1622. /* Save last working directory */
  1623. xstrlcpy(lastdir, path, PATH_MAX);
  1624. xstrlcpy(path, ipath, PATH_MAX);
  1625. oldpath[0] = '\0';
  1626. /* Reset filter */
  1627. xstrlcpy(fltr, ifilter, LINE_MAX);
  1628. DPRINTF_S(path);
  1629. goto begin;
  1630. case SEL_CDLAST:
  1631. if (lastdir[0] == '\0')
  1632. break;
  1633. if (canopendir(lastdir) == 0) {
  1634. printwarn();
  1635. goto nochange;
  1636. }
  1637. xstrlcpy(newpath, lastdir, PATH_MAX);
  1638. xstrlcpy(lastdir, path, PATH_MAX);
  1639. xstrlcpy(path, newpath, PATH_MAX);
  1640. oldpath[0] = '\0';
  1641. /* Reset filter */
  1642. xstrlcpy(fltr, ifilter, LINE_MAX);
  1643. DPRINTF_S(path);
  1644. goto begin;
  1645. case SEL_TOGGLEDOT:
  1646. showhidden ^= 1;
  1647. initfilter(showhidden, &ifilter);
  1648. xstrlcpy(fltr, ifilter, LINE_MAX);
  1649. goto begin;
  1650. case SEL_DETAIL:
  1651. showdetail = !showdetail;
  1652. showdetail ? (printptr = &printent_long)
  1653. : (printptr = &printent);
  1654. /* Save current */
  1655. if (ndents > 0)
  1656. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1657. goto begin;
  1658. case SEL_STATS:
  1659. {
  1660. struct stat sb;
  1661. if (ndents > 0) {
  1662. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1663. r = lstat(oldpath, &sb);
  1664. if (r == -1) {
  1665. if (dents)
  1666. dentfree(dents);
  1667. printerr(1, "lstat");
  1668. } else {
  1669. exitcurses();
  1670. r = show_stats(oldpath, dents[cur].name, &sb);
  1671. initcurses();
  1672. if (r < 0) {
  1673. printmsg(strerror(errno));
  1674. goto nochange;
  1675. }
  1676. }
  1677. }
  1678. break;
  1679. }
  1680. case SEL_MEDIA:
  1681. if (ndents > 0) {
  1682. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1683. if(show_mediainfo(oldpath, NULL) == -1) {
  1684. printmsg("mediainfo missing");
  1685. goto nochange;
  1686. }
  1687. }
  1688. break;
  1689. case SEL_FMEDIA:
  1690. if (ndents > 0) {
  1691. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1692. if(show_mediainfo(oldpath, "-f") == -1) {
  1693. printmsg("mediainfo missing");
  1694. goto nochange;
  1695. }
  1696. }
  1697. break;
  1698. case SEL_DFB:
  1699. if (!desktop_manager) {
  1700. printmsg("NNN_DE_FILE_MANAGER not set");
  1701. goto nochange;
  1702. }
  1703. spawn(desktop_manager, path, NULL, path, 2);
  1704. break;
  1705. case SEL_FSIZE:
  1706. sizeorder = !sizeorder;
  1707. mtimeorder = 0;
  1708. bsizeorder = 0;
  1709. /* Save current */
  1710. if (ndents > 0)
  1711. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1712. goto begin;
  1713. case SEL_BSIZE:
  1714. bsizeorder = !bsizeorder;
  1715. if (bsizeorder) {
  1716. showdetail = 1;
  1717. printptr = &printent_long;
  1718. }
  1719. mtimeorder = 0;
  1720. sizeorder = 0;
  1721. /* Save current */
  1722. if (ndents > 0)
  1723. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1724. goto begin;
  1725. case SEL_MTIME:
  1726. mtimeorder = !mtimeorder;
  1727. sizeorder = 0;
  1728. bsizeorder = 0;
  1729. /* Save current */
  1730. if (ndents > 0)
  1731. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1732. goto begin;
  1733. case SEL_REDRAW:
  1734. /* Save current */
  1735. if (ndents > 0)
  1736. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1737. goto begin;
  1738. case SEL_COPY:
  1739. if (copier && ndents) {
  1740. if (strcmp(path, "/") == 0)
  1741. snprintf(newpath, PATH_MAX, "/%s",
  1742. dents[cur].name);
  1743. else
  1744. snprintf(newpath, PATH_MAX, "%s/%s",
  1745. path, dents[cur].name);
  1746. spawn(copier, newpath, NULL, NULL, 0);
  1747. printmsg(newpath);
  1748. } else if (!copier)
  1749. printmsg("NNN_COPIER is not set");
  1750. goto nochange;
  1751. case SEL_HELP:
  1752. exitcurses();
  1753. show_help();
  1754. initcurses();
  1755. break;
  1756. case SEL_RUN:
  1757. run = xgetenv(env, run);
  1758. exitcurses();
  1759. spawn(run, NULL, NULL, path, 1);
  1760. initcurses();
  1761. /* Repopulate as directory content may have changed */
  1762. goto begin;
  1763. case SEL_RUNARG:
  1764. run = xgetenv(env, run);
  1765. exitcurses();
  1766. spawn(run, dents[cur].name, NULL, path, 0);
  1767. initcurses();
  1768. break;
  1769. }
  1770. /* Screensaver */
  1771. if (idletimeout != 0 && idle == idletimeout) {
  1772. idle = 0;
  1773. exitcurses();
  1774. spawn(idlecmd, NULL, NULL, NULL, 0);
  1775. initcurses();
  1776. }
  1777. }
  1778. }
  1779. static void
  1780. usage(void)
  1781. {
  1782. fprintf(stdout, "usage: nnn [-d] [-p custom_nlay] [-S] [-v] [-h] [PATH]\n\n\
  1783. The missing terminal file browser for X.\n\n\
  1784. positional arguments:\n\
  1785. PATH directory to open [default: current dir]\n\n\
  1786. optional arguments:\n\
  1787. -d start in detail view mode\n\
  1788. -p path to custom nlay\n\
  1789. -S start in disk usage analyzer mode\n\
  1790. -v show program version and exit\n\
  1791. -h show this help and exit\n\n\
  1792. Version: %s\n\
  1793. License: BSD 2-Clause\n\
  1794. Webpage: https://github.com/jarun/nnn\n", VERSION);
  1795. exit(0);
  1796. }
  1797. int
  1798. main(int argc, char *argv[])
  1799. {
  1800. char cwd[PATH_MAX], *ipath;
  1801. char *ifilter;
  1802. int opt = 0;
  1803. /* Confirm we are in a terminal */
  1804. if (!isatty(0) || !isatty(1)) {
  1805. fprintf(stderr, "stdin or stdout is not a tty\n");
  1806. exit(1);
  1807. }
  1808. while ((opt = getopt(argc, argv, "dSp:vh")) != -1) {
  1809. switch (opt) {
  1810. case 'S':
  1811. bsizeorder = 1;
  1812. case 'd':
  1813. /* Open in detail mode, if set */
  1814. showdetail = 1;
  1815. printptr = &printent_long;
  1816. break;
  1817. case 'p':
  1818. player = optarg;
  1819. break;
  1820. case 'v':
  1821. fprintf(stdout, "%s\n", VERSION);
  1822. return 0;
  1823. case 'h':
  1824. default:
  1825. usage();
  1826. }
  1827. }
  1828. if (argc == optind) {
  1829. /* Start in the current directory */
  1830. ipath = getcwd(cwd, PATH_MAX);
  1831. if (ipath == NULL)
  1832. ipath = "/";
  1833. } else {
  1834. ipath = realpath(argv[optind], cwd);
  1835. if (!ipath) {
  1836. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1837. exit(1);
  1838. }
  1839. }
  1840. open_max = max_openfds();
  1841. if (getuid() == 0)
  1842. showhidden = 1;
  1843. initfilter(showhidden, &ifilter);
  1844. /* Get the default desktop mime opener, if set */
  1845. opener = getenv("NNN_OPENER");
  1846. /* Get the fallback desktop mime opener, if set */
  1847. fb_opener = getenv("NNN_FALLBACK_OPENER");
  1848. /* Get the desktop file browser, if set */
  1849. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  1850. /* Get the default copier, if set */
  1851. copier = getenv("NNN_COPIER");
  1852. signal(SIGINT, SIG_IGN);
  1853. /* Test initial path */
  1854. if (canopendir(ipath) == 0) {
  1855. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1856. exit(1);
  1857. }
  1858. /* Set locale */
  1859. setlocale(LC_ALL, "");
  1860. initcurses();
  1861. browse(ipath, ifilter);
  1862. exitcurses();
  1863. exit(0);
  1864. }