My build of nnn with minor changes
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

2089 рядки
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.0"
  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 >= '\x01' && *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. sprintf(buf, "file -b \"%s\" 2>&1", fpath);
  958. p = get_output(buf, PATH_MAX + 16);
  959. if (p) {
  960. dprintf(fd, "\n\n ");
  961. while (*p) {
  962. if (*p == ',') {
  963. *p = '\0';
  964. dprintf(fd, " %s\n", begin);
  965. begin = p + 1;
  966. }
  967. p++;
  968. }
  969. dprintf(fd, " %s", begin);
  970. }
  971. }
  972. dprintf(fd, "\n\n");
  973. close(fd);
  974. sprintf(buf, "cat %s | %s", tmp, xgetenv("PAGER", "less"));
  975. fd = system(buf);
  976. unlink(tmp);
  977. return fd;
  978. }
  979. static int
  980. show_mediainfo(const char* fpath, int full)
  981. {
  982. static char buf[MAX_CMD_LEN];
  983. snprintf(buf, MAX_CMD_LEN, "which mediainfo");
  984. if (get_output(buf, MAX_CMD_LEN) == NULL)
  985. return -1;
  986. if (full)
  987. sprintf(buf, "mediainfo -f \"%s\" 2>&1 | %s", fpath, xgetenv("PAGER", "less"));
  988. else
  989. sprintf(buf, "mediainfo \"%s\" 2>&1 | %s", fpath, xgetenv("PAGER", "less"));
  990. return system(buf);
  991. }
  992. static int
  993. show_help(void)
  994. {
  995. char helpstr[2048] = ("echo \"\
  996. Key | Function\n\
  997. -+-\n\
  998. Up, k, ^P | Previous entry\n\
  999. Down, j, ^N | Next entry\n\
  1000. PgUp, ^U | Scroll half page up\n\
  1001. PgDn, ^D | Scroll half page down\n\
  1002. Home, g, ^, ^A | Jump to first entry\n\
  1003. End, G, $, ^E | Jump to last entry\n\
  1004. Right, Enter, l, ^M | Open file or enter dir\n\
  1005. Left, Bksp, h, ^H | Go to parent dir\n\
  1006. ~ | Jump to HOME dir\n\
  1007. & | Jump to initial dir\n\
  1008. - | Jump to last visited dir\n\
  1009. o | Open dir in NNN_DE_FILE_MANAGER\n\
  1010. / | Filter dir contents\n\
  1011. c | Show change dir prompt\n\
  1012. d | Toggle detail view\n\
  1013. D | Toggle current file details screen\n\
  1014. m | Show concise mediainfo\n\
  1015. M | Show full mediainfo\n\
  1016. . | Toggle hide .dot files\n\
  1017. s | Toggle sort by file size\n\
  1018. S | Toggle disk usage analyzer mode\n\
  1019. t | Toggle sort by modified time\n\
  1020. ! | Spawn SHELL in PWD (fallback sh)\n\
  1021. z | Run top\n\
  1022. e | Edit entry in EDITOR (fallback vi)\n\
  1023. p | Open entry in PAGER (fallback less)\n\
  1024. ^K | Invoke file name copier\n\
  1025. ^L | Force a redraw\n\
  1026. ? | Toggle help screen\n\
  1027. q | Quit\n\
  1028. Q | Quit and change directory\n\n\" | ");
  1029. return system(strcat(helpstr, xgetenv("PAGER", "less")));
  1030. }
  1031. static int
  1032. sum_bsizes(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
  1033. {
  1034. if(typeflag == FTW_F || typeflag == FTW_D)
  1035. blk_size += sb->st_blocks;
  1036. return 0;
  1037. }
  1038. static int
  1039. getorder(size_t size)
  1040. {
  1041. switch (size) {
  1042. case 4096:
  1043. return 12;
  1044. case 512:
  1045. return 9;
  1046. case 8192:
  1047. return 13;
  1048. case 16384:
  1049. return 14;
  1050. case 32768:
  1051. return 15;
  1052. case 65536:
  1053. return 16;
  1054. case 131072:
  1055. return 17;
  1056. case 262144:
  1057. return 18;
  1058. case 524288:
  1059. return 19;
  1060. case 1048576:
  1061. return 20;
  1062. case 2048:
  1063. return 11;
  1064. case 1024:
  1065. return 10;
  1066. default:
  1067. return 0;
  1068. }
  1069. }
  1070. static int
  1071. dentfill(char *path, struct entry **dents,
  1072. int (*filter)(regex_t *, char *), regex_t *re)
  1073. {
  1074. static char newpath[PATH_MAX];
  1075. static DIR *dirp;
  1076. static struct dirent *dp;
  1077. static struct stat sb;
  1078. static struct statvfs svb;
  1079. static int r, n;
  1080. r = n = 0;
  1081. dirp = opendir(path);
  1082. if (dirp == NULL)
  1083. return 0;
  1084. while ((dp = readdir(dirp)) != NULL) {
  1085. /* Skip self and parent */
  1086. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  1087. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  1088. continue;
  1089. if (filter(re, dp->d_name) == 0)
  1090. continue;
  1091. if (n == total_dents) {
  1092. total_dents += 64;
  1093. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1094. if (*dents == NULL)
  1095. printerr(1, "realloc");
  1096. }
  1097. xstrlcpy((*dents)[n].name, dp->d_name, NAME_MAX);
  1098. /* Get mode flags */
  1099. mkpath(path, dp->d_name, newpath, PATH_MAX);
  1100. r = lstat(newpath, &sb);
  1101. if (r == -1) {
  1102. if (*dents)
  1103. free(*dents);
  1104. printerr(1, "lstat");
  1105. }
  1106. (*dents)[n].mode = sb.st_mode;
  1107. (*dents)[n].t = sb.st_mtime;
  1108. (*dents)[n].size = sb.st_size;
  1109. if (bsizeorder) {
  1110. if (S_ISDIR(sb.st_mode)) {
  1111. blk_size = 0;
  1112. if (nftw(newpath, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1113. printmsg("nftw(3) failed");
  1114. (*dents)[n].bsize = sb.st_blocks;
  1115. } else
  1116. (*dents)[n].bsize = blk_size;
  1117. } else
  1118. (*dents)[n].bsize = sb.st_blocks;
  1119. }
  1120. n++;
  1121. }
  1122. if (bsizeorder) {
  1123. r = statvfs(path, &svb);
  1124. if (r == -1)
  1125. fs_free = 0;
  1126. else
  1127. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1128. }
  1129. /* Should never be null */
  1130. r = closedir(dirp);
  1131. if (r == -1) {
  1132. if (*dents)
  1133. free(*dents);
  1134. printerr(1, "closedir");
  1135. }
  1136. return n;
  1137. }
  1138. static void
  1139. dentfree(struct entry *dents)
  1140. {
  1141. free(dents);
  1142. }
  1143. /* Return the position of the matching entry or 0 otherwise */
  1144. static int
  1145. dentfind(struct entry *dents, int n, char *path)
  1146. {
  1147. if (!path)
  1148. return 0;
  1149. static int i;
  1150. static char *p;
  1151. p = xmemrchr(path, '/', strlen(path));
  1152. if (!p)
  1153. p = path;
  1154. else
  1155. /* We are assuming an entry with actual
  1156. name ending in '/' will not appear */
  1157. p++;
  1158. DPRINTF_S(p);
  1159. for (i = 0; i < n; i++)
  1160. if (strcmp(p, dents[i].name) == 0)
  1161. return i;
  1162. return 0;
  1163. }
  1164. static int
  1165. populate(char *path, char *oldpath, char *fltr)
  1166. {
  1167. static regex_t re;
  1168. static int r;
  1169. /* Can fail when permissions change while browsing */
  1170. if (canopendir(path) == 0)
  1171. return -1;
  1172. /* Search filter */
  1173. r = setfilter(&re, fltr);
  1174. if (r != 0)
  1175. return -1;
  1176. ndents = dentfill(path, &dents, visible, &re);
  1177. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1178. /* Find cur from history */
  1179. cur = dentfind(dents, ndents, oldpath);
  1180. return 0;
  1181. }
  1182. static void
  1183. redraw(char *path)
  1184. {
  1185. static char cwd[PATH_MAX];
  1186. static int nlines, odd;
  1187. static int i;
  1188. static size_t ncols;
  1189. nlines = MIN(LINES - 4, ndents);
  1190. /* Clean screen */
  1191. erase();
  1192. /* Strip trailing slashes */
  1193. for (i = strlen(path) - 1; i > 0; i--)
  1194. if (path[i] == '/')
  1195. path[i] = '\0';
  1196. else
  1197. break;
  1198. DPRINTF_D(cur);
  1199. DPRINTF_S(path);
  1200. /* No text wrapping in cwd line */
  1201. if (!realpath(path, cwd)) {
  1202. printmsg("Cannot resolve path");
  1203. return;
  1204. }
  1205. ncols = COLS;
  1206. if (ncols > PATH_MAX)
  1207. ncols = PATH_MAX;
  1208. cwd[ncols - strlen(CWD) - 1] = '\0';
  1209. printw(CWD "%s\n\n", cwd);
  1210. /* Print listing */
  1211. odd = ISODD(nlines);
  1212. if (cur < (nlines >> 1)) {
  1213. for (i = 0; i < nlines; i++)
  1214. printptr(&dents[i], i == cur);
  1215. } else if (cur >= ndents - (nlines >> 1)) {
  1216. for (i = ndents - nlines; i < ndents; i++)
  1217. printptr(&dents[i], i == cur);
  1218. } else {
  1219. nlines >>= 1;
  1220. for (i = cur - nlines; i < cur + nlines + odd; i++)
  1221. printptr(&dents[i], i == cur);
  1222. }
  1223. if (showdetail) {
  1224. if (ndents) {
  1225. static char ind[2] = "\0\0";
  1226. static char sort[17];
  1227. if (mtimeorder)
  1228. sprintf(sort, "by time ");
  1229. else if (sizeorder)
  1230. sprintf(sort, "by size ");
  1231. else
  1232. sort[0] = '\0';
  1233. if (S_ISDIR(dents[cur].mode))
  1234. ind[0] = '/';
  1235. else if (S_ISLNK(dents[cur].mode))
  1236. ind[0] = '@';
  1237. else if (S_ISSOCK(dents[cur].mode))
  1238. ind[0] = '=';
  1239. else if (S_ISFIFO(dents[cur].mode))
  1240. ind[0] = '|';
  1241. else if (dents[cur].mode & S_IXUSR)
  1242. ind[0] = '*';
  1243. else
  1244. ind[0] = '\0';
  1245. if (!bsizeorder)
  1246. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  1247. replace_escape(dents[cur].name), ind);
  1248. else
  1249. sprintf(cwd, "total %d by disk usage, %s free [%s%s]",
  1250. ndents, coolsize(fs_free),
  1251. replace_escape(dents[cur].name), ind);
  1252. printmsg(cwd);
  1253. } else
  1254. printmsg("0 items");
  1255. }
  1256. }
  1257. static void
  1258. browse(char *ipath, char *ifilter)
  1259. {
  1260. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1261. static char lastdir[PATH_MAX];
  1262. static char fltr[LINE_MAX];
  1263. char *mime, *dir, *tmp, *run, *env;
  1264. struct stat sb;
  1265. int r, fd, filtered = FALSE;
  1266. enum action sel = SEL_RUNARG + 1;
  1267. xstrlcpy(path, ipath, PATH_MAX);
  1268. xstrlcpy(fltr, ifilter, LINE_MAX);
  1269. oldpath[0] = '\0';
  1270. newpath[0] = '\0';
  1271. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1272. begin:
  1273. if (populate(path, oldpath, fltr) == -1) {
  1274. printwarn();
  1275. goto nochange;
  1276. }
  1277. for (;;) {
  1278. redraw(path);
  1279. nochange:
  1280. /* Exit if parent has exited */
  1281. if (getppid() == 1)
  1282. _exit(0);
  1283. sel = nextsel(&run, &env, &filtered);
  1284. switch (sel) {
  1285. case SEL_CDQUIT:
  1286. {
  1287. char *tmpfile = "/tmp/nnn";
  1288. if ((tmp = getenv("NNN_TMPFILE")) != NULL)
  1289. tmpfile = tmp;
  1290. FILE *fp = fopen(tmpfile, "w");
  1291. if (fp) {
  1292. fprintf(fp, "cd \"%s\"", path);
  1293. fclose(fp);
  1294. }
  1295. }
  1296. case SEL_QUIT:
  1297. dentfree(dents);
  1298. return;
  1299. case SEL_BACK:
  1300. /* There is no going back */
  1301. if (strcmp(path, "/") == 0 ||
  1302. strchr(path, '/') == NULL) {
  1303. printmsg("You are at /");
  1304. goto nochange;
  1305. }
  1306. dir = xdirname(path);
  1307. if (canopendir(dir) == 0) {
  1308. printwarn();
  1309. goto nochange;
  1310. }
  1311. /* Save history */
  1312. xstrlcpy(oldpath, path, PATH_MAX);
  1313. /* Save last working directory */
  1314. xstrlcpy(lastdir, path, PATH_MAX);
  1315. xstrlcpy(path, dir, PATH_MAX);
  1316. /* Reset filter */
  1317. xstrlcpy(fltr, ifilter, LINE_MAX);
  1318. goto begin;
  1319. case SEL_GOIN:
  1320. /* Cannot descend in empty directories */
  1321. if (ndents == 0)
  1322. goto begin;
  1323. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1324. DPRINTF_S(newpath);
  1325. /* Get path info */
  1326. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1327. if (fd == -1) {
  1328. printwarn();
  1329. goto nochange;
  1330. }
  1331. r = fstat(fd, &sb);
  1332. if (r == -1) {
  1333. printwarn();
  1334. close(fd);
  1335. goto nochange;
  1336. }
  1337. close(fd);
  1338. DPRINTF_U(sb.st_mode);
  1339. switch (sb.st_mode & S_IFMT) {
  1340. case S_IFDIR:
  1341. if (canopendir(newpath) == 0) {
  1342. printwarn();
  1343. goto nochange;
  1344. }
  1345. /* Save last working directory */
  1346. xstrlcpy(lastdir, path, PATH_MAX);
  1347. xstrlcpy(path, newpath, PATH_MAX);
  1348. oldpath[0] = '\0';
  1349. /* Reset filter */
  1350. xstrlcpy(fltr, ifilter, LINE_MAX);
  1351. goto begin;
  1352. case S_IFREG:
  1353. {
  1354. static char cmd[MAX_CMD_LEN];
  1355. /* If NNN_OPENER is set, use it */
  1356. if (opener) {
  1357. snprintf(cmd, MAX_CMD_LEN,
  1358. "%s \"%s\" > /dev/null 2>&1",
  1359. opener, newpath);
  1360. r = system(cmd);
  1361. continue;
  1362. }
  1363. /* Play with nlay if identified */
  1364. mime = getmime(dents[cur].name);
  1365. if (mime) {
  1366. snprintf(cmd, MAX_CMD_LEN, "nlay \"%s\" %s",
  1367. newpath, mime);
  1368. exitcurses();
  1369. r = system(cmd);
  1370. initcurses();
  1371. continue;
  1372. }
  1373. /* If nlay doesn't handle it, open plain text
  1374. files with vi, then try NNN_FALLBACK_OPENER */
  1375. snprintf(cmd, MAX_CMD_LEN,
  1376. "file \"%s\"", newpath);
  1377. if (get_output(cmd, MAX_CMD_LEN) == NULL)
  1378. continue;
  1379. if (strstr(cmd, "ASCII text") != NULL) {
  1380. exitcurses();
  1381. run = xgetenv("EDITOR", "vi");
  1382. spawn(run, newpath, NULL, 0);
  1383. initcurses();
  1384. continue;
  1385. } else if (fb_opener) {
  1386. snprintf(cmd, MAX_CMD_LEN, "%s \"%s\" > /dev/null 2>&1",
  1387. fb_opener, newpath);
  1388. r = system(cmd);
  1389. continue;
  1390. }
  1391. printmsg("No association");
  1392. goto nochange;
  1393. }
  1394. default:
  1395. printmsg("Unsupported file");
  1396. goto nochange;
  1397. }
  1398. case SEL_FLTR:
  1399. filtered = readln(path);
  1400. xstrlcpy(fltr, ifilter, LINE_MAX);
  1401. DPRINTF_S(fltr);
  1402. /* Save current */
  1403. if (ndents > 0)
  1404. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1405. goto nochange;
  1406. case SEL_NEXT:
  1407. if (cur < ndents - 1)
  1408. cur++;
  1409. else if (ndents)
  1410. /* Roll over, set cursor to first entry */
  1411. cur = 0;
  1412. break;
  1413. case SEL_PREV:
  1414. if (cur > 0)
  1415. cur--;
  1416. else if (ndents)
  1417. /* Roll over, set cursor to last entry */
  1418. cur = ndents - 1;
  1419. break;
  1420. case SEL_PGDN:
  1421. if (cur < ndents - 1)
  1422. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1423. break;
  1424. case SEL_PGUP:
  1425. if (cur > 0)
  1426. cur -= MIN((LINES - 4) / 2, cur);
  1427. break;
  1428. case SEL_HOME:
  1429. cur = 0;
  1430. break;
  1431. case SEL_END:
  1432. cur = ndents - 1;
  1433. break;
  1434. case SEL_CD:
  1435. {
  1436. static char *tmp, *input;
  1437. static int truecd;
  1438. /* Save the program start dir */
  1439. tmp = getcwd(newpath, PATH_MAX);
  1440. if (tmp == NULL) {
  1441. printwarn();
  1442. goto nochange;
  1443. }
  1444. /* Switch to current path for readline(3) */
  1445. if (chdir(path) == -1) {
  1446. printwarn();
  1447. goto nochange;
  1448. }
  1449. exitcurses();
  1450. tmp = readline("chdir: ");
  1451. initcurses();
  1452. /* Change back to program start dir */
  1453. if (chdir(newpath) == -1)
  1454. printwarn();
  1455. if (tmp[0] == '\0')
  1456. break;
  1457. else
  1458. /* Add to readline(3) history */
  1459. add_history(tmp);
  1460. input = tmp;
  1461. tmp = strstrip(tmp);
  1462. if (tmp[0] == '\0') {
  1463. free(input);
  1464. break;
  1465. }
  1466. truecd = 0;
  1467. if (tmp[0] == '~') {
  1468. /* Expand ~ to HOME absolute path */
  1469. char *home = getenv("HOME");
  1470. if (home)
  1471. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  1472. else {
  1473. free(input);
  1474. break;
  1475. }
  1476. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1477. if (lastdir[0] == '\0') {
  1478. free(input);
  1479. break;
  1480. }
  1481. /* Switch to last visited dir */
  1482. xstrlcpy(newpath, lastdir, PATH_MAX);
  1483. truecd = 1;
  1484. } else if ((r = all_dots(tmp))) {
  1485. if (r == 1) {
  1486. /* Always in the current dir */
  1487. free(input);
  1488. break;
  1489. }
  1490. r--;
  1491. dir = path;
  1492. for (fd = 0; fd < r; fd++) {
  1493. /* Reached / ? */
  1494. if (strcmp(path, "/") == 0 ||
  1495. strchr(path, '/') == NULL) {
  1496. /* If it's a cd .. at / */
  1497. if (fd == 0) {
  1498. printmsg("You are at /");
  1499. free(input);
  1500. goto nochange;
  1501. }
  1502. /* Can't cd beyond / anyway */
  1503. break;
  1504. } else {
  1505. dir = xdirname(dir);
  1506. if (canopendir(dir) == 0) {
  1507. printwarn();
  1508. free(input);
  1509. goto nochange;
  1510. }
  1511. }
  1512. }
  1513. truecd = 1;
  1514. /* Save the path in case of cd ..
  1515. We mark the current dir in parent dir */
  1516. if (r == 1) {
  1517. xstrlcpy(oldpath, path, PATH_MAX);
  1518. truecd = 2;
  1519. }
  1520. xstrlcpy(newpath, dir, PATH_MAX);
  1521. } else
  1522. mkpath(path, tmp, newpath, PATH_MAX);
  1523. if (canopendir(newpath) == 0) {
  1524. printwarn();
  1525. free(input);
  1526. break;
  1527. }
  1528. if (truecd == 0) {
  1529. /* Probable change in dir */
  1530. /* No-op if it's the same directory */
  1531. if (strcmp(path, newpath) == 0) {
  1532. free(input);
  1533. break;
  1534. }
  1535. oldpath[0] = '\0';
  1536. } else if (truecd == 1)
  1537. /* Sure change in dir */
  1538. oldpath[0] = '\0';
  1539. /* Save last working directory */
  1540. xstrlcpy(lastdir, path, PATH_MAX);
  1541. /* Save the newly opted dir in path */
  1542. xstrlcpy(path, newpath, PATH_MAX);
  1543. /* Reset filter */
  1544. xstrlcpy(fltr, ifilter, LINE_MAX);
  1545. DPRINTF_S(path);
  1546. free(input);
  1547. goto begin;
  1548. }
  1549. case SEL_CDHOME:
  1550. tmp = getenv("HOME");
  1551. if (tmp == NULL) {
  1552. clearprompt();
  1553. goto nochange;
  1554. }
  1555. if (canopendir(tmp) == 0) {
  1556. printwarn();
  1557. goto nochange;
  1558. }
  1559. if (strcmp(path, tmp) == 0)
  1560. break;
  1561. /* Save last working directory */
  1562. xstrlcpy(lastdir, path, PATH_MAX);
  1563. xstrlcpy(path, tmp, PATH_MAX);
  1564. oldpath[0] = '\0';
  1565. /* Reset filter */
  1566. xstrlcpy(fltr, ifilter, LINE_MAX);
  1567. DPRINTF_S(path);
  1568. goto begin;
  1569. case SEL_CDBEGIN:
  1570. if (canopendir(ipath) == 0) {
  1571. printwarn();
  1572. goto nochange;
  1573. }
  1574. if (strcmp(path, ipath) == 0)
  1575. break;
  1576. /* Save last working directory */
  1577. xstrlcpy(lastdir, path, PATH_MAX);
  1578. xstrlcpy(path, ipath, PATH_MAX);
  1579. oldpath[0] = '\0';
  1580. /* Reset filter */
  1581. xstrlcpy(fltr, ifilter, LINE_MAX);
  1582. DPRINTF_S(path);
  1583. goto begin;
  1584. case SEL_CDLAST:
  1585. if (lastdir[0] == '\0')
  1586. break;
  1587. if (canopendir(lastdir) == 0) {
  1588. printwarn();
  1589. goto nochange;
  1590. }
  1591. xstrlcpy(newpath, lastdir, PATH_MAX);
  1592. xstrlcpy(lastdir, path, PATH_MAX);
  1593. xstrlcpy(path, newpath, PATH_MAX);
  1594. oldpath[0] = '\0';
  1595. /* Reset filter */
  1596. xstrlcpy(fltr, ifilter, LINE_MAX);
  1597. DPRINTF_S(path);
  1598. goto begin;
  1599. case SEL_TOGGLEDOT:
  1600. showhidden ^= 1;
  1601. initfilter(showhidden, &ifilter);
  1602. xstrlcpy(fltr, ifilter, LINE_MAX);
  1603. goto begin;
  1604. case SEL_DETAIL:
  1605. showdetail = !showdetail;
  1606. showdetail ? (printptr = &printent_long)
  1607. : (printptr = &printent);
  1608. /* Save current */
  1609. if (ndents > 0)
  1610. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1611. goto begin;
  1612. case SEL_STATS:
  1613. {
  1614. struct stat sb;
  1615. if (ndents > 0)
  1616. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1617. r = lstat(oldpath, &sb);
  1618. if (r == -1) {
  1619. if (dents)
  1620. dentfree(dents);
  1621. printerr(1, "lstat");
  1622. } else {
  1623. exitcurses();
  1624. r = show_stats(oldpath, dents[cur].name, &sb);
  1625. initcurses();
  1626. if (r < 0) {
  1627. printmsg(strerror(errno));
  1628. goto nochange;
  1629. }
  1630. }
  1631. break;
  1632. }
  1633. case SEL_MEDIA:
  1634. if (ndents > 0)
  1635. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1636. exitcurses();
  1637. r = show_mediainfo(oldpath, FALSE);
  1638. initcurses();
  1639. if (r < 0) {
  1640. printmsg("mediainfo missing");
  1641. goto nochange;
  1642. }
  1643. break;
  1644. case SEL_FMEDIA:
  1645. if (ndents > 0)
  1646. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1647. exitcurses();
  1648. r = show_mediainfo(oldpath, TRUE);
  1649. initcurses();
  1650. if (r < 0) {
  1651. printmsg("mediainfo missing");
  1652. goto nochange;
  1653. }
  1654. break;
  1655. case SEL_DFB:
  1656. if (!desktop_manager) {
  1657. printmsg("NNN_DE_FILE_MANAGER not set");
  1658. goto nochange;
  1659. }
  1660. spawn(desktop_manager, path, path, 2);
  1661. break;
  1662. case SEL_FSIZE:
  1663. sizeorder = !sizeorder;
  1664. mtimeorder = 0;
  1665. bsizeorder = 0;
  1666. /* Save current */
  1667. if (ndents > 0)
  1668. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1669. goto begin;
  1670. case SEL_BSIZE:
  1671. bsizeorder = !bsizeorder;
  1672. if (bsizeorder) {
  1673. showdetail = 1;
  1674. printptr = &printent_long;
  1675. }
  1676. mtimeorder = 0;
  1677. sizeorder = 0;
  1678. /* Save current */
  1679. if (ndents > 0)
  1680. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1681. goto begin;
  1682. case SEL_MTIME:
  1683. mtimeorder = !mtimeorder;
  1684. sizeorder = 0;
  1685. bsizeorder = 0;
  1686. /* Save current */
  1687. if (ndents > 0)
  1688. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1689. goto begin;
  1690. case SEL_REDRAW:
  1691. /* Save current */
  1692. if (ndents > 0)
  1693. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1694. goto begin;
  1695. case SEL_COPY:
  1696. if (copier && ndents) {
  1697. if (strcmp(path, "/") == 0)
  1698. snprintf(newpath, PATH_MAX, "/%s",
  1699. dents[cur].name);
  1700. else
  1701. snprintf(newpath, PATH_MAX, "%s/%s",
  1702. path, dents[cur].name);
  1703. spawn(copier, newpath, NULL, 0);
  1704. printmsg(newpath);
  1705. } else if (!copier)
  1706. printmsg("NNN_COPIER is not set");
  1707. goto nochange;
  1708. case SEL_HELP:
  1709. exitcurses();
  1710. show_help();
  1711. initcurses();
  1712. break;
  1713. case SEL_RUN:
  1714. run = xgetenv(env, run);
  1715. exitcurses();
  1716. spawn(run, NULL, path, 1);
  1717. initcurses();
  1718. /* Repopulate as directory content may have changed */
  1719. goto begin;
  1720. case SEL_RUNARG:
  1721. run = xgetenv(env, run);
  1722. exitcurses();
  1723. spawn(run, dents[cur].name, path, 0);
  1724. initcurses();
  1725. break;
  1726. }
  1727. /* Screensaver */
  1728. if (idletimeout != 0 && idle == idletimeout) {
  1729. idle = 0;
  1730. exitcurses();
  1731. spawn(idlecmd, NULL, NULL, 0);
  1732. initcurses();
  1733. }
  1734. }
  1735. }
  1736. static void
  1737. usage(void)
  1738. {
  1739. fprintf(stdout, "usage: nnn [-d] [-S] [-v] [h] [PATH]\n\n\
  1740. The missing terminal file browser for X.\n\n\
  1741. positional arguments:\n\
  1742. PATH directory to open [default: current dir]\n\n\
  1743. optional arguments:\n\
  1744. -d start in detail view mode\n\
  1745. -S start in disk usage analyzer mode\n\
  1746. -v show program version and exit\n\
  1747. -h show this help and exit\n\n\
  1748. Version: %s\n\
  1749. License: BSD 2-Clause\n\
  1750. Webpage: https://github.com/jarun/nnn\n", VERSION);
  1751. exit(0);
  1752. }
  1753. int
  1754. main(int argc, char *argv[])
  1755. {
  1756. char cwd[PATH_MAX], *ipath;
  1757. char *ifilter;
  1758. int opt = 0;
  1759. /* Confirm we are in a terminal */
  1760. if (!isatty(0) || !isatty(1)) {
  1761. fprintf(stderr, "stdin or stdout is not a tty\n");
  1762. exit(1);
  1763. }
  1764. if (argc > 3)
  1765. usage();
  1766. while ((opt = getopt(argc, argv, "dSvh")) != -1) {
  1767. switch (opt) {
  1768. case 'S':
  1769. bsizeorder = 1;
  1770. case 'd':
  1771. /* Open in detail mode, if set */
  1772. showdetail = 1;
  1773. printptr = &printent_long;
  1774. break;
  1775. case 'v':
  1776. fprintf(stdout, "%s\n", VERSION);
  1777. return 0;
  1778. case 'h':
  1779. default:
  1780. usage();
  1781. }
  1782. }
  1783. if (argc == optind) {
  1784. /* Start in the current directory */
  1785. ipath = getcwd(cwd, PATH_MAX);
  1786. if (ipath == NULL)
  1787. ipath = "/";
  1788. } else {
  1789. ipath = realpath(argv[optind], cwd);
  1790. if (!ipath) {
  1791. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1792. exit(1);
  1793. }
  1794. }
  1795. open_max = max_openfds();
  1796. if (getuid() == 0)
  1797. showhidden = 1;
  1798. initfilter(showhidden, &ifilter);
  1799. /* Get the default desktop mime opener, if set */
  1800. opener = getenv("NNN_OPENER");
  1801. /* Get the fallback desktop mime opener, if set */
  1802. fb_opener = getenv("NNN_FALLBACK_OPENER");
  1803. /* Get the desktop file browser, if set */
  1804. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  1805. /* Get the default copier, if set */
  1806. copier = getenv("NNN_COPIER");
  1807. signal(SIGINT, SIG_IGN);
  1808. /* Test initial path */
  1809. if (canopendir(ipath) == 0) {
  1810. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1811. exit(1);
  1812. }
  1813. /* Set locale */
  1814. setlocale(LC_ALL, "");
  1815. initcurses();
  1816. browse(ipath, ifilter);
  1817. exitcurses();
  1818. exit(0);
  1819. }