My build of nnn with minor changes
 
 
 
 
 
 

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