My build of nnn with minor changes
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

2139 Zeilen
44 KiB

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