My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

2051 行
42 KiB

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