My build of nnn with minor changes
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

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