My build of nnn with minor changes
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

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