My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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