My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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