My build of nnn with minor changes
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 
 

2100 rindas
43 KiB

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