My build of nnn with minor changes
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

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