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.
 
 
 
 
 
 

887 line
15 KiB

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