My build of nnn with minor changes
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

2053 linhas
42 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 > sizeof(errbuf))
  381. len = sizeof(errbuf);
  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. n = 0;
  516. for (count = 0; count < ndents; count++) {
  517. if (filter(re, (*dents)[count].name) == 0)
  518. continue;
  519. if (n != count) {
  520. /* Copy to tmp */
  521. xstrlcpy(_dent.name, (*dents)[n].name, NAME_MAX);
  522. _dent.mode = (*dents)[n].mode;
  523. _dent.t = (*dents)[n].t;
  524. _dent.size = (*dents)[n].size;
  525. _dent.bsize = (*dents)[n].bsize;
  526. /* Copy count to n */
  527. xstrlcpy((*dents)[n].name, (*dents)[count].name, NAME_MAX);
  528. (*dents)[n].mode = (*dents)[count].mode;
  529. (*dents)[n].t = (*dents)[count].t;
  530. (*dents)[n].size = (*dents)[count].size;
  531. (*dents)[n].bsize = (*dents)[count].bsize;
  532. /* Copy tmp to count */
  533. xstrlcpy((*dents)[count].name, _dent.name, NAME_MAX);
  534. (*dents)[count].mode = _dent.mode;
  535. (*dents)[count].t = _dent.t;
  536. (*dents)[count].size = _dent.size;
  537. (*dents)[count].bsize = _dent.bsize;
  538. }
  539. n++;
  540. }
  541. return n;
  542. }
  543. static int
  544. matches(char *fltr)
  545. {
  546. static regex_t re;
  547. /* Search filter */
  548. if (setfilter(&re, fltr) != 0)
  549. return -1;
  550. ndents = fill(&dents, visible, &re);
  551. qsort(dents, ndents, sizeof(*dents), entrycmp);
  552. return 0;
  553. }
  554. static int
  555. readln(char *path)
  556. {
  557. static char ln[LINE_MAX << 2];
  558. static wchar_t wln[LINE_MAX];
  559. static wint_t ch[2] = {0};
  560. int r, total = ndents;
  561. int oldcur = cur;
  562. int len = 1;
  563. char *pln = ln + 1;
  564. memset(wln, 0, LINE_MAX << 2);
  565. wln[0] = '/';
  566. ln[0] = '/';
  567. ln[1] = '\0';
  568. cur = 0;
  569. timeout(-1);
  570. echo();
  571. curs_set(TRUE);
  572. printprompt(ln);
  573. while ((r = wget_wch(stdscr, ch)) != ERR) {
  574. if (r == OK) {
  575. switch(*ch) {
  576. case '\r': // with nonl(), this is ENTER key value
  577. if (len == 1) {
  578. cur = oldcur;
  579. *ch = CONTROL('L');
  580. goto end;
  581. }
  582. if (matches(pln) == -1)
  583. goto end;
  584. redraw(path);
  585. goto end;
  586. case 127: // handle DEL
  587. if (len == 1) {
  588. cur = oldcur;
  589. *ch = CONTROL('L');
  590. goto end;
  591. }
  592. if (len == 2)
  593. cur = oldcur;
  594. wln[--len] = '\0';
  595. wcstombs(ln, wln, LINE_MAX << 2);
  596. ndents = total;
  597. if (matches(pln) == -1)
  598. continue;
  599. redraw(path);
  600. printprompt(ln);
  601. break;
  602. default:
  603. wln[len++] = (wchar_t)*ch;
  604. wln[len] = '\0';
  605. wcstombs(ln, wln, LINE_MAX << 2);
  606. ndents = total;
  607. if (matches(pln) == -1)
  608. continue;
  609. redraw(path);
  610. printprompt(ln);
  611. }
  612. } else if (r == KEY_CODE_YES) {
  613. switch(*ch) {
  614. case KEY_DC:
  615. case KEY_BACKSPACE:
  616. if (len == 1) {
  617. cur = oldcur;
  618. *ch = CONTROL('L');
  619. goto end;
  620. }
  621. if (len == 2)
  622. cur = oldcur;
  623. wln[--len] = '\0';
  624. wcstombs(ln, wln, LINE_MAX << 2);
  625. ndents = total;
  626. if (matches(pln) == -1)
  627. continue;
  628. redraw(path);
  629. printprompt(ln);
  630. break;
  631. default:
  632. goto end;
  633. }
  634. }
  635. }
  636. end:
  637. noecho();
  638. curs_set(FALSE);
  639. timeout(1000);
  640. return *ch;
  641. }
  642. static int
  643. canopendir(char *path)
  644. {
  645. static DIR *dirp;
  646. dirp = opendir(path);
  647. if (dirp == NULL)
  648. return 0;
  649. closedir(dirp);
  650. return 1;
  651. }
  652. /*
  653. * Returns "dir/name or "/name"
  654. */
  655. static char *
  656. mkpath(char *dir, char *name, char *out, size_t n)
  657. {
  658. /* Handle absolute path */
  659. if (name[0] == '/')
  660. xstrlcpy(out, name, n);
  661. else {
  662. /* Handle root case */
  663. if (strcmp(dir, "/") == 0)
  664. snprintf(out, n, "/%s", name);
  665. else
  666. snprintf(out, n, "%s/%s", dir, name);
  667. }
  668. return out;
  669. }
  670. static void
  671. printent(struct entry *ent, int active)
  672. {
  673. static int ncols;
  674. static char str[PATH_MAX + 16];
  675. if (COLS > PATH_MAX + 16)
  676. ncols = PATH_MAX + 16;
  677. else
  678. ncols = COLS;
  679. if (S_ISDIR(ent->mode))
  680. snprintf(str, ncols, "%s%s/", CURSYM(active), ent->name);
  681. else if (S_ISLNK(ent->mode))
  682. snprintf(str, ncols, "%s%s@", CURSYM(active), ent->name);
  683. else if (S_ISSOCK(ent->mode))
  684. snprintf(str, ncols, "%s%s=", CURSYM(active), ent->name);
  685. else if (S_ISFIFO(ent->mode))
  686. snprintf(str, ncols, "%s%s|", CURSYM(active), ent->name);
  687. else if (ent->mode & S_IXUSR)
  688. snprintf(str, ncols, "%s%s*", CURSYM(active), ent->name);
  689. else
  690. snprintf(str, ncols, "%s%s", CURSYM(active), ent->name);
  691. printw("%s\n", str);
  692. }
  693. static void (*printptr)(struct entry *ent, int active) = &printent;
  694. static char*
  695. coolsize(off_t size)
  696. {
  697. static char size_buf[12]; /* Buffer to hold human readable size */
  698. static int i;
  699. static off_t fsize, tmp;
  700. static long double rem;
  701. i = 0;
  702. fsize = size;
  703. rem = 0;
  704. while (fsize > 1024) {
  705. tmp = fsize;
  706. //fsize *= div_2_pow_10;
  707. fsize >>= 10;
  708. rem = tmp - (fsize << 10);
  709. i++;
  710. }
  711. snprintf(size_buf, 12, "%.*Lf%s", i, fsize + rem * div_2_pow_10, size_units[i]);
  712. return size_buf;
  713. }
  714. static void
  715. printent_long(struct entry *ent, int active)
  716. {
  717. static int ncols;
  718. static char str[PATH_MAX + 32];
  719. static char buf[18];
  720. if (COLS > PATH_MAX + 32)
  721. ncols = PATH_MAX + 32;
  722. else
  723. ncols = COLS;
  724. strftime(buf, 18, "%d %m %Y %H:%M", localtime(&ent->t));
  725. if (active)
  726. attron(A_REVERSE);
  727. if (!bsizeorder) {
  728. if (S_ISDIR(ent->mode))
  729. snprintf(str, ncols, "%s%-16.16s / %s/",
  730. CURSYM(active), buf, ent->name);
  731. else if (S_ISLNK(ent->mode))
  732. snprintf(str, ncols, "%s%-16.16s @ %s@",
  733. CURSYM(active), buf, ent->name);
  734. else if (S_ISSOCK(ent->mode))
  735. snprintf(str, ncols, "%s%-16.16s = %s=",
  736. CURSYM(active), buf, ent->name);
  737. else if (S_ISFIFO(ent->mode))
  738. snprintf(str, ncols, "%s%-16.16s | %s|",
  739. CURSYM(active), buf, ent->name);
  740. else if (S_ISBLK(ent->mode))
  741. snprintf(str, ncols, "%s%-16.16s b %s",
  742. CURSYM(active), buf, ent->name);
  743. else if (S_ISCHR(ent->mode))
  744. snprintf(str, ncols, "%s%-16.16s c %s",
  745. CURSYM(active), buf, ent->name);
  746. else if (ent->mode & S_IXUSR)
  747. snprintf(str, ncols, "%s%-16.16s %8.8s* %s*",
  748. CURSYM(active), buf, coolsize(ent->size), ent->name);
  749. else
  750. snprintf(str, ncols, "%s%-16.16s %8.8s %s",
  751. CURSYM(active), buf, coolsize(ent->size), ent->name);
  752. } else {
  753. if (S_ISDIR(ent->mode))
  754. snprintf(str, ncols, "%s%-16.16s %8.8s/ %s/",
  755. CURSYM(active), buf, coolsize(ent->bsize << 9), ent->name);
  756. else if (S_ISLNK(ent->mode))
  757. snprintf(str, ncols, "%s%-16.16s @ %s@",
  758. CURSYM(active), buf, ent->name);
  759. else if (S_ISSOCK(ent->mode))
  760. snprintf(str, ncols, "%s%-16.16s = %s=",
  761. CURSYM(active), buf, ent->name);
  762. else if (S_ISFIFO(ent->mode))
  763. snprintf(str, ncols, "%s%-16.16s | %s|",
  764. CURSYM(active), buf, ent->name);
  765. else if (S_ISBLK(ent->mode))
  766. snprintf(str, ncols, "%s%-16.16s b %s",
  767. CURSYM(active), buf, ent->name);
  768. else if (S_ISCHR(ent->mode))
  769. snprintf(str, ncols, "%s%-16.16s c %s",
  770. CURSYM(active), buf, ent->name);
  771. else if (ent->mode & S_IXUSR)
  772. snprintf(str, ncols, "%s%-16.16s %8.8s* %s*",
  773. CURSYM(active), buf, coolsize(ent->bsize << 9), ent->name);
  774. else
  775. snprintf(str, ncols, "%s%-16.16s %8.8s %s",
  776. CURSYM(active), buf, coolsize(ent->bsize << 9), ent->name);
  777. }
  778. printw("%s\n", str);
  779. if (active)
  780. attroff(A_REVERSE);
  781. }
  782. static char
  783. get_fileind(mode_t mode, char *desc)
  784. {
  785. static char c;
  786. if (S_ISREG(mode)) {
  787. c = '-';
  788. sprintf(desc, "%s", "regular file");
  789. if (mode & S_IXUSR)
  790. strcat(desc, ", executable");
  791. } else if (S_ISDIR(mode)) {
  792. c = 'd';
  793. sprintf(desc, "%s", "directory");
  794. } else if (S_ISBLK(mode)) {
  795. c = 'b';
  796. sprintf(desc, "%s", "block special device");
  797. } else if (S_ISCHR(mode)) {
  798. c = 'c';
  799. sprintf(desc, "%s", "character special device");
  800. #ifdef S_ISFIFO
  801. } else if (S_ISFIFO(mode)) {
  802. c = 'p';
  803. sprintf(desc, "%s", "FIFO");
  804. #endif /* S_ISFIFO */
  805. #ifdef S_ISLNK
  806. } else if (S_ISLNK(mode)) {
  807. c = 'l';
  808. sprintf(desc, "%s", "symbolic link");
  809. #endif /* S_ISLNK */
  810. #ifdef S_ISSOCK
  811. } else if (S_ISSOCK(mode)) {
  812. c = 's';
  813. sprintf(desc, "%s", "socket");
  814. #endif /* S_ISSOCK */
  815. #ifdef S_ISDOOR
  816. /* Solaris 2.6, etc. */
  817. } else if (S_ISDOOR(mode)) {
  818. c = 'D';
  819. desc[0] = '\0';
  820. #endif /* S_ISDOOR */
  821. } else {
  822. /* Unknown type -- possibly a regular file? */
  823. c = '?';
  824. desc[0] = '\0';
  825. }
  826. return(c);
  827. }
  828. /* Convert a mode field into "ls -l" type perms field. */
  829. static char *
  830. get_lsperms(mode_t mode, char *desc)
  831. {
  832. static const char *rwx[] = {"---", "--x", "-w-", "-wx",
  833. "r--", "r-x", "rw-", "rwx"};
  834. static char bits[11];
  835. bits[0] = get_fileind(mode, desc);
  836. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  837. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  838. strcpy(&bits[7], rwx[(mode & 7)]);
  839. if (mode & S_ISUID)
  840. bits[3] = (mode & S_IXUSR) ? 's' : 'S';
  841. if (mode & S_ISGID)
  842. bits[6] = (mode & S_IXGRP) ? 's' : 'l';
  843. if (mode & S_ISVTX)
  844. bits[9] = (mode & S_IXOTH) ? 't' : 'T';
  845. bits[10] = '\0';
  846. return(bits);
  847. }
  848. /* Gets only a single line, that's what we need for now */
  849. static char *
  850. get_output(char *buf, size_t bytes)
  851. {
  852. char *ret;
  853. FILE *pf = popen(buf, "r");
  854. if (pf) {
  855. ret = fgets(buf, bytes, pf);
  856. pclose(pf);
  857. return ret;
  858. }
  859. return NULL;
  860. }
  861. /*
  862. * Follows the stat(1) output closely
  863. */
  864. static int
  865. show_stats(char* fpath, char* fname, struct stat *sb)
  866. {
  867. char buf[PATH_MAX + 16];
  868. char *perms = get_lsperms(sb->st_mode, buf);
  869. char *p, *begin = buf;
  870. char tmp[] = "/tmp/nnnXXXXXX";
  871. int fd = mkstemp(tmp);
  872. if (fd == -1)
  873. return -1;
  874. /* Show file name or 'symlink' -> 'target' */
  875. if (perms[0] == 'l') {
  876. char symtgt[PATH_MAX];
  877. ssize_t len = readlink(fpath, symtgt, PATH_MAX);
  878. if (len != -1) {
  879. symtgt[len] = '\0';
  880. dprintf(fd, " File: '%s' -> '%s'", fname, symtgt);
  881. }
  882. } else
  883. dprintf(fd, " File: '%s'", fname);
  884. /* Show size, blocks, file type */
  885. #ifdef __APPLE__
  886. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  887. #else
  888. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  889. #endif
  890. sb->st_size, sb->st_blocks, sb->st_blksize, buf);
  891. /* Show containing device, inode, hardlink count */
  892. #ifdef __APPLE__
  893. sprintf(buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  894. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  895. #else
  896. sprintf(buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  897. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  898. #endif
  899. buf, sb->st_ino, sb->st_nlink);
  900. /* Show major, minor number for block or char device */
  901. if (perms[0] == 'b' || perms[0] == 'c')
  902. dprintf(fd, " Device type: %x,%x",
  903. major(sb->st_rdev), minor(sb->st_rdev));
  904. /* Show permissions, owner, group */
  905. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)",
  906. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  907. perms,
  908. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  909. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  910. /* Show last access time */
  911. strftime(buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  912. dprintf(fd, "\n\n Access: %s", buf);
  913. /* Show last modification time */
  914. strftime(buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  915. dprintf(fd, "\n Modify: %s", buf);
  916. /* Show last status change time */
  917. strftime(buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  918. dprintf(fd, "\n Change: %s", buf);
  919. if (S_ISREG(sb->st_mode)) {
  920. /* Show file(1) output */
  921. sprintf(buf, "file -b \"%s\" 2>&1", fpath);
  922. p = get_output(buf, PATH_MAX + 16);
  923. if (p) {
  924. dprintf(fd, "\n\n ");
  925. while (*p) {
  926. if (*p == ',') {
  927. *p = '\0';
  928. dprintf(fd, " %s\n", begin);
  929. begin = p + 1;
  930. }
  931. p++;
  932. }
  933. dprintf(fd, " %s", begin);
  934. }
  935. }
  936. dprintf(fd, "\n\n");
  937. close(fd);
  938. sprintf(buf, "cat %s | %s", tmp, xgetenv("PAGER", "less"));
  939. fd = system(buf);
  940. unlink(tmp);
  941. return fd;
  942. }
  943. static int
  944. show_mediainfo(const char* fpath, int full)
  945. {
  946. static char buf[MAX_CMD_LEN];
  947. snprintf(buf, MAX_CMD_LEN, "which mediainfo");
  948. if (get_output(buf, MAX_CMD_LEN) == NULL)
  949. return -1;
  950. if (full)
  951. sprintf(buf, "mediainfo -f \"%s\" 2>&1 | %s", fpath, xgetenv("PAGER", "less"));
  952. else
  953. sprintf(buf, "mediainfo \"%s\" 2>&1 | %s", fpath, xgetenv("PAGER", "less"));
  954. return system(buf);
  955. }
  956. static int
  957. show_help(void)
  958. {
  959. char helpstr[2048] = ("echo \"\
  960. Key | Function\n\
  961. -+-\n\
  962. Up, k, ^P | Previous entry\n\
  963. Down, j, ^N | Next entry\n\
  964. PgUp, ^U | Scroll half page up\n\
  965. PgDn, ^D | Scroll half page down\n\
  966. Home, g, ^, ^A | Jump to first entry\n\
  967. End, G, $, ^E | Jump to last entry\n\
  968. Right, Enter, l, ^M | Open file or enter dir\n\
  969. Left, Bksp, h, ^H | Go to parent dir\n\
  970. ~ | Jump to HOME dir\n\
  971. & | Jump to initial dir\n\
  972. - | Jump to last visited dir\n\
  973. o | Open dir in NNN_DE_FILE_MANAGER\n\
  974. / | Filter dir contents\n\
  975. c | Show change dir prompt\n\
  976. d | Toggle detail view\n\
  977. D | Toggle current file details screen\n\
  978. m | Show concise mediainfo\n\
  979. M | Show full mediainfo\n\
  980. . | Toggle hide .dot files\n\
  981. s | Toggle sort by file size\n\
  982. S | Toggle disk usage analyzer mode\n\
  983. t | Toggle sort by modified time\n\
  984. ! | Spawn SHELL in PWD (fallback sh)\n\
  985. z | Run top\n\
  986. e | Edit entry in EDITOR (fallback vi)\n\
  987. p | Open entry in PAGER (fallback less)\n\
  988. ^K | Invoke file name copier\n\
  989. ^L | Force a redraw\n\
  990. ? | Toggle help screen\n\
  991. q | Quit\n\
  992. Q | Quit and change directory\n\n\" | ");
  993. return system(strcat(helpstr, xgetenv("PAGER", "less")));
  994. }
  995. static int
  996. sum_bsizes(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
  997. {
  998. /* Handle permission problems */
  999. if(typeflag == FTW_NS) {
  1000. printmsg("No stats (permissions ?)");
  1001. return 0;
  1002. }
  1003. blk_size += sb->st_blocks;
  1004. return 0;
  1005. }
  1006. static int
  1007. getorder(size_t size)
  1008. {
  1009. switch (size) {
  1010. case 4096:
  1011. return 12;
  1012. case 512:
  1013. return 9;
  1014. case 8192:
  1015. return 13;
  1016. case 16384:
  1017. return 14;
  1018. case 32768:
  1019. return 15;
  1020. case 65536:
  1021. return 16;
  1022. case 131072:
  1023. return 17;
  1024. case 262144:
  1025. return 18;
  1026. case 524288:
  1027. return 19;
  1028. case 1048576:
  1029. return 20;
  1030. case 2048:
  1031. return 11;
  1032. case 1024:
  1033. return 10;
  1034. default:
  1035. return 0;
  1036. }
  1037. }
  1038. static int
  1039. dentfill(char *path, struct entry **dents,
  1040. int (*filter)(regex_t *, char *), regex_t *re)
  1041. {
  1042. static char newpath[PATH_MAX];
  1043. static DIR *dirp;
  1044. static struct dirent *dp;
  1045. static struct stat sb;
  1046. static struct statvfs svb;
  1047. static int r, n;
  1048. r = n = 0;
  1049. dirp = opendir(path);
  1050. if (dirp == NULL)
  1051. return 0;
  1052. while ((dp = readdir(dirp)) != NULL) {
  1053. /* Skip self and parent */
  1054. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  1055. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  1056. continue;
  1057. if (filter(re, dp->d_name) == 0)
  1058. continue;
  1059. if (n == total_dents) {
  1060. total_dents += 64;
  1061. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1062. if (*dents == NULL)
  1063. printerr(1, "realloc");
  1064. }
  1065. xstrlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  1066. /* Get mode flags */
  1067. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  1068. r = lstat(newpath, &sb);
  1069. if (r == -1) {
  1070. if (*dents)
  1071. free(*dents);
  1072. printerr(1, "lstat");
  1073. }
  1074. (*dents)[n].mode = sb.st_mode;
  1075. (*dents)[n].t = sb.st_mtime;
  1076. (*dents)[n].size = sb.st_size;
  1077. if (bsizeorder) {
  1078. if (S_ISDIR(sb.st_mode)) {
  1079. blk_size = 0;
  1080. if (nftw(newpath, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1081. printmsg("nftw(3) failed");
  1082. (*dents)[n].bsize = sb.st_blocks;
  1083. } else
  1084. (*dents)[n].bsize = blk_size;
  1085. } else
  1086. (*dents)[n].bsize = sb.st_blocks;
  1087. }
  1088. n++;
  1089. }
  1090. if (bsizeorder) {
  1091. r = statvfs(path, &svb);
  1092. if (r == -1)
  1093. fs_free = 0;
  1094. else
  1095. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1096. }
  1097. /* Should never be null */
  1098. r = closedir(dirp);
  1099. if (r == -1) {
  1100. if (*dents)
  1101. free(*dents);
  1102. printerr(1, "closedir");
  1103. }
  1104. return n;
  1105. }
  1106. static void
  1107. dentfree(struct entry *dents)
  1108. {
  1109. free(dents);
  1110. }
  1111. /* Return the position of the matching entry or 0 otherwise */
  1112. static int
  1113. dentfind(struct entry *dents, int n, char *path)
  1114. {
  1115. if (!path)
  1116. return 0;
  1117. static int i;
  1118. static char *p;
  1119. p = xmemrchr(path, '/', strlen(path));
  1120. if (!p)
  1121. p = path;
  1122. else
  1123. /* We are assuming an entry with actual
  1124. name ending in '/' will not appear */
  1125. p++;
  1126. DPRINTF_S(p);
  1127. for (i = 0; i < n; i++)
  1128. if (strcmp(p, dents[i].name) == 0)
  1129. return i;
  1130. return 0;
  1131. }
  1132. static int
  1133. populate(char *path, char *oldpath, char *fltr)
  1134. {
  1135. static regex_t re;
  1136. static int r;
  1137. /* Can fail when permissions change while browsing */
  1138. if (canopendir(path) == 0)
  1139. return -1;
  1140. /* Search filter */
  1141. r = setfilter(&re, fltr);
  1142. if (r != 0)
  1143. return -1;
  1144. ndents = dentfill(path, &dents, visible, &re);
  1145. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1146. /* Find cur from history */
  1147. cur = dentfind(dents, ndents, oldpath);
  1148. return 0;
  1149. }
  1150. static void
  1151. redraw(char *path)
  1152. {
  1153. static char cwd[PATH_MAX];
  1154. static int nlines, odd;
  1155. static int i;
  1156. static size_t ncols;
  1157. nlines = MIN(LINES - 4, ndents);
  1158. /* Clean screen */
  1159. erase();
  1160. /* Strip trailing slashes */
  1161. for (i = strlen(path) - 1; i > 0; i--)
  1162. if (path[i] == '/')
  1163. path[i] = '\0';
  1164. else
  1165. break;
  1166. DPRINTF_D(cur);
  1167. DPRINTF_S(path);
  1168. /* No text wrapping in cwd line */
  1169. if (!realpath(path, cwd)) {
  1170. printmsg("Cannot resolve path");
  1171. return;
  1172. }
  1173. ncols = COLS;
  1174. if (ncols > PATH_MAX)
  1175. ncols = PATH_MAX;
  1176. cwd[ncols - strlen(CWD) - 1] = '\0';
  1177. printw(CWD "%s\n\n", cwd);
  1178. /* Print listing */
  1179. odd = ISODD(nlines);
  1180. if (cur < (nlines >> 1)) {
  1181. for (i = 0; i < nlines; i++)
  1182. printptr(&dents[i], i == cur);
  1183. } else if (cur >= ndents - (nlines >> 1)) {
  1184. for (i = ndents - nlines; i < ndents; i++)
  1185. printptr(&dents[i], i == cur);
  1186. } else {
  1187. nlines >>= 1;
  1188. for (i = cur - nlines; i < cur + nlines + odd; i++)
  1189. printptr(&dents[i], i == cur);
  1190. }
  1191. if (showdetail) {
  1192. if (ndents) {
  1193. static char ind[2] = "\0\0";
  1194. static char sort[17];
  1195. if (mtimeorder)
  1196. sprintf(sort, "by time ");
  1197. else if (sizeorder)
  1198. sprintf(sort, "by size ");
  1199. else
  1200. sort[0] = '\0';
  1201. if (S_ISDIR(dents[cur].mode))
  1202. ind[0] = '/';
  1203. else if (S_ISLNK(dents[cur].mode))
  1204. ind[0] = '@';
  1205. else if (S_ISSOCK(dents[cur].mode))
  1206. ind[0] = '=';
  1207. else if (S_ISFIFO(dents[cur].mode))
  1208. ind[0] = '|';
  1209. else if (dents[cur].mode & S_IXUSR)
  1210. ind[0] = '*';
  1211. else
  1212. ind[0] = '\0';
  1213. if (!bsizeorder)
  1214. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  1215. dents[cur].name, ind);
  1216. else
  1217. sprintf(cwd, "total %d by disk usage, %s free [%s%s]",
  1218. ndents, coolsize(fs_free), dents[cur].name, ind);
  1219. printmsg(cwd);
  1220. } else
  1221. printmsg("0 items");
  1222. }
  1223. }
  1224. static void
  1225. browse(char *ipath, char *ifilter)
  1226. {
  1227. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1228. static char lastdir[PATH_MAX];
  1229. static char fltr[LINE_MAX];
  1230. char *mime, *dir, *tmp, *run, *env;
  1231. struct stat sb;
  1232. int r, fd, filtered = FALSE;
  1233. enum action sel = SEL_RUNARG + 1;
  1234. xstrlcpy(path, ipath, sizeof(path));
  1235. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1236. oldpath[0] = '\0';
  1237. newpath[0] = '\0';
  1238. lastdir[0] = '\0'; /* Can't move back from initial directory */
  1239. begin:
  1240. if (populate(path, oldpath, fltr) == -1) {
  1241. printwarn();
  1242. goto nochange;
  1243. }
  1244. for (;;) {
  1245. redraw(path);
  1246. nochange:
  1247. /* Exit if parent has exited */
  1248. if (getppid() == 1)
  1249. _exit(0);
  1250. sel = nextsel(&run, &env, &filtered);
  1251. switch (sel) {
  1252. case SEL_CDQUIT:
  1253. {
  1254. char *tmpfile = "/tmp/nnn";
  1255. if ((tmp = getenv("NNN_TMPFILE")) != NULL)
  1256. tmpfile = tmp;
  1257. FILE *fp = fopen(tmpfile, "w");
  1258. if (fp) {
  1259. fprintf(fp, "cd \"%s\"", path);
  1260. fclose(fp);
  1261. }
  1262. }
  1263. case SEL_QUIT:
  1264. dentfree(dents);
  1265. return;
  1266. case SEL_BACK:
  1267. /* There is no going back */
  1268. if (strcmp(path, "/") == 0 ||
  1269. strchr(path, '/') == NULL) {
  1270. printmsg("You are at /");
  1271. goto nochange;
  1272. }
  1273. dir = xdirname(path);
  1274. if (canopendir(dir) == 0) {
  1275. printwarn();
  1276. goto nochange;
  1277. }
  1278. /* Save history */
  1279. xstrlcpy(oldpath, path, sizeof(oldpath));
  1280. /* Save last working directory */
  1281. xstrlcpy(lastdir, path, sizeof(lastdir));
  1282. xstrlcpy(path, dir, sizeof(path));
  1283. /* Reset filter */
  1284. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1285. goto begin;
  1286. case SEL_GOIN:
  1287. /* Cannot descend in empty directories */
  1288. if (ndents == 0)
  1289. goto begin;
  1290. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  1291. DPRINTF_S(newpath);
  1292. /* Get path info */
  1293. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1294. if (fd == -1) {
  1295. printwarn();
  1296. goto nochange;
  1297. }
  1298. r = fstat(fd, &sb);
  1299. if (r == -1) {
  1300. printwarn();
  1301. close(fd);
  1302. goto nochange;
  1303. }
  1304. close(fd);
  1305. DPRINTF_U(sb.st_mode);
  1306. switch (sb.st_mode & S_IFMT) {
  1307. case S_IFDIR:
  1308. if (canopendir(newpath) == 0) {
  1309. printwarn();
  1310. goto nochange;
  1311. }
  1312. /* Save last working directory */
  1313. xstrlcpy(lastdir, path, sizeof(lastdir));
  1314. xstrlcpy(path, newpath, sizeof(path));
  1315. oldpath[0] = '\0';
  1316. /* Reset filter */
  1317. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1318. goto begin;
  1319. case S_IFREG:
  1320. {
  1321. static char cmd[MAX_CMD_LEN];
  1322. /* If NNN_OPENER is set, use it */
  1323. if (opener) {
  1324. snprintf(cmd, MAX_CMD_LEN,
  1325. "%s \"%s\" > /dev/null 2>&1",
  1326. opener, newpath);
  1327. r = system(cmd);
  1328. continue;
  1329. }
  1330. /* Play with nlay if identified */
  1331. mime = getmime(dents[cur].name);
  1332. if (mime) {
  1333. snprintf(cmd, MAX_CMD_LEN, "nlay \"%s\" %s",
  1334. newpath, mime);
  1335. exitcurses();
  1336. r = system(cmd);
  1337. initcurses();
  1338. continue;
  1339. }
  1340. /* If nlay doesn't handle it, open plain text
  1341. files with vi, then try NNN_FALLBACK_OPENER */
  1342. snprintf(cmd, MAX_CMD_LEN,
  1343. "file \"%s\"", newpath);
  1344. if (get_output(cmd, MAX_CMD_LEN) == NULL)
  1345. continue;
  1346. if (strstr(cmd, "ASCII text") != NULL) {
  1347. exitcurses();
  1348. run = xgetenv("EDITOR", "vi");
  1349. spawn(run, newpath, NULL, 0);
  1350. initcurses();
  1351. continue;
  1352. } else if (fb_opener) {
  1353. snprintf(cmd, MAX_CMD_LEN, "%s \"%s\" > /dev/null 2>&1",
  1354. fb_opener, newpath);
  1355. r = system(cmd);
  1356. continue;
  1357. }
  1358. printmsg("No association");
  1359. goto nochange;
  1360. }
  1361. default:
  1362. printmsg("Unsupported file");
  1363. goto nochange;
  1364. }
  1365. case SEL_FLTR:
  1366. filtered = readln(path);
  1367. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1368. DPRINTF_S(fltr);
  1369. /* Save current */
  1370. if (ndents > 0)
  1371. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1372. goto nochange;
  1373. case SEL_NEXT:
  1374. if (cur < ndents - 1)
  1375. cur++;
  1376. else if (ndents)
  1377. /* Roll over, set cursor to first entry */
  1378. cur = 0;
  1379. break;
  1380. case SEL_PREV:
  1381. if (cur > 0)
  1382. cur--;
  1383. else if (ndents)
  1384. /* Roll over, set cursor to last entry */
  1385. cur = ndents - 1;
  1386. break;
  1387. case SEL_PGDN:
  1388. if (cur < ndents - 1)
  1389. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1390. break;
  1391. case SEL_PGUP:
  1392. if (cur > 0)
  1393. cur -= MIN((LINES - 4) / 2, cur);
  1394. break;
  1395. case SEL_HOME:
  1396. cur = 0;
  1397. break;
  1398. case SEL_END:
  1399. cur = ndents - 1;
  1400. break;
  1401. case SEL_CD:
  1402. {
  1403. static char *tmp, *input;
  1404. static int truecd;
  1405. /* Save the program start dir */
  1406. tmp = getcwd(newpath, PATH_MAX);
  1407. if (tmp == NULL) {
  1408. printwarn();
  1409. goto nochange;
  1410. }
  1411. /* Switch to current path for readline(3) */
  1412. if (chdir(path) == -1) {
  1413. printwarn();
  1414. goto nochange;
  1415. }
  1416. exitcurses();
  1417. tmp = readline("chdir: ");
  1418. initcurses();
  1419. /* Change back to program start dir */
  1420. if (chdir(newpath) == -1)
  1421. printwarn();
  1422. if (tmp[0] == '\0')
  1423. break;
  1424. else
  1425. /* Add to readline(3) history */
  1426. add_history(tmp);
  1427. input = tmp;
  1428. tmp = strstrip(tmp);
  1429. if (tmp[0] == '\0') {
  1430. free(input);
  1431. break;
  1432. }
  1433. truecd = 0;
  1434. if (tmp[0] == '~') {
  1435. /* Expand ~ to HOME absolute path */
  1436. char *home = getenv("HOME");
  1437. if (home)
  1438. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  1439. else {
  1440. free(input);
  1441. break;
  1442. }
  1443. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1444. if (lastdir[0] == '\0') {
  1445. free(input);
  1446. break;
  1447. }
  1448. /* Switch to last visited dir */
  1449. xstrlcpy(newpath, lastdir, sizeof(newpath));
  1450. truecd = 1;
  1451. } else if ((r = all_dots(tmp))) {
  1452. if (r == 1) {
  1453. /* Always in the current dir */
  1454. free(input);
  1455. break;
  1456. }
  1457. r--;
  1458. dir = path;
  1459. for (fd = 0; fd < r; fd++) {
  1460. /* Reached / ? */
  1461. if (strcmp(path, "/") == 0 ||
  1462. strchr(path, '/') == NULL) {
  1463. /* If it's a cd .. at / */
  1464. if (fd == 0) {
  1465. printmsg("You are at /");
  1466. free(input);
  1467. goto nochange;
  1468. }
  1469. /* Can't cd beyond / anyway */
  1470. break;
  1471. } else {
  1472. dir = xdirname(dir);
  1473. if (canopendir(dir) == 0) {
  1474. printwarn();
  1475. free(input);
  1476. goto nochange;
  1477. }
  1478. }
  1479. }
  1480. truecd = 1;
  1481. /* Save the path in case of cd ..
  1482. We mark the current dir in parent dir */
  1483. if (r == 1) {
  1484. xstrlcpy(oldpath, path, sizeof(oldpath));
  1485. truecd = 2;
  1486. }
  1487. xstrlcpy(newpath, dir, sizeof(newpath));
  1488. } else
  1489. mkpath(path, tmp, newpath, sizeof(newpath));
  1490. if (canopendir(newpath) == 0) {
  1491. printwarn();
  1492. free(input);
  1493. break;
  1494. }
  1495. if (truecd == 0) {
  1496. /* Probable change in dir */
  1497. /* No-op if it's the same directory */
  1498. if (strcmp(path, newpath) == 0) {
  1499. free(input);
  1500. break;
  1501. }
  1502. oldpath[0] = '\0';
  1503. } else if (truecd == 1)
  1504. /* Sure change in dir */
  1505. oldpath[0] = '\0';
  1506. /* Save last working directory */
  1507. xstrlcpy(lastdir, path, sizeof(lastdir));
  1508. /* Save the newly opted dir in path */
  1509. xstrlcpy(path, newpath, sizeof(path));
  1510. /* Reset filter */
  1511. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1512. DPRINTF_S(path);
  1513. free(input);
  1514. goto begin;
  1515. }
  1516. case SEL_CDHOME:
  1517. tmp = getenv("HOME");
  1518. if (tmp == NULL) {
  1519. clearprompt();
  1520. goto nochange;
  1521. }
  1522. if (canopendir(tmp) == 0) {
  1523. printwarn();
  1524. goto nochange;
  1525. }
  1526. if (strcmp(path, tmp) == 0)
  1527. break;
  1528. /* Save last working directory */
  1529. xstrlcpy(lastdir, path, sizeof(lastdir));
  1530. xstrlcpy(path, tmp, sizeof(path));
  1531. oldpath[0] = '\0';
  1532. /* Reset filter */
  1533. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1534. DPRINTF_S(path);
  1535. goto begin;
  1536. case SEL_CDBEGIN:
  1537. if (canopendir(ipath) == 0) {
  1538. printwarn();
  1539. goto nochange;
  1540. }
  1541. if (strcmp(path, ipath) == 0)
  1542. break;
  1543. /* Save last working directory */
  1544. xstrlcpy(lastdir, path, sizeof(lastdir));
  1545. xstrlcpy(path, ipath, sizeof(path));
  1546. oldpath[0] = '\0';
  1547. /* Reset filter */
  1548. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1549. DPRINTF_S(path);
  1550. goto begin;
  1551. case SEL_CDLAST:
  1552. if (lastdir[0] == '\0')
  1553. break;
  1554. if (canopendir(lastdir) == 0) {
  1555. printwarn();
  1556. goto nochange;
  1557. }
  1558. xstrlcpy(newpath, lastdir, sizeof(newpath));
  1559. xstrlcpy(lastdir, path, sizeof(lastdir));
  1560. xstrlcpy(path, newpath, sizeof(path));
  1561. oldpath[0] = '\0';
  1562. /* Reset filter */
  1563. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1564. DPRINTF_S(path);
  1565. goto begin;
  1566. case SEL_TOGGLEDOT:
  1567. showhidden ^= 1;
  1568. initfilter(showhidden, &ifilter);
  1569. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1570. goto begin;
  1571. case SEL_DETAIL:
  1572. showdetail = !showdetail;
  1573. showdetail ? (printptr = &printent_long)
  1574. : (printptr = &printent);
  1575. /* Save current */
  1576. if (ndents > 0)
  1577. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1578. goto begin;
  1579. case SEL_STATS:
  1580. {
  1581. struct stat sb;
  1582. if (ndents > 0)
  1583. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1584. r = lstat(oldpath, &sb);
  1585. if (r == -1) {
  1586. if (dents)
  1587. dentfree(dents);
  1588. printerr(1, "lstat");
  1589. } else {
  1590. exitcurses();
  1591. r = show_stats(oldpath, dents[cur].name, &sb);
  1592. initcurses();
  1593. if (r < 0) {
  1594. printmsg(strerror(errno));
  1595. goto nochange;
  1596. }
  1597. }
  1598. break;
  1599. }
  1600. case SEL_MEDIA:
  1601. if (ndents > 0)
  1602. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1603. exitcurses();
  1604. r = show_mediainfo(oldpath, FALSE);
  1605. initcurses();
  1606. if (r < 0) {
  1607. printmsg("mediainfo missing");
  1608. goto nochange;
  1609. }
  1610. break;
  1611. case SEL_FMEDIA:
  1612. if (ndents > 0)
  1613. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1614. exitcurses();
  1615. r = show_mediainfo(oldpath, TRUE);
  1616. initcurses();
  1617. if (r < 0) {
  1618. printmsg("mediainfo missing");
  1619. goto nochange;
  1620. }
  1621. break;
  1622. case SEL_DFB:
  1623. if (!desktop_manager) {
  1624. printmsg("NNN_DE_FILE_MANAGER not set");
  1625. goto nochange;
  1626. }
  1627. spawn(desktop_manager, path, path, 2);
  1628. break;
  1629. case SEL_FSIZE:
  1630. sizeorder = !sizeorder;
  1631. mtimeorder = 0;
  1632. bsizeorder = 0;
  1633. /* Save current */
  1634. if (ndents > 0)
  1635. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1636. goto begin;
  1637. case SEL_BSIZE:
  1638. bsizeorder = !bsizeorder;
  1639. if (bsizeorder) {
  1640. showdetail = 1;
  1641. printptr = &printent_long;
  1642. }
  1643. mtimeorder = 0;
  1644. sizeorder = 0;
  1645. /* Save current */
  1646. if (ndents > 0)
  1647. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1648. goto begin;
  1649. case SEL_MTIME:
  1650. mtimeorder = !mtimeorder;
  1651. sizeorder = 0;
  1652. bsizeorder = 0;
  1653. /* Save current */
  1654. if (ndents > 0)
  1655. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1656. goto begin;
  1657. case SEL_REDRAW:
  1658. /* Save current */
  1659. if (ndents > 0)
  1660. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1661. goto begin;
  1662. case SEL_COPY:
  1663. if (copier && ndents) {
  1664. if (strcmp(path, "/") == 0)
  1665. snprintf(newpath, PATH_MAX, "/%s",
  1666. dents[cur].name);
  1667. else
  1668. snprintf(newpath, PATH_MAX, "%s/%s",
  1669. path, dents[cur].name);
  1670. spawn(copier, newpath, NULL, 0);
  1671. printmsg(newpath);
  1672. } else if (!copier)
  1673. printmsg("NNN_COPIER is not set");
  1674. goto nochange;
  1675. case SEL_HELP:
  1676. exitcurses();
  1677. show_help();
  1678. initcurses();
  1679. break;
  1680. case SEL_RUN:
  1681. run = xgetenv(env, run);
  1682. exitcurses();
  1683. spawn(run, NULL, path, 1);
  1684. initcurses();
  1685. /* Repopulate as directory content may have changed */
  1686. goto begin;
  1687. case SEL_RUNARG:
  1688. run = xgetenv(env, run);
  1689. exitcurses();
  1690. spawn(run, dents[cur].name, path, 0);
  1691. initcurses();
  1692. break;
  1693. }
  1694. /* Screensaver */
  1695. if (idletimeout != 0 && idle == idletimeout) {
  1696. idle = 0;
  1697. exitcurses();
  1698. spawn(idlecmd, NULL, NULL, 0);
  1699. initcurses();
  1700. }
  1701. }
  1702. }
  1703. static void
  1704. usage(void)
  1705. {
  1706. fprintf(stdout, "usage: nnn [-d] [-S] [-v] [h] [PATH]\n\n\
  1707. The missing terminal file browser for X.\n\n\
  1708. positional arguments:\n\
  1709. PATH directory to open [default: current dir]\n\n\
  1710. optional arguments:\n\
  1711. -d start in detail view mode\n\
  1712. -S start in disk usage analyzer mode\n\
  1713. -v show program version and exit\n\
  1714. -h show this help and exit\n\n\
  1715. Version: %s\n\
  1716. License: BSD 2-Clause\n\
  1717. Webpage: https://github.com/jarun/nnn\n", VERSION);
  1718. exit(0);
  1719. }
  1720. int
  1721. main(int argc, char *argv[])
  1722. {
  1723. char cwd[PATH_MAX], *ipath;
  1724. char *ifilter;
  1725. int opt = 0;
  1726. /* Confirm we are in a terminal */
  1727. if (!isatty(0) || !isatty(1)) {
  1728. fprintf(stderr, "stdin or stdout is not a tty\n");
  1729. exit(1);
  1730. }
  1731. if (argc > 3)
  1732. usage();
  1733. while ((opt = getopt(argc, argv, "dSvh")) != -1) {
  1734. switch (opt) {
  1735. case 'S':
  1736. bsizeorder = 1;
  1737. case 'd':
  1738. /* Open in detail mode, if set */
  1739. showdetail = 1;
  1740. printptr = &printent_long;
  1741. break;
  1742. case 'v':
  1743. fprintf(stdout, "%s\n", VERSION);
  1744. return 0;
  1745. case 'h':
  1746. default:
  1747. usage();
  1748. }
  1749. }
  1750. if (argc == optind) {
  1751. /* Start in the current directory */
  1752. ipath = getcwd(cwd, sizeof(cwd));
  1753. if (ipath == NULL)
  1754. ipath = "/";
  1755. } else {
  1756. ipath = realpath(argv[optind], cwd);
  1757. if (!ipath) {
  1758. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1759. exit(1);
  1760. }
  1761. }
  1762. open_max = max_openfds();
  1763. if (getuid() == 0)
  1764. showhidden = 1;
  1765. initfilter(showhidden, &ifilter);
  1766. /* Get the default desktop mime opener, if set */
  1767. opener = getenv("NNN_OPENER");
  1768. /* Get the fallback desktop mime opener, if set */
  1769. fb_opener = getenv("NNN_FALLBACK_OPENER");
  1770. /* Get the desktop file browser, if set */
  1771. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  1772. /* Get the default copier, if set */
  1773. copier = getenv("NNN_COPIER");
  1774. signal(SIGINT, SIG_IGN);
  1775. /* Test initial path */
  1776. if (canopendir(ipath) == 0) {
  1777. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1778. exit(1);
  1779. }
  1780. /* Set locale */
  1781. setlocale(LC_ALL, "");
  1782. initcurses();
  1783. browse(ipath, ifilter);
  1784. exitcurses();
  1785. exit(0);
  1786. }