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.
 
 
 
 
 
 

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