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.
 
 
 
 
 
 

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