My build of nnn with minor changes
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

2109 řádky
44 KiB

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