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

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