My build of nnn with minor changes
 
 
 
 
 
 

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