My build of nnn with minor changes
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

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