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.
 
 
 
 
 
 

836 line
13 KiB

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