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

1805 行
38 KiB

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