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

1815 строки
38 KiB

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