My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1759 lignes
36 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. strcmp(path, ".") == 0 ||
  1120. strchr(path, '/') == NULL) {
  1121. printmsg("You are at /");
  1122. goto nochange;
  1123. }
  1124. dir = xdirname(path);
  1125. if (canopendir(dir) == 0) {
  1126. printwarn();
  1127. goto nochange;
  1128. }
  1129. /* Save history */
  1130. xstrlcpy(oldpath, path, sizeof(oldpath));
  1131. /* Save last working directory */
  1132. xstrlcpy(lastdir, path, sizeof(lastdir));
  1133. xstrlcpy(path, dir, sizeof(path));
  1134. /* Reset filter */
  1135. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1136. goto begin;
  1137. case SEL_GOIN:
  1138. /* Cannot descend in empty directories */
  1139. if (ndents == 0)
  1140. goto nochange;
  1141. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  1142. DPRINTF_S(newpath);
  1143. /* Get path info */
  1144. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1145. if (fd == -1) {
  1146. printwarn();
  1147. goto nochange;
  1148. }
  1149. r = fstat(fd, &sb);
  1150. if (r == -1) {
  1151. printwarn();
  1152. close(fd);
  1153. goto nochange;
  1154. }
  1155. close(fd);
  1156. DPRINTF_U(sb.st_mode);
  1157. switch (sb.st_mode & S_IFMT) {
  1158. case S_IFDIR:
  1159. if (canopendir(newpath) == 0) {
  1160. printwarn();
  1161. goto nochange;
  1162. }
  1163. /* Save last working directory */
  1164. xstrlcpy(lastdir, path, sizeof(lastdir));
  1165. xstrlcpy(path, newpath, sizeof(path));
  1166. /* Reset filter */
  1167. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1168. goto begin;
  1169. case S_IFREG:
  1170. {
  1171. static char cmd[MAX_CMD_LEN];
  1172. static char *runvi = "vi";
  1173. static int status;
  1174. /* If default mime opener is set, use it */
  1175. if (opener) {
  1176. snprintf(cmd, MAX_CMD_LEN,
  1177. "%s \"%s\" > /dev/null 2>&1",
  1178. opener, newpath);
  1179. status = system(cmd);
  1180. continue;
  1181. }
  1182. /* Try custom applications */
  1183. bin = openwith(newpath);
  1184. /* If custom app doesn't exist try fallback */
  1185. snprintf(cmd, MAX_CMD_LEN, "which \"%s\"", bin);
  1186. if (get_output(cmd, MAX_CMD_LEN) == NULL)
  1187. bin = NULL;
  1188. if (bin == NULL) {
  1189. /* If a custom handler application is
  1190. not set, open plain text files with
  1191. vi, then try fallback_opener */
  1192. snprintf(cmd, MAX_CMD_LEN,
  1193. "file \"%s\"", newpath);
  1194. if (get_output(cmd, MAX_CMD_LEN) == NULL)
  1195. goto nochange;
  1196. if (strstr(cmd, "ASCII text") != NULL)
  1197. bin = runvi;
  1198. else if (fallback_opener) {
  1199. snprintf(cmd, MAX_CMD_LEN,
  1200. "%s \"%s\" > \
  1201. /dev/null 2>&1",
  1202. fallback_opener,
  1203. newpath);
  1204. status = system(cmd);
  1205. continue;
  1206. } else {
  1207. status++; /* Dummy operation */
  1208. printmsg("No association");
  1209. goto nochange;
  1210. }
  1211. }
  1212. exitcurses();
  1213. spawn(bin, newpath, NULL, 0);
  1214. initcurses();
  1215. continue;
  1216. }
  1217. default:
  1218. printmsg("Unsupported file");
  1219. goto nochange;
  1220. }
  1221. case SEL_FLTR:
  1222. /* Read filter */
  1223. printprompt("filter: ");
  1224. tmp = readln();
  1225. if (tmp == NULL)
  1226. tmp = ifilter;
  1227. /* Check and report regex errors */
  1228. r = setfilter(&re, tmp);
  1229. if (r != 0)
  1230. goto nochange;
  1231. xstrlcpy(fltr, tmp, sizeof(fltr));
  1232. DPRINTF_S(fltr);
  1233. /* Save current */
  1234. if (ndents > 0)
  1235. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1236. goto begin;
  1237. case SEL_NEXT:
  1238. if (cur < ndents - 1)
  1239. cur++;
  1240. else if (ndents)
  1241. /* Roll over, set cursor to first entry */
  1242. cur = 0;
  1243. break;
  1244. case SEL_PREV:
  1245. if (cur > 0)
  1246. cur--;
  1247. else if (ndents)
  1248. /* Roll over, set cursor to last entry */
  1249. cur = ndents - 1;
  1250. break;
  1251. case SEL_PGDN:
  1252. if (cur < ndents - 1)
  1253. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1254. break;
  1255. case SEL_PGUP:
  1256. if (cur > 0)
  1257. cur -= MIN((LINES - 4) / 2, cur);
  1258. break;
  1259. case SEL_HOME:
  1260. cur = 0;
  1261. break;
  1262. case SEL_END:
  1263. cur = ndents - 1;
  1264. break;
  1265. case SEL_CD:
  1266. {
  1267. /* Read target dir */
  1268. char cwd[PATH_MAX];
  1269. tmp = getcwd(cwd, PATH_MAX);
  1270. if (tmp == NULL) {
  1271. printwarn();
  1272. goto nochange;
  1273. }
  1274. if (chdir(path) == -1) {
  1275. printwarn();
  1276. goto nochange;
  1277. }
  1278. exitcurses();
  1279. char *tmp = readline("chdir: ");
  1280. initcurses();
  1281. tmp = tmp[0] ? tmp : NULL;
  1282. if (chdir(cwd) == -1)
  1283. printwarn();
  1284. if (tmp == NULL) {
  1285. /* Save current */
  1286. if (ndents > 0)
  1287. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1288. goto begin;
  1289. } else
  1290. add_history(tmp);
  1291. char *input = tmp;
  1292. tmp = strstrip(tmp);
  1293. if (tmp[0] == '~') {
  1294. char *home = getenv("HOME");
  1295. if (home)
  1296. snprintf(newpath, PATH_MAX,
  1297. "%s%s", home, tmp + 1);
  1298. else
  1299. mkpath(path, tmp, newpath, sizeof(newpath));
  1300. } else if (tmp[0] == '-' && tmp[1] == '\0')
  1301. xstrlcpy(newpath, lastdir, sizeof(newpath));
  1302. else
  1303. mkpath(path, tmp, newpath, sizeof(newpath));
  1304. if (canopendir(newpath) == 0) {
  1305. /* Save current */
  1306. if (ndents > 0)
  1307. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1308. printwarn();
  1309. free(input);
  1310. goto begin;
  1311. }
  1312. /* Save last working directory */
  1313. xstrlcpy(lastdir, path, sizeof(lastdir));
  1314. xstrlcpy(path, newpath, sizeof(path));
  1315. /* Reset filter */
  1316. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1317. DPRINTF_S(path);
  1318. oldpath[0] = '\0';
  1319. free(input);
  1320. goto begin;
  1321. }
  1322. case SEL_CDHOME:
  1323. tmp = getenv("HOME");
  1324. if (tmp == NULL) {
  1325. clearprompt();
  1326. goto nochange;
  1327. }
  1328. if (canopendir(tmp) == 0) {
  1329. printwarn();
  1330. goto nochange;
  1331. }
  1332. /* Save last working directory */
  1333. xstrlcpy(lastdir, path, sizeof(lastdir));
  1334. xstrlcpy(path, tmp, sizeof(path));
  1335. /* Reset filter */
  1336. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1337. DPRINTF_S(path);
  1338. goto begin;
  1339. case SEL_LAST:
  1340. xstrlcpy(newpath, lastdir, sizeof(newpath));
  1341. xstrlcpy(lastdir, path, sizeof(lastdir));
  1342. xstrlcpy(path, newpath, sizeof(path));
  1343. DPRINTF_S(path);
  1344. goto begin;
  1345. case SEL_TOGGLEDOT:
  1346. showhidden ^= 1;
  1347. initfilter(showhidden, &ifilter);
  1348. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1349. goto begin;
  1350. case SEL_DETAIL:
  1351. showdetail = !showdetail;
  1352. showdetail ? (printptr = &printent_long)
  1353. : (printptr = &printent);
  1354. /* Save current */
  1355. if (ndents > 0)
  1356. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1357. goto begin;
  1358. case SEL_STATS:
  1359. {
  1360. struct stat sb;
  1361. if (ndents > 0)
  1362. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1363. r = lstat(oldpath, &sb);
  1364. if (r == -1)
  1365. printerr(1, "lstat");
  1366. else
  1367. show_stats(oldpath, dents[cur].name, &sb);
  1368. goto begin;
  1369. }
  1370. case SEL_DFB:
  1371. if (!desktop_manager)
  1372. goto nochange;
  1373. exitcurses();
  1374. spawn(desktop_manager, path, path, 0);
  1375. initcurses();
  1376. goto nochange;
  1377. case SEL_FSIZE:
  1378. sizeorder = !sizeorder;
  1379. mtimeorder = 0;
  1380. bsizeorder = 0;
  1381. /* Save current */
  1382. if (ndents > 0)
  1383. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1384. goto begin;
  1385. case SEL_BSIZE:
  1386. bsizeorder = !bsizeorder;
  1387. if (bsizeorder) {
  1388. showdetail = 1;
  1389. printptr = &printent_long;
  1390. }
  1391. mtimeorder = 0;
  1392. sizeorder = 0;
  1393. /* Save current */
  1394. if (ndents > 0)
  1395. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1396. goto begin;
  1397. case SEL_MTIME:
  1398. mtimeorder = !mtimeorder;
  1399. sizeorder = 0;
  1400. bsizeorder = 0;
  1401. /* Save current */
  1402. if (ndents > 0)
  1403. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1404. goto begin;
  1405. case SEL_REDRAW:
  1406. /* Save current */
  1407. if (ndents > 0)
  1408. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1409. goto begin;
  1410. case SEL_COPY:
  1411. if (copier && ndents) {
  1412. char abspath[PATH_MAX];
  1413. if (strcmp(path, "/") == 0)
  1414. snprintf(abspath, PATH_MAX, "/%s",
  1415. dents[cur].name);
  1416. else
  1417. snprintf(abspath, PATH_MAX, "%s/%s",
  1418. path, dents[cur].name);
  1419. spawn(copier, abspath, NULL, 0);
  1420. printmsg(abspath);
  1421. } else if (!copier)
  1422. printmsg("NNN_COPIER is not set");
  1423. goto nochange;
  1424. case SEL_HELP:
  1425. show_help();
  1426. /* Save current */
  1427. if (ndents > 0)
  1428. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1429. goto begin;
  1430. case SEL_RUN:
  1431. run = xgetenv(env, run);
  1432. exitcurses();
  1433. spawn(run, NULL, path, 1);
  1434. initcurses();
  1435. /* Repopulate as directory content may have changed */
  1436. goto begin;
  1437. case SEL_RUNARG:
  1438. run = xgetenv(env, run);
  1439. exitcurses();
  1440. spawn(run, dents[cur].name, path, 0);
  1441. initcurses();
  1442. break;
  1443. }
  1444. /* Screensaver */
  1445. if (idletimeout != 0 && idle == idletimeout) {
  1446. idle = 0;
  1447. exitcurses();
  1448. spawn(idlecmd, NULL, NULL, 0);
  1449. initcurses();
  1450. }
  1451. }
  1452. }
  1453. static void
  1454. usage(void)
  1455. {
  1456. fprintf(stdout, "usage: nnn [-d] [-S] [-v] [h] [PATH]\n\n\
  1457. The missing terminal file browser for X.\n\n\
  1458. positional arguments:\n\
  1459. PATH directory to open [default: current dir]\n\n\
  1460. optional arguments:\n\
  1461. -d start in detail view mode\n\
  1462. -S start in disk usage analyzer mode\n\
  1463. -v show program version and exit\n\
  1464. -h show this help and exit\n\n\
  1465. Version: %s\n\
  1466. License: BSD 2-Clause\n\
  1467. Webpage: https://github.com/jarun/nnn\n", VERSION);
  1468. exit(0);
  1469. }
  1470. int
  1471. main(int argc, char *argv[])
  1472. {
  1473. char cwd[PATH_MAX], *ipath;
  1474. char *ifilter;
  1475. int opt = 0;
  1476. /* Confirm we are in a terminal */
  1477. if (!isatty(0) || !isatty(1)) {
  1478. fprintf(stderr, "stdin or stdout is not a tty\n");
  1479. exit(1);
  1480. }
  1481. if (argc > 3)
  1482. usage();
  1483. while ((opt = getopt(argc, argv, "dSvh")) != -1) {
  1484. switch (opt) {
  1485. case 'S':
  1486. bsizeorder = 1;
  1487. case 'd':
  1488. /* Open in detail mode, if set */
  1489. showdetail = 1;
  1490. printptr = &printent_long;
  1491. break;
  1492. case 'v':
  1493. fprintf(stdout, "%s\n", VERSION);
  1494. return 0;
  1495. case 'h':
  1496. default:
  1497. usage();
  1498. }
  1499. }
  1500. if (argc == optind) {
  1501. /* Start in the current directory */
  1502. ipath = getcwd(cwd, sizeof(cwd));
  1503. if (ipath == NULL)
  1504. ipath = "/";
  1505. } else {
  1506. ipath = realpath(argv[optind], cwd);
  1507. if (!ipath) {
  1508. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1509. exit(1);
  1510. }
  1511. }
  1512. open_max = max_openfds();
  1513. if (getuid() == 0)
  1514. showhidden = 1;
  1515. initfilter(showhidden, &ifilter);
  1516. /* Get the default desktop mime opener, if set */
  1517. opener = getenv("NNN_OPENER");
  1518. /* Get the fallback desktop mime opener, if set */
  1519. fallback_opener = getenv("NNN_FALLBACK_OPENER");
  1520. /* Get the desktop file browser, if set */
  1521. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  1522. /* Get the default copier, if set */
  1523. copier = getenv("NNN_COPIER");
  1524. signal(SIGINT, SIG_IGN);
  1525. /* Test initial path */
  1526. if (canopendir(ipath) == 0) {
  1527. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1528. exit(1);
  1529. }
  1530. /* Set locale */
  1531. setlocale(LC_ALL, "");
  1532. initcurses();
  1533. browse(ipath, ifilter);
  1534. exitcurses();
  1535. exit(0);
  1536. }