My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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