My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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