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

829 lines
15 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 <curses.h>
  6. #include <dirent.h>
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <libgen.h>
  10. #include <limits.h>
  11. #include <locale.h>
  12. #include <regex.h>
  13. #include <signal.h>
  14. #include <stdarg.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <unistd.h>
  19. #include "util.h"
  20. #ifdef DEBUG
  21. #define DEBUG_FD 8
  22. #define DPRINTF_D(x) dprintf(DEBUG_FD, #x "=%d\n", x)
  23. #define DPRINTF_U(x) dprintf(DEBUG_FD, #x "=%u\n", x)
  24. #define DPRINTF_S(x) dprintf(DEBUG_FD, #x "=%s\n", x)
  25. #define DPRINTF_P(x) dprintf(DEBUG_FD, #x "=0x%p\n", x)
  26. #else
  27. #define DPRINTF_D(x)
  28. #define DPRINTF_U(x)
  29. #define DPRINTF_S(x)
  30. #define DPRINTF_P(x)
  31. #endif /* DEBUG */
  32. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  33. #undef MIN
  34. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  35. #define ISODD(x) ((x) & 1)
  36. #define CONTROL(c) ((c) ^ 0x40)
  37. struct assoc {
  38. char *regex; /* Regex to match on filename */
  39. char *bin; /* Program */
  40. };
  41. /* Supported actions */
  42. enum action {
  43. SEL_QUIT = 1,
  44. SEL_BACK,
  45. SEL_GOIN,
  46. SEL_FLTR,
  47. SEL_NEXT,
  48. SEL_PREV,
  49. SEL_PGDN,
  50. SEL_PGUP,
  51. SEL_HOME,
  52. SEL_END,
  53. SEL_CD,
  54. SEL_CDHOME,
  55. SEL_TOGGLEDOT,
  56. SEL_MTIME,
  57. SEL_REDRAW,
  58. SEL_RUN,
  59. SEL_RUNARG,
  60. };
  61. struct key {
  62. int sym; /* Key pressed */
  63. enum action act; /* Action */
  64. char *run; /* Program to run */
  65. char *env; /* Environment variable to run */
  66. };
  67. #include "config.h"
  68. struct entry {
  69. char name[PATH_MAX];
  70. mode_t mode;
  71. time_t t;
  72. };
  73. /* Global context */
  74. struct entry *dents;
  75. int ndents, cur;
  76. int idle;
  77. /*
  78. * Layout:
  79. * .---------
  80. * | cwd: /mnt/path
  81. * |
  82. * | file0
  83. * | file1
  84. * | > file2
  85. * | file3
  86. * | file4
  87. * ...
  88. * | filen
  89. * |
  90. * | Permission denied
  91. * '------
  92. */
  93. void printmsg(char *);
  94. void printwarn(void);
  95. void printerr(int, char *);
  96. #undef dprintf
  97. int
  98. dprintf(int fd, const char *fmt, ...)
  99. {
  100. char buf[BUFSIZ];
  101. int r;
  102. va_list ap;
  103. va_start(ap, fmt);
  104. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  105. if (r > 0)
  106. write(fd, buf, r);
  107. va_end(ap);
  108. return r;
  109. }
  110. void *
  111. xmalloc(size_t size)
  112. {
  113. void *p;
  114. p = malloc(size);
  115. if (p == NULL)
  116. printerr(1, "malloc");
  117. return p;
  118. }
  119. void *
  120. xrealloc(void *p, size_t size)
  121. {
  122. p = realloc(p, size);
  123. if (p == NULL)
  124. printerr(1, "realloc");
  125. return p;
  126. }
  127. char *
  128. xstrdup(const char *s)
  129. {
  130. char *p;
  131. p = strdup(s);
  132. if (p == NULL)
  133. printerr(1, "strdup");
  134. return p;
  135. }
  136. /* Some implementations of dirname(3) may modify `path' and some
  137. * return a pointer inside `path'. */
  138. char *
  139. xdirname(const char *path)
  140. {
  141. static char out[PATH_MAX];
  142. char tmp[PATH_MAX], *p;
  143. strlcpy(tmp, path, sizeof(tmp));
  144. p = dirname(tmp);
  145. if (p == NULL)
  146. printerr(1, "dirname");
  147. strlcpy(out, p, sizeof(out));
  148. return out;
  149. }
  150. void
  151. spawn(char *file, char *arg, char *dir)
  152. {
  153. pid_t pid;
  154. int status;
  155. pid = fork();
  156. if (pid == 0) {
  157. if (dir != NULL)
  158. chdir(dir);
  159. execlp(file, file, arg, NULL);
  160. _exit(1);
  161. } else {
  162. /* Ignore interruptions */
  163. while (waitpid(pid, &status, 0) == -1)
  164. DPRINTF_D(status);
  165. DPRINTF_D(pid);
  166. }
  167. }
  168. char *
  169. xgetenv(char *name, char *fallback)
  170. {
  171. char *value;
  172. if (name == NULL)
  173. return fallback;
  174. value = getenv(name);
  175. return value && value[0] ? value : fallback;
  176. }
  177. char *
  178. openwith(char *file)
  179. {
  180. regex_t regex;
  181. char *bin = NULL;
  182. int i;
  183. for (i = 0; i < LEN(assocs); i++) {
  184. if (regcomp(&regex, assocs[i].regex,
  185. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  186. continue;
  187. if (regexec(&regex, file, 0, NULL, 0) == 0) {
  188. bin = assocs[i].bin;
  189. break;
  190. }
  191. }
  192. DPRINTF_S(bin);
  193. return bin;
  194. }
  195. int
  196. setfilter(regex_t *regex, char *filter)
  197. {
  198. char errbuf[LINE_MAX];
  199. size_t len;
  200. int r;
  201. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  202. if (r != 0) {
  203. len = COLS;
  204. if (len > sizeof(errbuf))
  205. len = sizeof(errbuf);
  206. regerror(r, regex, errbuf, len);
  207. printmsg(errbuf);
  208. }
  209. return r;
  210. }
  211. void
  212. initfilter(int dot, char **ifilter)
  213. {
  214. *ifilter = dot ? "." : "^[^.]";
  215. }
  216. int
  217. visible(regex_t *regex, char *file)
  218. {
  219. return regexec(regex, file, 0, NULL, 0) == 0;
  220. }
  221. int
  222. entrycmp(const void *va, const void *vb)
  223. {
  224. const struct entry *a = va, *b = vb;
  225. if (mtimeorder)
  226. return b->t - a->t;
  227. return strcmp(a->name, b->name);
  228. }
  229. void
  230. initcurses(void)
  231. {
  232. char *term;
  233. if (initscr() == NULL) {
  234. term = getenv("TERM");
  235. if (term != NULL)
  236. fprintf(stderr, "error opening terminal: %s\n", term);
  237. else
  238. fprintf(stderr, "failed to initialize curses\n");
  239. exit(1);
  240. }
  241. cbreak();
  242. noecho();
  243. nonl();
  244. intrflush(stdscr, FALSE);
  245. keypad(stdscr, TRUE);
  246. curs_set(FALSE); /* Hide cursor */
  247. timeout(1000); /* One second */
  248. }
  249. void
  250. exitcurses(void)
  251. {
  252. endwin(); /* Restore terminal */
  253. }
  254. /* Messages show up at the bottom */
  255. void
  256. printmsg(char *msg)
  257. {
  258. move(LINES - 1, 0);
  259. printw("%s\n", msg);
  260. }
  261. /* Display warning as a message */
  262. void
  263. printwarn(void)
  264. {
  265. printmsg(strerror(errno));
  266. }
  267. /* Kill curses and display error before exiting */
  268. void
  269. printerr(int ret, char *prefix)
  270. {
  271. exitcurses();
  272. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  273. exit(ret);
  274. }
  275. /* Clear the last line */
  276. void
  277. clearprompt(void)
  278. {
  279. printmsg("");
  280. }
  281. /* Print prompt on the last line */
  282. void
  283. printprompt(char *str)
  284. {
  285. clearprompt();
  286. printw(str);
  287. }
  288. /* Returns SEL_* if key is bound and 0 otherwise.
  289. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}) */
  290. int
  291. nextsel(char **run, char **env)
  292. {
  293. int c, i;
  294. c = getch();
  295. if (c == -1)
  296. idle++;
  297. else
  298. idle = 0;
  299. for (i = 0; i < LEN(bindings); i++)
  300. if (c == bindings[i].sym) {
  301. *run = bindings[i].run;
  302. *env = bindings[i].env;
  303. return bindings[i].act;
  304. }
  305. return 0;
  306. }
  307. char *
  308. readln(void)
  309. {
  310. static char ln[LINE_MAX];
  311. timeout(-1);
  312. echo();
  313. curs_set(TRUE);
  314. memset(ln, 0, sizeof(ln));
  315. wgetnstr(stdscr, ln, sizeof(ln) - 1);
  316. noecho();
  317. curs_set(FALSE);
  318. timeout(1000);
  319. return ln[0] ? ln : NULL;
  320. }
  321. int
  322. canopendir(char *path)
  323. {
  324. DIR *dirp;
  325. dirp = opendir(path);
  326. if (dirp == NULL)
  327. return 0;
  328. closedir(dirp);
  329. return 1;
  330. }
  331. char *
  332. mkpath(char *dir, char *name, char *out, size_t n)
  333. {
  334. /* Handle absolute path */
  335. if (name[0] == '/') {
  336. strlcpy(out, name, n);
  337. } else {
  338. /* Handle root case */
  339. if (strcmp(dir, "/") == 0) {
  340. strlcpy(out, "/", n);
  341. strlcat(out, name, n);
  342. } else {
  343. strlcpy(out, dir, n);
  344. strlcat(out, "/", n);
  345. strlcat(out, name, n);
  346. }
  347. }
  348. return out;
  349. }
  350. void
  351. printent(struct entry *ent, int active)
  352. {
  353. char name[PATH_MAX];
  354. unsigned int maxlen = COLS - strlen(CURSR) - 1;
  355. char cm = 0;
  356. /* Copy name locally */
  357. strlcpy(name, ent->name, sizeof(name));
  358. if (S_ISDIR(ent->mode)) {
  359. cm = '/';
  360. maxlen--;
  361. } else if (S_ISLNK(ent->mode)) {
  362. cm = '@';
  363. maxlen--;
  364. } else if (S_ISSOCK(ent->mode)) {
  365. cm = '=';
  366. maxlen--;
  367. } else if (S_ISFIFO(ent->mode)) {
  368. cm = '|';
  369. maxlen--;
  370. } else if (ent->mode & S_IXUSR) {
  371. cm = '*';
  372. maxlen--;
  373. }
  374. /* No text wrapping in entries */
  375. if (strlen(name) > maxlen)
  376. name[maxlen] = '\0';
  377. if (cm == 0)
  378. printw("%s%s\n", active ? CURSR : EMPTY, name);
  379. else
  380. printw("%s%s%c\n", active ? CURSR : EMPTY, name, cm);
  381. }
  382. int
  383. dentfill(char *path, struct entry **dents,
  384. int (*filter)(regex_t *, char *), regex_t *re)
  385. {
  386. char newpath[PATH_MAX];
  387. DIR *dirp;
  388. struct dirent *dp;
  389. struct stat sb;
  390. int r, n = 0;
  391. dirp = opendir(path);
  392. if (dirp == NULL)
  393. return 0;
  394. while ((dp = readdir(dirp)) != NULL) {
  395. /* Skip self and parent */
  396. if (strcmp(dp->d_name, ".") == 0 ||
  397. strcmp(dp->d_name, "..") == 0)
  398. continue;
  399. if (filter(re, dp->d_name) == 0)
  400. continue;
  401. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  402. strlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  403. /* Get mode flags */
  404. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  405. r = lstat(newpath, &sb);
  406. if (r == -1)
  407. printerr(1, "lstat");
  408. (*dents)[n].mode = sb.st_mode;
  409. (*dents)[n].t = sb.st_mtime;
  410. n++;
  411. }
  412. /* Should never be null */
  413. r = closedir(dirp);
  414. if (r == -1)
  415. printerr(1, "closedir");
  416. return n;
  417. }
  418. void
  419. dentfree(struct entry *dents)
  420. {
  421. free(dents);
  422. }
  423. /* Return the position of the matching entry or 0 otherwise */
  424. int
  425. dentfind(struct entry *dents, int n, char *cwd, char *path)
  426. {
  427. char tmp[PATH_MAX];
  428. int i;
  429. if (path == NULL)
  430. return 0;
  431. for (i = 0; i < n; i++) {
  432. mkpath(cwd, dents[i].name, tmp, sizeof(tmp));
  433. DPRINTF_S(path);
  434. DPRINTF_S(tmp);
  435. if (strcmp(tmp, path) == 0)
  436. return i;
  437. }
  438. return 0;
  439. }
  440. int
  441. populate(char *path, char *oldpath, char *fltr)
  442. {
  443. regex_t re;
  444. int r;
  445. /* Can fail when permissions change while browsing */
  446. if (canopendir(path) == 0)
  447. return -1;
  448. /* Search filter */
  449. r = setfilter(&re, fltr);
  450. if (r != 0)
  451. return -1;
  452. dentfree(dents);
  453. ndents = 0;
  454. dents = NULL;
  455. ndents = dentfill(path, &dents, visible, &re);
  456. qsort(dents, ndents, sizeof(*dents), entrycmp);
  457. /* Find cur from history */
  458. cur = dentfind(dents, ndents, path, oldpath);
  459. return 0;
  460. }
  461. void
  462. redraw(char *path)
  463. {
  464. char cwd[PATH_MAX], cwdresolved[PATH_MAX];
  465. size_t ncols;
  466. int nlines, odd;
  467. int i;
  468. nlines = MIN(LINES - 4, ndents);
  469. /* Clean screen */
  470. erase();
  471. /* Strip trailing slashes */
  472. for (i = strlen(path) - 1; i > 0; i--)
  473. if (path[i] == '/')
  474. path[i] = '\0';
  475. else
  476. break;
  477. DPRINTF_D(cur);
  478. DPRINTF_S(path);
  479. /* No text wrapping in cwd line */
  480. ncols = COLS;
  481. if (ncols > PATH_MAX)
  482. ncols = PATH_MAX;
  483. strlcpy(cwd, path, ncols);
  484. cwd[ncols - strlen(CWD) - 1] = '\0';
  485. realpath(cwd, cwdresolved);
  486. printw(CWD "%s\n\n", cwdresolved);
  487. /* Print listing */
  488. odd = ISODD(nlines);
  489. if (cur < nlines / 2) {
  490. for (i = 0; i < nlines; i++)
  491. printent(&dents[i], i == cur);
  492. } else if (cur >= ndents - nlines / 2) {
  493. for (i = ndents - nlines; i < ndents; i++)
  494. printent(&dents[i], i == cur);
  495. } else {
  496. for (i = cur - nlines / 2;
  497. i < cur + nlines / 2 + odd; i++)
  498. printent(&dents[i], i == cur);
  499. }
  500. }
  501. void
  502. browse(char *ipath, char *ifilter)
  503. {
  504. char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  505. char fltr[LINE_MAX];
  506. char *bin, *dir, *tmp, *run, *env;
  507. struct stat sb;
  508. regex_t re;
  509. int r, fd;
  510. strlcpy(path, ipath, sizeof(path));
  511. strlcpy(fltr, ifilter, sizeof(fltr));
  512. oldpath[0] = '\0';
  513. begin:
  514. r = populate(path, oldpath, fltr);
  515. if (r == -1) {
  516. printwarn();
  517. goto nochange;
  518. }
  519. for (;;) {
  520. redraw(path);
  521. nochange:
  522. switch (nextsel(&run, &env)) {
  523. case SEL_QUIT:
  524. dentfree(dents);
  525. return;
  526. case SEL_BACK:
  527. /* There is no going back */
  528. if (strcmp(path, "/") == 0 ||
  529. strcmp(path, ".") == 0 ||
  530. strchr(path, '/') == NULL)
  531. goto nochange;
  532. dir = xdirname(path);
  533. if (canopendir(dir) == 0) {
  534. printwarn();
  535. goto nochange;
  536. }
  537. /* Save history */
  538. strlcpy(oldpath, path, sizeof(oldpath));
  539. strlcpy(path, dir, sizeof(path));
  540. /* Reset filter */
  541. strlcpy(fltr, ifilter, sizeof(fltr));
  542. goto begin;
  543. case SEL_GOIN:
  544. /* Cannot descend in empty directories */
  545. if (ndents == 0)
  546. goto nochange;
  547. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  548. DPRINTF_S(newpath);
  549. /* Get path info */
  550. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  551. if (fd == -1) {
  552. printwarn();
  553. goto nochange;
  554. }
  555. r = fstat(fd, &sb);
  556. if (r == -1) {
  557. printwarn();
  558. close(fd);
  559. goto nochange;
  560. }
  561. close(fd);
  562. DPRINTF_U(sb.st_mode);
  563. switch (sb.st_mode & S_IFMT) {
  564. case S_IFDIR:
  565. if (canopendir(newpath) == 0) {
  566. printwarn();
  567. goto nochange;
  568. }
  569. strlcpy(path, newpath, sizeof(path));
  570. /* Reset filter */
  571. strlcpy(fltr, ifilter, sizeof(fltr));
  572. goto begin;
  573. case S_IFREG:
  574. bin = openwith(newpath);
  575. if (bin == NULL) {
  576. printmsg("No association");
  577. goto nochange;
  578. }
  579. exitcurses();
  580. spawn(bin, newpath, NULL);
  581. initcurses();
  582. continue;
  583. default:
  584. printmsg("Unsupported file");
  585. goto nochange;
  586. }
  587. case SEL_FLTR:
  588. /* Read filter */
  589. printprompt("filter: ");
  590. tmp = readln();
  591. if (tmp == NULL)
  592. tmp = ifilter;
  593. /* Check and report regex errors */
  594. r = setfilter(&re, tmp);
  595. if (r != 0)
  596. goto nochange;
  597. strlcpy(fltr, tmp, sizeof(fltr));
  598. DPRINTF_S(fltr);
  599. /* Save current */
  600. if (ndents > 0)
  601. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  602. goto begin;
  603. case SEL_NEXT:
  604. if (cur < ndents - 1)
  605. cur++;
  606. break;
  607. case SEL_PREV:
  608. if (cur > 0)
  609. cur--;
  610. break;
  611. case SEL_PGDN:
  612. if (cur < ndents - 1)
  613. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  614. break;
  615. case SEL_PGUP:
  616. if (cur > 0)
  617. cur -= MIN((LINES - 4) / 2, cur);
  618. break;
  619. case SEL_HOME:
  620. cur = 0;
  621. break;
  622. case SEL_END:
  623. cur = ndents - 1;
  624. break;
  625. case SEL_CD:
  626. /* Read target dir */
  627. printprompt("chdir: ");
  628. tmp = readln();
  629. if (tmp == NULL) {
  630. clearprompt();
  631. goto nochange;
  632. }
  633. mkpath(path, tmp, newpath, sizeof(newpath));
  634. if (canopendir(newpath) == 0) {
  635. printwarn();
  636. goto nochange;
  637. }
  638. strlcpy(path, newpath, sizeof(path));
  639. /* Reset filter */
  640. strlcpy(fltr, ifilter, sizeof(fltr))
  641. DPRINTF_S(path);
  642. goto begin;
  643. case SEL_CDHOME:
  644. tmp = getenv("HOME");
  645. if (tmp == NULL) {
  646. clearprompt();
  647. goto nochange;
  648. }
  649. if (canopendir(tmp) == 0) {
  650. printwarn();
  651. goto nochange;
  652. }
  653. strlcpy(path, tmp, sizeof(path));
  654. /* Reset filter */
  655. strlcpy(fltr, ifilter, sizeof(fltr));
  656. DPRINTF_S(path);
  657. goto begin;
  658. case SEL_TOGGLEDOT:
  659. showhidden ^= 1;
  660. initfilter(showhidden, &ifilter);
  661. strlcpy(fltr, ifilter, sizeof(fltr));
  662. goto begin;
  663. case SEL_MTIME:
  664. mtimeorder = !mtimeorder;
  665. /* Save current */
  666. if (ndents > 0)
  667. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  668. goto begin;
  669. case SEL_REDRAW:
  670. /* Save current */
  671. if (ndents > 0)
  672. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  673. goto begin;
  674. case SEL_RUN:
  675. run = xgetenv(env, run);
  676. exitcurses();
  677. spawn(run, NULL, path);
  678. initcurses();
  679. break;
  680. case SEL_RUNARG:
  681. run = xgetenv(env, run);
  682. exitcurses();
  683. spawn(run, dents[cur].name, path);
  684. initcurses();
  685. break;
  686. }
  687. /* Screensaver */
  688. if (idletimeout != 0 && idle == idletimeout) {
  689. idle = 0;
  690. exitcurses();
  691. spawn(idlecmd, NULL, NULL);
  692. initcurses();
  693. }
  694. }
  695. }
  696. void
  697. usage(char *argv0)
  698. {
  699. fprintf(stderr, "usage: %s [dir]\n", argv0);
  700. exit(1);
  701. }
  702. int
  703. main(int argc, char *argv[])
  704. {
  705. char cwd[PATH_MAX], *ipath;
  706. char *ifilter;
  707. if (argc > 2)
  708. usage(argv[0]);
  709. /* Confirm we are in a terminal */
  710. if (!isatty(0) || !isatty(1)) {
  711. fprintf(stderr, "stdin or stdout is not a tty\n");
  712. exit(1);
  713. }
  714. if (getuid() == 0)
  715. showhidden = 1;
  716. initfilter(showhidden, &ifilter);
  717. if (argv[1] != NULL) {
  718. ipath = argv[1];
  719. } else {
  720. ipath = getcwd(cwd, sizeof(cwd));
  721. if (ipath == NULL)
  722. ipath = "/";
  723. }
  724. signal(SIGINT, SIG_IGN);
  725. /* Test initial path */
  726. if (canopendir(ipath) == 0) {
  727. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  728. exit(1);
  729. }
  730. /* Set locale before curses setup */
  731. setlocale(LC_ALL, "");
  732. initcurses();
  733. browse(ipath, ifilter);
  734. exitcurses();
  735. exit(0);
  736. }