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.
 
 
 
 
 
 

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