My build of nnn with minor changes
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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