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.
 
 
 
 
 
 

1677 lignes
35 KiB

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