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.
 
 
 
 
 
 

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