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.
 
 
 
 
 
 

827 line
14 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. int
  212. visible(regex_t *regex, char *file)
  213. {
  214. return regexec(regex, file, 0, NULL, 0) == 0;
  215. }
  216. int
  217. entrycmp(const void *va, const void *vb)
  218. {
  219. const struct entry *a = va, *b = vb;
  220. if (mtimeorder)
  221. return b->t - a->t;
  222. return strcmp(a->name, b->name);
  223. }
  224. void
  225. initcurses(void)
  226. {
  227. char *term;
  228. if (initscr() == NULL) {
  229. term = getenv("TERM");
  230. if (term != NULL)
  231. fprintf(stderr, "error opening terminal: %s\n", term);
  232. else
  233. fprintf(stderr, "failed to initialize curses\n");
  234. exit(1);
  235. }
  236. cbreak();
  237. noecho();
  238. nonl();
  239. intrflush(stdscr, FALSE);
  240. keypad(stdscr, TRUE);
  241. curs_set(FALSE); /* Hide cursor */
  242. timeout(1000); /* One second */
  243. }
  244. void
  245. exitcurses(void)
  246. {
  247. endwin(); /* Restore terminal */
  248. }
  249. /* Messages show up at the bottom */
  250. void
  251. printmsg(char *msg)
  252. {
  253. move(LINES - 1, 0);
  254. printw("%s\n", msg);
  255. }
  256. /* Display warning as a message */
  257. void
  258. printwarn(void)
  259. {
  260. printmsg(strerror(errno));
  261. }
  262. /* Kill curses and display error before exiting */
  263. void
  264. printerr(int ret, char *prefix)
  265. {
  266. exitcurses();
  267. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  268. exit(ret);
  269. }
  270. /* Clear the last line */
  271. void
  272. clearprompt(void)
  273. {
  274. printmsg("");
  275. }
  276. /* Print prompt on the last line */
  277. void
  278. printprompt(char *str)
  279. {
  280. clearprompt();
  281. printw(str);
  282. }
  283. /* Returns SEL_* if key is bound and 0 otherwise.
  284. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}) */
  285. int
  286. nextsel(char **run, char **env)
  287. {
  288. int c, i;
  289. c = getch();
  290. if (c == -1)
  291. idle++;
  292. else
  293. idle = 0;
  294. for (i = 0; i < LEN(bindings); i++)
  295. if (c == bindings[i].sym) {
  296. *run = bindings[i].run;
  297. *env = bindings[i].env;
  298. return bindings[i].act;
  299. }
  300. return 0;
  301. }
  302. char *
  303. readln(void)
  304. {
  305. static char ln[LINE_MAX];
  306. timeout(-1);
  307. echo();
  308. curs_set(TRUE);
  309. memset(ln, 0, sizeof(ln));
  310. wgetnstr(stdscr, ln, sizeof(ln) - 1);
  311. noecho();
  312. curs_set(FALSE);
  313. timeout(1000);
  314. return ln[0] ? ln : NULL;
  315. }
  316. int
  317. canopendir(char *path)
  318. {
  319. DIR *dirp;
  320. dirp = opendir(path);
  321. if (dirp == NULL)
  322. return 0;
  323. closedir(dirp);
  324. return 1;
  325. }
  326. char *
  327. mkpath(char *dir, char *name, char *out, size_t n)
  328. {
  329. /* Handle absolute path */
  330. if (name[0] == '/') {
  331. strlcpy(out, name, n);
  332. } else {
  333. /* Handle root case */
  334. if (strcmp(dir, "/") == 0) {
  335. strlcpy(out, "/", n);
  336. strlcat(out, name, n);
  337. } else {
  338. strlcpy(out, dir, n);
  339. strlcat(out, "/", n);
  340. strlcat(out, name, n);
  341. }
  342. }
  343. return out;
  344. }
  345. void
  346. printent(struct entry *ent, int active)
  347. {
  348. char name[PATH_MAX];
  349. unsigned int maxlen = COLS - strlen(CURSR) - 1;
  350. char cm = 0;
  351. /* Copy name locally */
  352. strlcpy(name, ent->name, sizeof(name));
  353. if (S_ISDIR(ent->mode)) {
  354. cm = '/';
  355. maxlen--;
  356. } else if (S_ISLNK(ent->mode)) {
  357. cm = '@';
  358. maxlen--;
  359. } else if (S_ISSOCK(ent->mode)) {
  360. cm = '=';
  361. maxlen--;
  362. } else if (S_ISFIFO(ent->mode)) {
  363. cm = '|';
  364. maxlen--;
  365. } else if (ent->mode & S_IXUSR) {
  366. cm = '*';
  367. maxlen--;
  368. }
  369. /* No text wrapping in entries */
  370. if (strlen(name) > maxlen)
  371. name[maxlen] = '\0';
  372. if (cm == 0)
  373. printw("%s%s\n", active ? CURSR : EMPTY, name);
  374. else
  375. printw("%s%s%c\n", active ? CURSR : EMPTY, name, cm);
  376. }
  377. int
  378. dentfill(char *path, struct entry **dents,
  379. int (*filter)(regex_t *, char *), regex_t *re)
  380. {
  381. char newpath[PATH_MAX];
  382. DIR *dirp;
  383. struct dirent *dp;
  384. struct stat sb;
  385. int r, n = 0;
  386. dirp = opendir(path);
  387. if (dirp == NULL)
  388. return 0;
  389. while ((dp = readdir(dirp)) != NULL) {
  390. /* Skip self and parent */
  391. if (strcmp(dp->d_name, ".") == 0 ||
  392. strcmp(dp->d_name, "..") == 0)
  393. continue;
  394. if (filter(re, dp->d_name) == 0)
  395. continue;
  396. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  397. strlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  398. /* Get mode flags */
  399. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  400. r = lstat(newpath, &sb);
  401. if (r == -1)
  402. printerr(1, "lstat");
  403. (*dents)[n].mode = sb.st_mode;
  404. (*dents)[n].t = sb.st_mtime;
  405. n++;
  406. }
  407. /* Should never be null */
  408. r = closedir(dirp);
  409. if (r == -1)
  410. printerr(1, "closedir");
  411. return n;
  412. }
  413. void
  414. dentfree(struct entry *dents)
  415. {
  416. free(dents);
  417. }
  418. /* Return the position of the matching entry or 0 otherwise */
  419. int
  420. dentfind(struct entry *dents, int n, char *cwd, char *path)
  421. {
  422. char tmp[PATH_MAX];
  423. int i;
  424. if (path == NULL)
  425. return 0;
  426. for (i = 0; i < n; i++) {
  427. mkpath(cwd, dents[i].name, tmp, sizeof(tmp));
  428. DPRINTF_S(path);
  429. DPRINTF_S(tmp);
  430. if (strcmp(tmp, path) == 0)
  431. return i;
  432. }
  433. return 0;
  434. }
  435. int
  436. populate(char *path, char *oldpath, char *fltr)
  437. {
  438. regex_t re;
  439. int r;
  440. /* Can fail when permissions change while browsing */
  441. if (canopendir(path) == 0)
  442. return -1;
  443. /* Search filter */
  444. r = setfilter(&re, fltr);
  445. if (r != 0)
  446. return -1;
  447. dentfree(dents);
  448. ndents = 0;
  449. dents = NULL;
  450. ndents = dentfill(path, &dents, visible, &re);
  451. qsort(dents, ndents, sizeof(*dents), entrycmp);
  452. /* Find cur from history */
  453. cur = dentfind(dents, ndents, path, oldpath);
  454. return 0;
  455. }
  456. void
  457. redraw(char *path)
  458. {
  459. char cwd[PATH_MAX], cwdresolved[PATH_MAX];
  460. size_t ncols;
  461. int nlines, odd;
  462. int i;
  463. nlines = MIN(LINES - 4, ndents);
  464. /* Clean screen */
  465. erase();
  466. /* Strip trailing slashes */
  467. for (i = strlen(path) - 1; i > 0; i--)
  468. if (path[i] == '/')
  469. path[i] = '\0';
  470. else
  471. break;
  472. DPRINTF_D(cur);
  473. DPRINTF_S(path);
  474. /* No text wrapping in cwd line */
  475. ncols = COLS;
  476. if (ncols > PATH_MAX)
  477. ncols = PATH_MAX;
  478. strlcpy(cwd, path, ncols);
  479. cwd[ncols - strlen(CWD) - 1] = '\0';
  480. realpath(cwd, cwdresolved);
  481. printw(CWD "%s\n\n", cwdresolved);
  482. /* Print listing */
  483. odd = ISODD(nlines);
  484. if (cur < nlines / 2) {
  485. for (i = 0; i < nlines; i++)
  486. printent(&dents[i], i == cur);
  487. } else if (cur >= ndents - nlines / 2) {
  488. for (i = ndents - nlines; i < ndents; i++)
  489. printent(&dents[i], i == cur);
  490. } else {
  491. for (i = cur - nlines / 2;
  492. i < cur + nlines / 2 + odd; i++)
  493. printent(&dents[i], i == cur);
  494. }
  495. }
  496. void
  497. browse(char *ipath, char *ifilter)
  498. {
  499. char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  500. char fltr[LINE_MAX];
  501. char *bin, *dir, *tmp, *run, *env;
  502. struct stat sb;
  503. regex_t re;
  504. int r, fd;
  505. strlcpy(path, ipath, sizeof(path));
  506. strlcpy(fltr, ifilter, sizeof(fltr));
  507. oldpath[0] = '\0';
  508. begin:
  509. r = populate(path, oldpath, fltr);
  510. if (r == -1) {
  511. printwarn();
  512. goto nochange;
  513. }
  514. for (;;) {
  515. redraw(path);
  516. nochange:
  517. switch (nextsel(&run, &env)) {
  518. case SEL_QUIT:
  519. dentfree(dents);
  520. return;
  521. case SEL_BACK:
  522. /* There is no going back */
  523. if (strcmp(path, "/") == 0 ||
  524. strcmp(path, ".") == 0 ||
  525. strchr(path, '/') == NULL)
  526. goto nochange;
  527. dir = xdirname(path);
  528. if (canopendir(dir) == 0) {
  529. printwarn();
  530. goto nochange;
  531. }
  532. /* Save history */
  533. strlcpy(oldpath, path, sizeof(oldpath));
  534. strlcpy(path, dir, sizeof(path));
  535. /* Reset filter */
  536. strlcpy(fltr, ifilter, sizeof(fltr));
  537. goto begin;
  538. case SEL_GOIN:
  539. /* Cannot descend in empty directories */
  540. if (ndents == 0)
  541. goto nochange;
  542. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  543. DPRINTF_S(newpath);
  544. /* Get path info */
  545. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  546. if (fd == -1) {
  547. printwarn();
  548. goto nochange;
  549. }
  550. r = fstat(fd, &sb);
  551. if (r == -1) {
  552. printwarn();
  553. close(fd);
  554. goto nochange;
  555. }
  556. close(fd);
  557. DPRINTF_U(sb.st_mode);
  558. switch (sb.st_mode & S_IFMT) {
  559. case S_IFDIR:
  560. if (canopendir(newpath) == 0) {
  561. printwarn();
  562. goto nochange;
  563. }
  564. strlcpy(path, newpath, sizeof(path));
  565. /* Reset filter */
  566. strlcpy(fltr, ifilter, sizeof(fltr));
  567. goto begin;
  568. case S_IFREG:
  569. bin = openwith(newpath);
  570. if (bin == NULL) {
  571. printmsg("No association");
  572. goto nochange;
  573. }
  574. exitcurses();
  575. spawn(bin, newpath, NULL);
  576. initcurses();
  577. continue;
  578. default:
  579. printmsg("Unsupported file");
  580. goto nochange;
  581. }
  582. case SEL_FLTR:
  583. /* Read filter */
  584. printprompt("filter: ");
  585. tmp = readln();
  586. if (tmp == NULL)
  587. tmp = ifilter;
  588. /* Check and report regex errors */
  589. r = setfilter(&re, tmp);
  590. if (r != 0)
  591. goto nochange;
  592. strlcpy(fltr, tmp, sizeof(fltr));
  593. DPRINTF_S(fltr);
  594. /* Save current */
  595. if (ndents > 0)
  596. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  597. goto begin;
  598. case SEL_NEXT:
  599. if (cur < ndents - 1)
  600. cur++;
  601. break;
  602. case SEL_PREV:
  603. if (cur > 0)
  604. cur--;
  605. break;
  606. case SEL_PGDN:
  607. if (cur < ndents - 1)
  608. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  609. break;
  610. case SEL_PGUP:
  611. if (cur > 0)
  612. cur -= MIN((LINES - 4) / 2, cur);
  613. break;
  614. case SEL_HOME:
  615. cur = 0;
  616. break;
  617. case SEL_END:
  618. cur = ndents - 1;
  619. break;
  620. case SEL_CD:
  621. /* Read target dir */
  622. printprompt("chdir: ");
  623. tmp = readln();
  624. if (tmp == NULL) {
  625. clearprompt();
  626. goto nochange;
  627. }
  628. mkpath(path, tmp, newpath, sizeof(newpath));
  629. if (canopendir(newpath) == 0) {
  630. printwarn();
  631. goto nochange;
  632. }
  633. strlcpy(path, newpath, sizeof(path));
  634. /* Reset filter */
  635. strlcpy(fltr, ifilter, sizeof(fltr))
  636. DPRINTF_S(path);
  637. goto begin;
  638. case SEL_CDHOME:
  639. tmp = getenv("HOME");
  640. if (tmp == NULL) {
  641. clearprompt();
  642. goto nochange;
  643. }
  644. if (canopendir(tmp) == 0) {
  645. printwarn();
  646. goto nochange;
  647. }
  648. strlcpy(path, tmp, sizeof(path));
  649. /* Reset filter */
  650. strlcpy(fltr, ifilter, sizeof(fltr));
  651. DPRINTF_S(path);
  652. goto begin;
  653. case SEL_TOGGLEDOT:
  654. showhidden ^= 1;
  655. ifilter = showhidden ? "." : "^[^.]";
  656. strlcpy(fltr, ifilter, sizeof(fltr));
  657. goto begin;
  658. case SEL_MTIME:
  659. mtimeorder = !mtimeorder;
  660. /* Save current */
  661. if (ndents > 0)
  662. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  663. goto begin;
  664. case SEL_REDRAW:
  665. /* Save current */
  666. if (ndents > 0)
  667. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  668. goto begin;
  669. case SEL_RUN:
  670. run = xgetenv(env, run);
  671. exitcurses();
  672. spawn(run, NULL, path);
  673. initcurses();
  674. break;
  675. case SEL_RUNARG:
  676. run = xgetenv(env, run);
  677. exitcurses();
  678. spawn(run, dents[cur].name, path);
  679. initcurses();
  680. break;
  681. }
  682. /* Screensaver */
  683. if (idletimeout != 0 && idle == idletimeout) {
  684. idle = 0;
  685. exitcurses();
  686. spawn(idlecmd, NULL, NULL);
  687. initcurses();
  688. }
  689. }
  690. }
  691. void
  692. usage(char *argv0)
  693. {
  694. fprintf(stderr, "usage: %s [dir]\n", argv0);
  695. exit(1);
  696. }
  697. int
  698. main(int argc, char *argv[])
  699. {
  700. char cwd[PATH_MAX], *ipath;
  701. char *ifilter;
  702. if (argc > 2)
  703. usage(argv[0]);
  704. /* Confirm we are in a terminal */
  705. if (!isatty(0) || !isatty(1)) {
  706. fprintf(stderr, "stdin or stdout is not a tty\n");
  707. exit(1);
  708. }
  709. if (getuid() == 0)
  710. showhidden = 1;
  711. if (showhidden)
  712. ifilter = ".";
  713. else
  714. ifilter = "^[^.]";
  715. if (argv[1] != NULL) {
  716. ipath = argv[1];
  717. } else {
  718. ipath = getcwd(cwd, sizeof(cwd));
  719. if (ipath == NULL)
  720. ipath = "/";
  721. }
  722. signal(SIGINT, SIG_IGN);
  723. /* Test initial path */
  724. if (canopendir(ipath) == 0) {
  725. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  726. exit(1);
  727. }
  728. /* Set locale before curses setup */
  729. setlocale(LC_ALL, "");
  730. initcurses();
  731. browse(ipath, ifilter);
  732. exitcurses();
  733. exit(0);
  734. }