My build of nnn with minor changes
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

2199 wiersze
45 KiB

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