My build of nnn with minor changes
 
 
 
 
 
 

1825 lines
38 KiB

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