My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

888 lignes
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. memset(ln, 0, sizeof(ln));
  289. getnstr(ln, sizeof(ln) - 1);
  290. noecho();
  291. curs_set(FALSE);
  292. return strlen(ln) ? strdup(ln) : NULL;
  293. }
  294. /*
  295. * Read one key and modify the provided string accordingly.
  296. * Returns 0 when more input is expected and 1 on completion.
  297. */
  298. int
  299. readmore(char **str)
  300. {
  301. int c, ret = 0;
  302. int i;
  303. char *ln = *str;
  304. if (ln != NULL)
  305. i = strlen(ln);
  306. else
  307. i = 0;
  308. DPRINTF_D(i);
  309. curs_set(TRUE);
  310. c = getch();
  311. switch (c) {
  312. case KEY_ENTER:
  313. case '\r':
  314. ret = 1;
  315. break;
  316. case KEY_BACKSPACE:
  317. case CONTROL('H'):
  318. i--;
  319. if (i > 0) {
  320. ln = xrealloc(ln, (i + 1) * sizeof(*ln));
  321. ln[i] = '\0';
  322. } else {
  323. free(ln);
  324. ln = NULL;
  325. }
  326. break;
  327. default:
  328. i++;
  329. ln = xrealloc(ln, (i + 1) * sizeof(*ln));
  330. ln[i - 1] = c;
  331. ln[i] = '\0';
  332. }
  333. curs_set(FALSE);
  334. *str = ln;
  335. return ret;
  336. }
  337. int
  338. canopendir(char *path)
  339. {
  340. DIR *dirp;
  341. dirp = opendir(path);
  342. if (dirp == NULL)
  343. return 0;
  344. closedir(dirp);
  345. return 1;
  346. }
  347. void
  348. printent(struct entry *ent, int active)
  349. {
  350. char *name;
  351. unsigned int maxlen = COLS - strlen(CURSR) - 1;
  352. char cm = 0;
  353. /* Copy name locally */
  354. name = xstrdup(ent->name);
  355. if (S_ISDIR(ent->mode)) {
  356. cm = '/';
  357. maxlen--;
  358. } else if (S_ISLNK(ent->mode)) {
  359. cm = '@';
  360. maxlen--;
  361. } else if (S_ISSOCK(ent->mode)) {
  362. cm = '=';
  363. maxlen--;
  364. } else if (S_ISFIFO(ent->mode)) {
  365. cm = '|';
  366. maxlen--;
  367. } else if (ent->mode & S_IXUSR) {
  368. cm = '*';
  369. maxlen--;
  370. }
  371. /* No text wrapping in entries */
  372. if (strlen(name) > maxlen)
  373. name[maxlen] = '\0';
  374. if (cm == 0)
  375. printw("%s%s\n", active ? CURSR : EMPTY, name);
  376. else
  377. printw("%s%s%c\n", active ? CURSR : EMPTY, name, cm);
  378. free(name);
  379. }
  380. int
  381. dentfill(char *path, struct entry **dents,
  382. int (*filter)(regex_t *, char *), regex_t *re)
  383. {
  384. DIR *dirp;
  385. struct dirent *dp;
  386. struct stat sb;
  387. char *newpath;
  388. int r, n = 0;
  389. dirp = opendir(path);
  390. if (dirp == NULL)
  391. return 0;
  392. while ((dp = readdir(dirp)) != NULL) {
  393. /* Skip self and parent */
  394. if (strcmp(dp->d_name, ".") == 0
  395. || strcmp(dp->d_name, "..") == 0)
  396. continue;
  397. if (filter(re, dp->d_name) == 0)
  398. continue;
  399. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  400. (*dents)[n].name = xstrdup(dp->d_name);
  401. /* Get mode flags */
  402. newpath = makepath(path, dp->d_name);
  403. r = lstat(newpath, &sb);
  404. if (r == -1)
  405. printerr(1, "lstat");
  406. (*dents)[n].mode = sb.st_mode;
  407. (*dents)[n].t = sb.st_mtime;
  408. n++;
  409. }
  410. /* Should never be null */
  411. r = closedir(dirp);
  412. if (r == -1)
  413. printerr(1, "closedir");
  414. return n;
  415. }
  416. void
  417. dentfree(struct entry *dents, int n)
  418. {
  419. int i;
  420. for (i = 0; i < n; i++)
  421. free(dents[i].name);
  422. free(dents);
  423. }
  424. char *
  425. makepath(char *dir, char *name)
  426. {
  427. char path[PATH_MAX];
  428. /* Handle absolute path */
  429. if (name[0] == '/') {
  430. strlcpy(path, name, sizeof(path));
  431. } else {
  432. /* Handle root case */
  433. if (strcmp(dir, "/") == 0) {
  434. strlcpy(path, "/", sizeof(path));
  435. strlcat(path, name, sizeof(path));
  436. } else {
  437. strlcpy(path, dir, sizeof(path));
  438. strlcat(path, "/", sizeof(path));
  439. strlcat(path, name, sizeof(path));
  440. }
  441. }
  442. return xstrdup(path);
  443. }
  444. /* Return the position of the matching entry or 0 otherwise */
  445. int
  446. dentfind(struct entry *dents, int n, char *cwd, char *path)
  447. {
  448. int i;
  449. char *tmp;
  450. if (path == NULL)
  451. return 0;
  452. for (i = 0; i < n; i++) {
  453. tmp = makepath(cwd, dents[i].name);
  454. DPRINTF_S(path);
  455. DPRINTF_S(tmp);
  456. if (strcmp(tmp, path) == 0) {
  457. free(tmp);
  458. return i;
  459. }
  460. free(tmp);
  461. }
  462. return 0;
  463. }
  464. int
  465. populate(void)
  466. {
  467. regex_t re;
  468. int r;
  469. /* Can fail when permissions change while browsing */
  470. if (canopendir(path) == 0)
  471. return -1;
  472. /* Search filter */
  473. r = setfilter(&re, fltr);
  474. if (r != 0)
  475. return -1;
  476. dentfree(dents, n);
  477. n = 0;
  478. dents = NULL;
  479. n = dentfill(path, &dents, visible, &re);
  480. qsort(dents, n, sizeof(*dents), entrycmp);
  481. /* Find cur from history */
  482. cur = dentfind(dents, n, path, oldpath);
  483. free(oldpath);
  484. oldpath = NULL;
  485. return 0;
  486. }
  487. void
  488. redraw(void)
  489. {
  490. int nlines, odd;
  491. char *cwd;
  492. int i;
  493. nlines = MIN(LINES - 4, n);
  494. /* Clean screen */
  495. erase();
  496. /* Strip trailing slashes */
  497. for (i = strlen(path) - 1; i > 0; i--)
  498. if (path[i] == '/')
  499. path[i] = '\0';
  500. else
  501. break;
  502. DPRINTF_D(cur);
  503. DPRINTF_S(path);
  504. /* No text wrapping in cwd line */
  505. cwd = xmalloc(COLS * sizeof(char));
  506. strlcpy(cwd, path, COLS * sizeof(char));
  507. cwd[COLS - strlen(CWD) - 1] = '\0';
  508. printw(CWD "%s\n\n", cwd);
  509. /* Print listing */
  510. odd = ISODD(nlines);
  511. if (cur < nlines / 2) {
  512. for (i = 0; i < nlines; i++)
  513. printent(&dents[i], i == cur);
  514. } else if (cur >= n - nlines / 2) {
  515. for (i = n - nlines; i < n; i++)
  516. printent(&dents[i], i == cur);
  517. } else {
  518. for (i = cur - nlines / 2;
  519. i < cur + nlines / 2 + odd; i++)
  520. printent(&dents[i], i == cur);
  521. }
  522. }
  523. void
  524. browse(const char *ipath, const char *ifilter)
  525. {
  526. int r, fd;
  527. regex_t re;
  528. char *newpath;
  529. struct stat sb;
  530. char *name, *bin, *dir, *tmp, *run;
  531. int nowtyping = 0;
  532. oldpath = NULL;
  533. path = xstrdup(ipath);
  534. fltr = xstrdup(ifilter);
  535. begin:
  536. /* Path and filter should be malloc(3)-ed strings at all times */
  537. r = populate();
  538. if (r == -1) {
  539. if (!nowtyping) {
  540. printwarn();
  541. goto nochange;
  542. }
  543. }
  544. for (;;) {
  545. redraw();
  546. /* Handle filter-as-you-type mode */
  547. if (nowtyping)
  548. goto moretyping;
  549. nochange:
  550. switch (nextsel(&run)) {
  551. case SEL_QUIT:
  552. free(path);
  553. free(fltr);
  554. dentfree(dents, n);
  555. return;
  556. case SEL_BACK:
  557. /* There is no going back */
  558. if (strcmp(path, "/") == 0 ||
  559. strcmp(path, ".") == 0 ||
  560. strchr(path, '/') == NULL)
  561. goto nochange;
  562. dir = xdirname(path);
  563. if (canopendir(dir) == 0) {
  564. free(dir);
  565. printwarn();
  566. goto nochange;
  567. }
  568. /* Save history */
  569. oldpath = path;
  570. path = dir;
  571. /* Reset filter */
  572. free(fltr);
  573. fltr = xstrdup(ifilter);
  574. goto begin;
  575. case SEL_GOIN:
  576. /* Cannot descend in empty directories */
  577. if (n == 0)
  578. goto nochange;
  579. name = dents[cur].name;
  580. newpath = makepath(path, name);
  581. DPRINTF_S(newpath);
  582. /* Get path info */
  583. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  584. if (fd == -1) {
  585. printwarn();
  586. free(newpath);
  587. goto nochange;
  588. }
  589. r = fstat(fd, &sb);
  590. if (r == -1) {
  591. printwarn();
  592. close(fd);
  593. free(newpath);
  594. goto nochange;
  595. }
  596. close(fd);
  597. DPRINTF_U(sb.st_mode);
  598. switch (sb.st_mode & S_IFMT) {
  599. case S_IFDIR:
  600. if (canopendir(newpath) == 0) {
  601. printwarn();
  602. free(newpath);
  603. goto nochange;
  604. }
  605. free(path);
  606. path = newpath;
  607. /* Reset filter */
  608. free(fltr);
  609. fltr = xstrdup(ifilter);
  610. goto begin;
  611. case S_IFREG:
  612. bin = openwith(newpath);
  613. if (bin == NULL) {
  614. printmsg("No association");
  615. free(newpath);
  616. goto nochange;
  617. }
  618. exitcurses();
  619. spawn(bin, newpath, NULL);
  620. initcurses();
  621. free(newpath);
  622. continue;
  623. default:
  624. printmsg("Unsupported file");
  625. goto nochange;
  626. }
  627. case SEL_FLTR:
  628. /* Read filter */
  629. printprompt("filter: ");
  630. tmp = readln();
  631. if (tmp == NULL)
  632. tmp = xstrdup(ifilter);
  633. /* Check and report regex errors */
  634. r = setfilter(&re, tmp);
  635. if (r != 0) {
  636. free(tmp);
  637. goto nochange;
  638. }
  639. free(fltr);
  640. fltr = tmp;
  641. DPRINTF_S(fltr);
  642. /* Save current */
  643. if (n > 0)
  644. oldpath = makepath(path, dents[cur].name);
  645. goto begin;
  646. case SEL_TYPE:
  647. nowtyping = 1;
  648. tmp = NULL;
  649. moretyping:
  650. printprompt("type: ");
  651. if (tmp != NULL)
  652. printw("%s", tmp);
  653. r = readmore(&tmp);
  654. DPRINTF_D(r);
  655. DPRINTF_S(tmp);
  656. if (r == 1)
  657. nowtyping = 0;
  658. /* Check regex errors */
  659. if (tmp != NULL) {
  660. r = setfilter(&re, tmp);
  661. if (r != 0)
  662. if (nowtyping) {
  663. goto moretyping;
  664. } else {
  665. free(tmp);
  666. goto nochange;
  667. }
  668. }
  669. /* Copy or reset filter */
  670. free(fltr);
  671. if (tmp != NULL)
  672. fltr = xstrdup(tmp);
  673. else
  674. fltr = xstrdup(ifilter);
  675. /* Save current */
  676. if (n > 0)
  677. oldpath = makepath(path, dents[cur].name);
  678. if (!nowtyping)
  679. free(tmp);
  680. goto begin;
  681. case SEL_NEXT:
  682. if (cur < n - 1)
  683. cur++;
  684. break;
  685. case SEL_PREV:
  686. if (cur > 0)
  687. cur--;
  688. break;
  689. case SEL_PGDN:
  690. if (cur < n - 1)
  691. cur += MIN((LINES - 4) / 2, n - 1 - cur);
  692. break;
  693. case SEL_PGUP:
  694. if (cur > 0)
  695. cur -= MIN((LINES - 4) / 2, cur);
  696. break;
  697. case SEL_HOME:
  698. cur = 0;
  699. break;
  700. case SEL_END:
  701. cur = n - 1;
  702. break;
  703. case SEL_CD:
  704. /* Read target dir */
  705. printprompt("chdir: ");
  706. tmp = readln();
  707. if (tmp == NULL) {
  708. clearprompt();
  709. goto nochange;
  710. }
  711. newpath = makepath(path, tmp);
  712. free(tmp);
  713. if (canopendir(newpath) == 0) {
  714. free(newpath);
  715. printwarn();
  716. goto nochange;
  717. }
  718. free(path);
  719. path = newpath;
  720. free(fltr);
  721. fltr = xstrdup(ifilter); /* Reset filter */
  722. DPRINTF_S(path);
  723. goto begin;
  724. case SEL_MTIME:
  725. mtimeorder = !mtimeorder;
  726. /* Save current */
  727. if (n > 0)
  728. oldpath = makepath(path, dents[cur].name);
  729. goto begin;
  730. case SEL_REDRAW:
  731. /* Save current */
  732. if (n > 0)
  733. oldpath = makepath(path, dents[cur].name);
  734. goto begin;
  735. case SEL_RUN:
  736. exitcurses();
  737. spawn(run, NULL, path);
  738. initcurses();
  739. break;
  740. case SEL_RUNARG:
  741. name = dents[cur].name;
  742. exitcurses();
  743. spawn(run, name, path);
  744. initcurses();
  745. break;
  746. }
  747. }
  748. }
  749. int
  750. main(int argc, char *argv[])
  751. {
  752. char cwd[PATH_MAX], *ipath;
  753. char *ifilter;
  754. /* Confirm we are in a terminal */
  755. if (!isatty(STDIN_FILENO))
  756. printerr(1, "isatty");
  757. if (getuid() == 0)
  758. ifilter = ".";
  759. else
  760. ifilter = "^[^.]"; /* Hide dotfiles */
  761. if (argv[1] != NULL) {
  762. ipath = argv[1];
  763. } else {
  764. ipath = getcwd(cwd, sizeof(cwd));
  765. if (ipath == NULL)
  766. ipath = "/";
  767. }
  768. signal(SIGINT, SIG_IGN);
  769. /* Test initial path */
  770. if (canopendir(ipath) == 0)
  771. printerr(1, ipath);
  772. /* Set locale before curses setup */
  773. setlocale(LC_ALL, "");
  774. initcurses();
  775. browse(ipath, ifilter);
  776. exitcurses();
  777. return 0;
  778. }