My build of nnn with minor changes
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

1828 рядки
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 void
  817. show_help(void)
  818. {
  819. char c;
  820. clear();
  821. scrollok(stdscr, TRUE);
  822. printw("\
  823. << Key >> << Function >>\n\n\
  824. [Up], k, ^P Previous entry\n\
  825. [Down], j, ^N Next entry\n\
  826. [PgUp], ^U Scroll half page up\n\
  827. [PgDn], ^D Scroll half page down\n\
  828. [Home], g, ^, ^A Jump to first entry\n\
  829. [End], G, $, ^E Jump to last entry\n\
  830. [Right], [Enter], l, ^M Open file or enter dir\n\
  831. [Left], [Backspace], h, ^H Go to parent dir\n\
  832. ~ Jump to HOME dir\n\
  833. - Jump to last visited dir\n\
  834. o Open dir in NNN_DE_FILE_MANAGER\n\
  835. /, & Filter dir contents\n\
  836. c Show change dir prompt\n\
  837. d Toggle detail view\n\
  838. D Toggle current file details screen\n\
  839. m Show concise mediainfo in less\n\
  840. M Show full mediainfo in less\n\
  841. . Toggle hide .dot files\n\
  842. s Toggle sort by file size\n\
  843. S Toggle disk usage analyzer mode\n\
  844. t Toggle sort by modified time\n\
  845. ! Spawn SHELL in PWD (fallback sh)\n\
  846. z Run top\n\
  847. e Edit entry in EDITOR (fallback vi)\n\
  848. p Open entry in PAGER (fallback less)\n\
  849. ^K Invoke file name copier\n\
  850. ^L Force a redraw\n\
  851. ? Toggle help screen\n\
  852. q Quit\n\
  853. Q Quit and change directory\n");
  854. /* Show exit keys */
  855. printw("\n << (?/q)");
  856. while ((c = getch()))
  857. if (c == '?' || c == 'q')
  858. break;
  859. scrollok(stdscr, FALSE);
  860. return;
  861. }
  862. static int
  863. sum_bsizes(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
  864. {
  865. /* Handle permission problems */
  866. if(typeflag == FTW_NS) {
  867. printmsg("No stats (permissions ?)");
  868. return 0;
  869. }
  870. blk_size += sb->st_blocks;
  871. return 0;
  872. }
  873. static int
  874. getorder(size_t size)
  875. {
  876. switch (size) {
  877. case 4096:
  878. return 12;
  879. case 512:
  880. return 9;
  881. case 8192:
  882. return 13;
  883. case 16384:
  884. return 14;
  885. case 32768:
  886. return 15;
  887. case 65536:
  888. return 16;
  889. case 131072:
  890. return 17;
  891. case 262144:
  892. return 18;
  893. case 524288:
  894. return 19;
  895. case 1048576:
  896. return 20;
  897. case 2048:
  898. return 11;
  899. case 1024:
  900. return 10;
  901. default:
  902. return 0;
  903. }
  904. }
  905. static int
  906. dentfill(char *path, struct entry **dents,
  907. int (*filter)(regex_t *, char *), regex_t *re)
  908. {
  909. static char newpath[PATH_MAX];
  910. static DIR *dirp;
  911. static struct dirent *dp;
  912. static struct stat sb;
  913. static struct statvfs svb;
  914. static int r, n;
  915. r = n = 0;
  916. dirp = opendir(path);
  917. if (dirp == NULL)
  918. return 0;
  919. while ((dp = readdir(dirp)) != NULL) {
  920. /* Skip self and parent */
  921. if ((dp->d_name[0] == '.' && (dp->d_name[1] == '\0' ||
  922. (dp->d_name[1] == '.' && dp->d_name[2] == '\0'))))
  923. continue;
  924. if (filter(re, dp->d_name) == 0)
  925. continue;
  926. if (n == total_dents) {
  927. total_dents += 64;
  928. *dents = realloc(*dents, total_dents * sizeof(**dents));
  929. if (*dents == NULL)
  930. printerr(1, "realloc");
  931. }
  932. xstrlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  933. /* Get mode flags */
  934. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  935. r = lstat(newpath, &sb);
  936. if (r == -1) {
  937. if (*dents)
  938. free(*dents);
  939. printerr(1, "lstat");
  940. }
  941. (*dents)[n].mode = sb.st_mode;
  942. (*dents)[n].t = sb.st_mtime;
  943. (*dents)[n].size = sb.st_size;
  944. if (bsizeorder) {
  945. if (S_ISDIR(sb.st_mode)) {
  946. blk_size = 0;
  947. if (nftw(newpath, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  948. printmsg("nftw(3) failed");
  949. (*dents)[n].bsize = sb.st_blocks;
  950. } else
  951. (*dents)[n].bsize = blk_size;
  952. } else
  953. (*dents)[n].bsize = sb.st_blocks;
  954. }
  955. n++;
  956. }
  957. if (bsizeorder) {
  958. r = statvfs(path, &svb);
  959. if (r == -1)
  960. fs_free = 0;
  961. else
  962. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  963. }
  964. /* Should never be null */
  965. r = closedir(dirp);
  966. if (r == -1) {
  967. if (*dents)
  968. free(*dents);
  969. printerr(1, "closedir");
  970. }
  971. return n;
  972. }
  973. static void
  974. dentfree(struct entry *dents)
  975. {
  976. free(dents);
  977. }
  978. /* Return the position of the matching entry or 0 otherwise */
  979. static int
  980. dentfind(struct entry *dents, int n, char *path)
  981. {
  982. if (!path)
  983. return 0;
  984. static int i;
  985. static char *p;
  986. p = xmemrchr(path, '/', strlen(path));
  987. if (!p)
  988. p = path;
  989. else
  990. /* We are assuming an entry with actual
  991. name ending in '/' will not appear */
  992. p++;
  993. DPRINTF_S(p);
  994. for (i = 0; i < n; i++)
  995. if (strcmp(p, dents[i].name) == 0)
  996. return i;
  997. return 0;
  998. }
  999. static int
  1000. populate(char *path, char *oldpath, char *fltr)
  1001. {
  1002. static regex_t re;
  1003. static int r;
  1004. /* Can fail when permissions change while browsing */
  1005. if (canopendir(path) == 0)
  1006. return -1;
  1007. /* Search filter */
  1008. r = setfilter(&re, fltr);
  1009. if (r != 0)
  1010. return -1;
  1011. ndents = dentfill(path, &dents, visible, &re);
  1012. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1013. /* Find cur from history */
  1014. cur = dentfind(dents, ndents, oldpath);
  1015. return 0;
  1016. }
  1017. static void
  1018. redraw(char *path)
  1019. {
  1020. static char cwd[PATH_MAX];
  1021. static int nlines, odd;
  1022. static int i;
  1023. static size_t ncols;
  1024. nlines = MIN(LINES - 4, ndents);
  1025. /* Clean screen */
  1026. erase();
  1027. /* Strip trailing slashes */
  1028. for (i = strlen(path) - 1; i > 0; i--)
  1029. if (path[i] == '/')
  1030. path[i] = '\0';
  1031. else
  1032. break;
  1033. DPRINTF_D(cur);
  1034. DPRINTF_S(path);
  1035. /* No text wrapping in cwd line */
  1036. if (!realpath(path, cwd)) {
  1037. printmsg("Cannot resolve path");
  1038. return;
  1039. }
  1040. ncols = COLS;
  1041. if (ncols > PATH_MAX)
  1042. ncols = PATH_MAX;
  1043. cwd[ncols - strlen(CWD) - 1] = '\0';
  1044. printw(CWD "%s\n\n", cwd);
  1045. /* Print listing */
  1046. odd = ISODD(nlines);
  1047. if (cur < (nlines >> 1)) {
  1048. for (i = 0; i < nlines; i++)
  1049. printptr(&dents[i], i == cur);
  1050. } else if (cur >= ndents - (nlines >> 1)) {
  1051. for (i = ndents - nlines; i < ndents; i++)
  1052. printptr(&dents[i], i == cur);
  1053. } else {
  1054. nlines >>= 1;
  1055. for (i = cur - nlines; i < cur + nlines + odd; i++)
  1056. printptr(&dents[i], i == cur);
  1057. }
  1058. if (showdetail) {
  1059. if (ndents) {
  1060. static char ind[2] = "\0\0";
  1061. static char sort[17];
  1062. if (mtimeorder)
  1063. sprintf(sort, "by time ");
  1064. else if (sizeorder)
  1065. sprintf(sort, "by size ");
  1066. else
  1067. sort[0] = '\0';
  1068. if (S_ISDIR(dents[cur].mode))
  1069. ind[0] = '/';
  1070. else if (S_ISLNK(dents[cur].mode))
  1071. ind[0] = '@';
  1072. else if (S_ISSOCK(dents[cur].mode))
  1073. ind[0] = '=';
  1074. else if (S_ISFIFO(dents[cur].mode))
  1075. ind[0] = '|';
  1076. else if (dents[cur].mode & S_IXUSR)
  1077. ind[0] = '*';
  1078. else
  1079. ind[0] = '\0';
  1080. if (!bsizeorder)
  1081. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  1082. dents[cur].name, ind);
  1083. else
  1084. sprintf(cwd, "total %d by disk usage, %s free [%s%s]",
  1085. ndents, coolsize(fs_free), dents[cur].name, ind);
  1086. printmsg(cwd);
  1087. } else
  1088. printmsg("0 items");
  1089. }
  1090. }
  1091. static void
  1092. browse(char *ipath, char *ifilter)
  1093. {
  1094. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  1095. static char lastdir[PATH_MAX];
  1096. static char fltr[LINE_MAX];
  1097. char *bin, *dir, *tmp, *run, *env;
  1098. struct stat sb;
  1099. regex_t re;
  1100. int r, fd;
  1101. enum action sel = SEL_RUNARG + 1;
  1102. xstrlcpy(path, ipath, sizeof(path));
  1103. xstrlcpy(lastdir, ipath, sizeof(lastdir));
  1104. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1105. oldpath[0] = '\0';
  1106. newpath[0] = '\0';
  1107. begin:
  1108. if (sel == SEL_GOIN && S_ISDIR(sb.st_mode))
  1109. r = populate(path, NULL, fltr);
  1110. else
  1111. r = populate(path, oldpath, fltr);
  1112. if (r == -1) {
  1113. printwarn();
  1114. goto nochange;
  1115. }
  1116. for (;;) {
  1117. redraw(path);
  1118. nochange:
  1119. sel = nextsel(&run, &env);
  1120. switch (sel) {
  1121. case SEL_CDQUIT:
  1122. {
  1123. FILE *fp = fopen(nnn_tmpfile, "w");
  1124. if (fp) {
  1125. fprintf(fp, "cd \"%s\"", path);
  1126. fclose(fp);
  1127. }
  1128. }
  1129. case SEL_QUIT:
  1130. dentfree(dents);
  1131. return;
  1132. case SEL_BACK:
  1133. /* There is no going back */
  1134. if (strcmp(path, "/") == 0 ||
  1135. strchr(path, '/') == NULL) {
  1136. printmsg("You are at /");
  1137. goto nochange;
  1138. }
  1139. dir = xdirname(path);
  1140. if (canopendir(dir) == 0) {
  1141. printwarn();
  1142. goto nochange;
  1143. }
  1144. /* Save history */
  1145. xstrlcpy(oldpath, path, sizeof(oldpath));
  1146. /* Save last working directory */
  1147. xstrlcpy(lastdir, path, sizeof(lastdir));
  1148. xstrlcpy(path, dir, sizeof(path));
  1149. /* Reset filter */
  1150. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1151. goto begin;
  1152. case SEL_GOIN:
  1153. /* Cannot descend in empty directories */
  1154. if (ndents == 0)
  1155. goto nochange;
  1156. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  1157. DPRINTF_S(newpath);
  1158. /* Get path info */
  1159. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1160. if (fd == -1) {
  1161. printwarn();
  1162. goto nochange;
  1163. }
  1164. r = fstat(fd, &sb);
  1165. if (r == -1) {
  1166. printwarn();
  1167. close(fd);
  1168. goto nochange;
  1169. }
  1170. close(fd);
  1171. DPRINTF_U(sb.st_mode);
  1172. switch (sb.st_mode & S_IFMT) {
  1173. case S_IFDIR:
  1174. if (canopendir(newpath) == 0) {
  1175. printwarn();
  1176. goto nochange;
  1177. }
  1178. /* Save last working directory */
  1179. xstrlcpy(lastdir, path, sizeof(lastdir));
  1180. xstrlcpy(path, newpath, sizeof(path));
  1181. /* Reset filter */
  1182. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1183. goto begin;
  1184. case S_IFREG:
  1185. {
  1186. static char cmd[MAX_CMD_LEN];
  1187. static char *runvi = "vi";
  1188. /* If default mime opener is set, use it */
  1189. if (opener) {
  1190. snprintf(cmd, MAX_CMD_LEN,
  1191. "%s \"%s\" > /dev/null 2>&1",
  1192. opener, newpath);
  1193. r = system(cmd);
  1194. continue;
  1195. }
  1196. /* Try custom applications */
  1197. bin = openwith(newpath);
  1198. /* If custom app doesn't exist try fallback */
  1199. snprintf(cmd, MAX_CMD_LEN, "which \"%s\"", bin);
  1200. if (get_output(cmd, MAX_CMD_LEN) == NULL)
  1201. bin = NULL;
  1202. if (bin == NULL) {
  1203. /* If a custom handler application is
  1204. not set, open plain text files with
  1205. vi, then try fallback_opener */
  1206. snprintf(cmd, MAX_CMD_LEN,
  1207. "file \"%s\"", newpath);
  1208. if (get_output(cmd, MAX_CMD_LEN) == NULL)
  1209. goto nochange;
  1210. if (strstr(cmd, "ASCII text") != NULL)
  1211. bin = runvi;
  1212. else if (fallback_opener) {
  1213. snprintf(cmd, MAX_CMD_LEN,
  1214. "%s \"%s\" > \
  1215. /dev/null 2>&1",
  1216. fallback_opener,
  1217. newpath);
  1218. r = system(cmd);
  1219. continue;
  1220. } else {
  1221. printmsg("No association");
  1222. goto nochange;
  1223. }
  1224. }
  1225. exitcurses();
  1226. spawn(bin, newpath, NULL, 0);
  1227. initcurses();
  1228. continue;
  1229. }
  1230. default:
  1231. printmsg("Unsupported file");
  1232. goto nochange;
  1233. }
  1234. case SEL_FLTR:
  1235. /* Read filter */
  1236. printprompt("filter: ");
  1237. tmp = readln();
  1238. if (tmp == NULL)
  1239. tmp = ifilter;
  1240. /* Check and report regex errors */
  1241. r = setfilter(&re, tmp);
  1242. if (r != 0)
  1243. goto nochange;
  1244. xstrlcpy(fltr, tmp, sizeof(fltr));
  1245. DPRINTF_S(fltr);
  1246. /* Save current */
  1247. if (ndents > 0)
  1248. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1249. goto begin;
  1250. case SEL_NEXT:
  1251. if (cur < ndents - 1)
  1252. cur++;
  1253. else if (ndents)
  1254. /* Roll over, set cursor to first entry */
  1255. cur = 0;
  1256. break;
  1257. case SEL_PREV:
  1258. if (cur > 0)
  1259. cur--;
  1260. else if (ndents)
  1261. /* Roll over, set cursor to last entry */
  1262. cur = ndents - 1;
  1263. break;
  1264. case SEL_PGDN:
  1265. if (cur < ndents - 1)
  1266. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1267. break;
  1268. case SEL_PGUP:
  1269. if (cur > 0)
  1270. cur -= MIN((LINES - 4) / 2, cur);
  1271. break;
  1272. case SEL_HOME:
  1273. cur = 0;
  1274. break;
  1275. case SEL_END:
  1276. cur = ndents - 1;
  1277. break;
  1278. case SEL_CD:
  1279. {
  1280. /* Read target dir */
  1281. tmp = getcwd(newpath, PATH_MAX);
  1282. if (tmp == NULL) {
  1283. printwarn();
  1284. goto nochange;
  1285. }
  1286. if (chdir(path) == -1) {
  1287. printwarn();
  1288. goto nochange;
  1289. }
  1290. exitcurses();
  1291. char *tmp = readline("chdir: ");
  1292. initcurses();
  1293. if (chdir(newpath) == -1)
  1294. printwarn();
  1295. /* Save current */
  1296. if (ndents > 0)
  1297. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1298. if (tmp[0] == '\0')
  1299. break;
  1300. else
  1301. add_history(tmp);
  1302. char *input = tmp;
  1303. tmp = strstrip(tmp);
  1304. if (tmp[0] == '\0') {
  1305. free(input);
  1306. break;
  1307. }
  1308. if (tmp[0] == '~') {
  1309. char *home = getenv("HOME");
  1310. if (home)
  1311. snprintf(newpath, PATH_MAX,
  1312. "%s%s", home, tmp + 1);
  1313. else
  1314. mkpath(path, tmp, newpath, sizeof(newpath));
  1315. oldpath[0] = '\0';
  1316. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1317. xstrlcpy(newpath, lastdir, sizeof(newpath));
  1318. oldpath[0] = '\0';
  1319. } else if (tmp[0] == '.' && tmp[1] == '\0')
  1320. xstrlcpy(newpath, path, sizeof(newpath));
  1321. else if (tmp[0] == '.' && tmp[1] == '.' && tmp[2] == '\0') {
  1322. /* There is no going back */
  1323. if (strcmp(path, "/") == 0 ||
  1324. strchr(path, '/') == NULL) {
  1325. printmsg("You are at /");
  1326. free(input);
  1327. goto nochange;
  1328. }
  1329. dir = xdirname(path);
  1330. if (canopendir(dir) == 0) {
  1331. printwarn();
  1332. free(input);
  1333. goto nochange;
  1334. }
  1335. /* Save history */
  1336. xstrlcpy(oldpath, path, sizeof(oldpath));
  1337. xstrlcpy(newpath, dir, sizeof(newpath));
  1338. } else {
  1339. mkpath(path, tmp, newpath, sizeof(newpath));
  1340. oldpath[0] = '\0';
  1341. }
  1342. if (canopendir(newpath) == 0) {
  1343. /* Save current */
  1344. if (ndents > 0)
  1345. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1346. printwarn();
  1347. free(input);
  1348. break;
  1349. }
  1350. /* Save last working directory */
  1351. xstrlcpy(lastdir, path, sizeof(lastdir));
  1352. xstrlcpy(path, newpath, sizeof(path));
  1353. /* Reset filter */
  1354. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1355. DPRINTF_S(path);
  1356. free(input);
  1357. goto begin;
  1358. }
  1359. case SEL_CDHOME:
  1360. tmp = getenv("HOME");
  1361. if (tmp == NULL) {
  1362. clearprompt();
  1363. goto nochange;
  1364. }
  1365. if (canopendir(tmp) == 0) {
  1366. printwarn();
  1367. goto nochange;
  1368. }
  1369. /* Save last working directory */
  1370. xstrlcpy(lastdir, path, sizeof(lastdir));
  1371. xstrlcpy(path, tmp, sizeof(path));
  1372. /* Reset filter */
  1373. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1374. DPRINTF_S(path);
  1375. goto begin;
  1376. case SEL_LAST:
  1377. xstrlcpy(newpath, lastdir, sizeof(newpath));
  1378. xstrlcpy(lastdir, path, sizeof(lastdir));
  1379. xstrlcpy(path, newpath, sizeof(path));
  1380. oldpath[0] = '\0';
  1381. DPRINTF_S(path);
  1382. goto begin;
  1383. case SEL_TOGGLEDOT:
  1384. showhidden ^= 1;
  1385. initfilter(showhidden, &ifilter);
  1386. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1387. goto begin;
  1388. case SEL_DETAIL:
  1389. showdetail = !showdetail;
  1390. showdetail ? (printptr = &printent_long)
  1391. : (printptr = &printent);
  1392. /* Save current */
  1393. if (ndents > 0)
  1394. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1395. goto begin;
  1396. case SEL_STATS:
  1397. {
  1398. struct stat sb;
  1399. if (ndents > 0)
  1400. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1401. r = lstat(oldpath, &sb);
  1402. if (r == -1) {
  1403. if (dents)
  1404. dentfree(dents);
  1405. printerr(1, "lstat");
  1406. } else
  1407. show_stats(oldpath, dents[cur].name, &sb);
  1408. goto begin;
  1409. }
  1410. case SEL_MEDIA:
  1411. if (ndents > 0)
  1412. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1413. exitcurses();
  1414. r = show_mediainfo(oldpath, FALSE);
  1415. initcurses();
  1416. if (r < 0)
  1417. printmsg("mediainfo missing");
  1418. goto nochange;
  1419. case SEL_FMEDIA:
  1420. if (ndents > 0)
  1421. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1422. exitcurses();
  1423. r = show_mediainfo(oldpath, TRUE);
  1424. initcurses();
  1425. if (r < 0)
  1426. printmsg("mediainfo missing");
  1427. goto nochange;
  1428. case SEL_DFB:
  1429. if (!desktop_manager)
  1430. goto nochange;
  1431. exitcurses();
  1432. spawn(desktop_manager, path, path, 0);
  1433. initcurses();
  1434. goto nochange;
  1435. case SEL_FSIZE:
  1436. sizeorder = !sizeorder;
  1437. mtimeorder = 0;
  1438. bsizeorder = 0;
  1439. /* Save current */
  1440. if (ndents > 0)
  1441. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1442. goto begin;
  1443. case SEL_BSIZE:
  1444. bsizeorder = !bsizeorder;
  1445. if (bsizeorder) {
  1446. showdetail = 1;
  1447. printptr = &printent_long;
  1448. }
  1449. mtimeorder = 0;
  1450. sizeorder = 0;
  1451. /* Save current */
  1452. if (ndents > 0)
  1453. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1454. goto begin;
  1455. case SEL_MTIME:
  1456. mtimeorder = !mtimeorder;
  1457. sizeorder = 0;
  1458. bsizeorder = 0;
  1459. /* Save current */
  1460. if (ndents > 0)
  1461. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1462. goto begin;
  1463. case SEL_REDRAW:
  1464. /* Save current */
  1465. if (ndents > 0)
  1466. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1467. goto begin;
  1468. case SEL_COPY:
  1469. if (copier && ndents) {
  1470. if (strcmp(path, "/") == 0)
  1471. snprintf(newpath, PATH_MAX, "/%s",
  1472. dents[cur].name);
  1473. else
  1474. snprintf(newpath, PATH_MAX, "%s/%s",
  1475. path, dents[cur].name);
  1476. spawn(copier, newpath, NULL, 0);
  1477. printmsg(newpath);
  1478. } else if (!copier)
  1479. printmsg("NNN_COPIER is not set");
  1480. goto nochange;
  1481. case SEL_HELP:
  1482. show_help();
  1483. /* Save current */
  1484. if (ndents > 0)
  1485. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1486. goto begin;
  1487. case SEL_RUN:
  1488. run = xgetenv(env, run);
  1489. exitcurses();
  1490. spawn(run, NULL, path, 1);
  1491. initcurses();
  1492. /* Repopulate as directory content may have changed */
  1493. goto begin;
  1494. case SEL_RUNARG:
  1495. run = xgetenv(env, run);
  1496. exitcurses();
  1497. spawn(run, dents[cur].name, path, 0);
  1498. initcurses();
  1499. break;
  1500. }
  1501. /* Screensaver */
  1502. if (idletimeout != 0 && idle == idletimeout) {
  1503. idle = 0;
  1504. exitcurses();
  1505. spawn(idlecmd, NULL, NULL, 0);
  1506. initcurses();
  1507. }
  1508. }
  1509. }
  1510. static void
  1511. usage(void)
  1512. {
  1513. fprintf(stdout, "usage: nnn [-d] [-S] [-v] [h] [PATH]\n\n\
  1514. The missing terminal file browser for X.\n\n\
  1515. positional arguments:\n\
  1516. PATH directory to open [default: current dir]\n\n\
  1517. optional arguments:\n\
  1518. -d start in detail view mode\n\
  1519. -S start in disk usage analyzer mode\n\
  1520. -v show program version and exit\n\
  1521. -h show this help and exit\n\n\
  1522. Version: %s\n\
  1523. License: BSD 2-Clause\n\
  1524. Webpage: https://github.com/jarun/nnn\n", VERSION);
  1525. exit(0);
  1526. }
  1527. int
  1528. main(int argc, char *argv[])
  1529. {
  1530. char cwd[PATH_MAX], *ipath;
  1531. char *ifilter;
  1532. int opt = 0;
  1533. /* Confirm we are in a terminal */
  1534. if (!isatty(0) || !isatty(1)) {
  1535. fprintf(stderr, "stdin or stdout is not a tty\n");
  1536. exit(1);
  1537. }
  1538. if (argc > 3)
  1539. usage();
  1540. while ((opt = getopt(argc, argv, "dSvh")) != -1) {
  1541. switch (opt) {
  1542. case 'S':
  1543. bsizeorder = 1;
  1544. case 'd':
  1545. /* Open in detail mode, if set */
  1546. showdetail = 1;
  1547. printptr = &printent_long;
  1548. break;
  1549. case 'v':
  1550. fprintf(stdout, "%s\n", VERSION);
  1551. return 0;
  1552. case 'h':
  1553. default:
  1554. usage();
  1555. }
  1556. }
  1557. if (argc == optind) {
  1558. /* Start in the current directory */
  1559. ipath = getcwd(cwd, sizeof(cwd));
  1560. if (ipath == NULL)
  1561. ipath = "/";
  1562. } else {
  1563. ipath = realpath(argv[optind], cwd);
  1564. if (!ipath) {
  1565. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1566. exit(1);
  1567. }
  1568. }
  1569. open_max = max_openfds();
  1570. /* Get temporary file name (ifilter used as temporary variable) */
  1571. if ((ifilter = getenv("NNN_TMPFILE")) != NULL)
  1572. nnn_tmpfile = ifilter;
  1573. if (getuid() == 0)
  1574. showhidden = 1;
  1575. initfilter(showhidden, &ifilter);
  1576. /* Get the default desktop mime opener, if set */
  1577. opener = getenv("NNN_OPENER");
  1578. /* Get the fallback desktop mime opener, if set */
  1579. fallback_opener = getenv("NNN_FALLBACK_OPENER");
  1580. /* Get the desktop file browser, if set */
  1581. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  1582. /* Get the default copier, if set */
  1583. copier = getenv("NNN_COPIER");
  1584. signal(SIGINT, SIG_IGN);
  1585. /* Test initial path */
  1586. if (canopendir(ipath) == 0) {
  1587. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1588. exit(1);
  1589. }
  1590. /* Set locale */
  1591. setlocale(LC_ALL, "");
  1592. initcurses();
  1593. browse(ipath, ifilter);
  1594. exitcurses();
  1595. exit(0);
  1596. }