My build of nnn with minor changes
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

909 wiersze
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. dir = xdirname(path);
  594. if (canopendir(dir) == 0) {
  595. free(dir);
  596. printwarn();
  597. goto nochange;
  598. }
  599. /* Save history */
  600. oldpath = path;
  601. path = dir;
  602. /* Reset filter */
  603. free(fltr);
  604. fltr = xstrdup(ifilter);
  605. goto begin;
  606. case SEL_GOIN:
  607. /* Cannot descend in empty directories */
  608. if (n == 0)
  609. goto nochange;
  610. name = dents[cur].name;
  611. newpath = makepath(path, name);
  612. DPRINTF_S(newpath);
  613. /* Get path info */
  614. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  615. if (fd == -1) {
  616. printwarn();
  617. free(newpath);
  618. goto nochange;
  619. }
  620. r = fstat(fd, &sb);
  621. if (r == -1) {
  622. printwarn();
  623. close(fd);
  624. free(newpath);
  625. goto nochange;
  626. }
  627. close(fd);
  628. DPRINTF_U(sb.st_mode);
  629. switch (sb.st_mode & S_IFMT) {
  630. case S_IFDIR:
  631. if (canopendir(newpath) == 0) {
  632. printwarn();
  633. free(newpath);
  634. goto nochange;
  635. }
  636. free(path);
  637. path = newpath;
  638. /* Reset filter */
  639. free(fltr);
  640. fltr = xstrdup(ifilter);
  641. goto begin;
  642. case S_IFREG:
  643. bin = openwith(newpath);
  644. if (bin == NULL) {
  645. printmsg("No association");
  646. free(newpath);
  647. goto nochange;
  648. }
  649. exitcurses();
  650. spawn(bin, newpath, NULL);
  651. initcurses();
  652. free(newpath);
  653. continue;
  654. default:
  655. printmsg("Unsupported file");
  656. goto nochange;
  657. }
  658. case SEL_FLTR:
  659. /* Read filter */
  660. printprompt("filter: ");
  661. tmp = readln();
  662. if (tmp == NULL)
  663. tmp = xstrdup(ifilter);
  664. /* Check and report regex errors */
  665. r = setfilter(&re, tmp);
  666. if (r != 0) {
  667. free(tmp);
  668. goto nochange;
  669. }
  670. free(fltr);
  671. fltr = tmp;
  672. DPRINTF_S(fltr);
  673. /* Save current */
  674. if (n > 0)
  675. oldpath = makepath(path, dents[cur].name);
  676. goto begin;
  677. case SEL_TYPE:
  678. nowtyping = 1;
  679. tmp = NULL;
  680. moretyping:
  681. printprompt("type: ");
  682. if (tmp != NULL)
  683. printw("%s", tmp);
  684. r = readmore(&tmp);
  685. DPRINTF_D(r);
  686. DPRINTF_S(tmp);
  687. if (r == 1)
  688. nowtyping = 0;
  689. /* Check regex errors */
  690. if (tmp != NULL) {
  691. r = setfilter(&re, tmp);
  692. if (r != 0)
  693. if (nowtyping) {
  694. goto moretyping;
  695. } else {
  696. free(tmp);
  697. goto nochange;
  698. }
  699. }
  700. /* Copy or reset filter */
  701. free(fltr);
  702. if (tmp != NULL)
  703. fltr = xstrdup(tmp);
  704. else
  705. fltr = xstrdup(ifilter);
  706. /* Save current */
  707. if (n > 0)
  708. oldpath = makepath(path, dents[cur].name);
  709. if (!nowtyping)
  710. free(tmp);
  711. goto begin;
  712. case SEL_NEXT:
  713. if (cur < n - 1)
  714. cur++;
  715. break;
  716. case SEL_PREV:
  717. if (cur > 0)
  718. cur--;
  719. break;
  720. case SEL_PGDN:
  721. if (cur < n - 1)
  722. cur += MIN((LINES - 4) / 2, n - 1 - cur);
  723. break;
  724. case SEL_PGUP:
  725. if (cur > 0)
  726. cur -= MIN((LINES - 4) / 2, cur);
  727. break;
  728. case SEL_CD:
  729. /* Read target dir */
  730. printprompt("chdir: ");
  731. tmp = readln();
  732. if (tmp == NULL) {
  733. clearprompt();
  734. goto nochange;
  735. }
  736. newpath = makepath(path, tmp);
  737. free(tmp);
  738. if (canopendir(newpath) == 0) {
  739. free(newpath);
  740. printwarn();
  741. goto nochange;
  742. }
  743. free(path);
  744. path = newpath;
  745. free(fltr);
  746. fltr = xstrdup(ifilter); /* Reset filter */
  747. DPRINTF_S(path);
  748. goto begin;
  749. case SEL_MTIME:
  750. mtimeorder = !mtimeorder;
  751. goto begin;
  752. case SEL_REDRAW:
  753. goto begin;
  754. case SEL_RUN:
  755. exitcurses();
  756. spawn(run, NULL, path);
  757. initcurses();
  758. break;
  759. case SEL_RUNARG:
  760. name = dents[cur].name;
  761. exitcurses();
  762. spawn(run, name, path);
  763. initcurses();
  764. break;
  765. }
  766. }
  767. }
  768. int
  769. main(int argc, char *argv[])
  770. {
  771. char cwd[PATH_MAX], *ipath;
  772. char *ifilter;
  773. /* Confirm we are in a terminal */
  774. if (!isatty(STDIN_FILENO))
  775. printerr(1, "isatty");
  776. if (getuid() == 0)
  777. ifilter = ".";
  778. else
  779. ifilter = "^[^.]"; /* Hide dotfiles */
  780. if (argv[1] != NULL) {
  781. ipath = argv[1];
  782. } else {
  783. ipath = getcwd(cwd, sizeof(cwd));
  784. if (ipath == NULL)
  785. ipath = "/";
  786. }
  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. }