My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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