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

2095 строки
43 KiB

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