My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

2095 行
43 KiB

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