My build of nnn with minor changes
 
 
 
 
 
 

829 rindas
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 root case */
  430. if (strcmp(dir, "/") == 0)
  431. asprintf(&path, "/%s", name);
  432. else
  433. asprintf(&path, "%s/%s", dir, name);
  434. return path;
  435. }
  436. /* Return the position of the matching entry or 0 otherwise */
  437. int
  438. dentfind(struct entry *dents, int n, char *cwd, char *path)
  439. {
  440. int i;
  441. char *tmp;
  442. if (path == NULL)
  443. return 0;
  444. for (i = 0; i < n; i++) {
  445. tmp = makepath(cwd, dents[i].name);
  446. DPRINTF_S(path);
  447. DPRINTF_S(tmp);
  448. if (strcmp(tmp, path) == 0) {
  449. free(tmp);
  450. return i;
  451. }
  452. free(tmp);
  453. }
  454. return 0;
  455. }
  456. void
  457. pushhist(char *path)
  458. {
  459. struct history *hist;
  460. hist = xmalloc(sizeof(*hist));
  461. hist->path = xstrdup(path);
  462. SLIST_INSERT_HEAD(&histhead, hist, entry);
  463. }
  464. char *
  465. pophist(void)
  466. {
  467. struct history *hist;
  468. char *path;
  469. /* Recall history */
  470. hist = SLIST_FIRST(&histhead);
  471. if (hist != NULL) {
  472. path = hist->path;
  473. SLIST_REMOVE_HEAD(&histhead, entry);
  474. free(hist);
  475. } else {
  476. path = NULL;
  477. }
  478. return path;
  479. }
  480. void
  481. forgethist(void)
  482. {
  483. struct history *hist;
  484. while (SLIST_EMPTY(&histhead) == 0) {
  485. hist = SLIST_FIRST(&histhead);
  486. SLIST_REMOVE_HEAD(&histhead, entry);
  487. free(hist->path);
  488. free(hist);
  489. }
  490. }
  491. void
  492. browse(const char *ipath, const char *ifilter)
  493. {
  494. DIR *dirp;
  495. struct entry *dents;
  496. int i, n, cur;
  497. int r, ret, fd;
  498. char *path = xstrdup(ipath);
  499. char *filter = xstrdup(ifilter);
  500. regex_t filter_re;
  501. char *cwd, *newpath;
  502. struct stat sb;
  503. char *hpath;
  504. cur = 0;
  505. hpath = NULL;
  506. begin:
  507. /* Path and filter should be malloc(3)-ed strings at all times */
  508. n = 0;
  509. dents = NULL;
  510. dirp = opendir(path);
  511. if (dirp == NULL) {
  512. printwarn();
  513. goto nochange;
  514. }
  515. /* Search filter */
  516. r = setfilter(&filter_re, filter);
  517. if (r != 0)
  518. goto nochange;
  519. n = dentfill(dirp, &dents, visible, &filter_re);
  520. qsort(dents, n, sizeof(*dents), entrycmp);
  521. /* Find cur from history */
  522. cur = dentfind(dents, n, path, hpath);
  523. if (hpath != NULL) {
  524. free(hpath);
  525. hpath = NULL;
  526. }
  527. for (;;) {
  528. int nlines;
  529. int odd;
  530. char *name;
  531. char *bin;
  532. char *dir;
  533. char *tmp;
  534. regex_t re;
  535. redraw:
  536. nlines = MIN(LINES - 4, n);
  537. /* Clean screen */
  538. erase();
  539. DPRINTF_D(cur);
  540. DPRINTF_S(path);
  541. /* No text wrapping in cwd line */
  542. cwd = xmalloc(COLS * sizeof(char));
  543. strlcpy(cwd, path, COLS * sizeof(char));
  544. cwd[COLS - strlen(CWD) - 1] = '\0';
  545. printw(CWD "%s\n\n", cwd);
  546. /* Print listing */
  547. odd = ISODD(nlines);
  548. if (cur < nlines / 2) {
  549. for (i = 0; i < nlines; i++)
  550. printent(&dents[i], i == cur);
  551. } else if (cur >= n - nlines / 2) {
  552. for (i = n - nlines; i < n; i++)
  553. printent(&dents[i], i == cur);
  554. } else {
  555. for (i = cur - nlines / 2;
  556. i < cur + nlines / 2 + odd; i++)
  557. printent(&dents[i], i == cur);
  558. }
  559. nochange:
  560. ret = nextsel(&cur, n);
  561. switch (ret) {
  562. case SEL_QUIT:
  563. free(path);
  564. free(filter);
  565. forgethist();
  566. dentfree(dents, n);
  567. return;
  568. case SEL_BACK:
  569. /* There is no going back */
  570. if (strcmp(path, "/") == 0)
  571. goto nochange;
  572. if (canopendir(path) == 0) {
  573. printwarn();
  574. goto nochange;
  575. }
  576. dir = xdirname(path);
  577. free(path);
  578. path = dir;
  579. /* Reset filter */
  580. free(filter);
  581. filter = xstrdup(ifilter);
  582. /* Recall history */
  583. hpath = pophist();
  584. goto out;
  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(filter);
  619. filter = xstrdup(ifilter);
  620. /* Remember history */
  621. pushhist(path);
  622. cur = 0;
  623. goto out;
  624. case S_IFREG:
  625. bin = openwith(name);
  626. if (bin == NULL) {
  627. printmsg("No association");
  628. free(newpath);
  629. goto nochange;
  630. }
  631. exitcurses();
  632. spawn(bin, newpath, NULL);
  633. initcurses();
  634. free(newpath);
  635. goto redraw;
  636. default:
  637. printmsg("Unsupported file");
  638. goto nochange;
  639. }
  640. case SEL_FLTR:
  641. /* Read filter */
  642. printprompt("filter: ");
  643. tmp = readln();
  644. if (tmp == NULL) {
  645. clearprompt();
  646. goto nochange;
  647. }
  648. r = setfilter(&re, tmp);
  649. if (r != 0) {
  650. free(tmp);
  651. goto nochange;
  652. }
  653. free(filter);
  654. filter = tmp;
  655. filter_re = re;
  656. DPRINTF_S(filter);
  657. cur = 0;
  658. goto out;
  659. case SEL_SH:
  660. exitcurses();
  661. spawn("/bin/sh", NULL, path);
  662. initcurses();
  663. break;
  664. case SEL_CD:
  665. /* Read target dir */
  666. printprompt("chdir: ");
  667. tmp = readln();
  668. if (tmp == NULL) {
  669. clearprompt();
  670. goto nochange;
  671. }
  672. newpath = makepath(path, tmp);
  673. free(tmp);
  674. if (canopendir(newpath) == 0) {
  675. free(newpath);
  676. printwarn();
  677. goto nochange;
  678. }
  679. free(path);
  680. path = newpath;
  681. free(filter);
  682. filter = xstrdup(ifilter); /* Reset filter */
  683. forgethist();
  684. DPRINTF_S(path);
  685. cur = 0;
  686. goto out;
  687. }
  688. }
  689. out:
  690. dentfree(dents, n);
  691. /* Should never be null */
  692. r = closedir(dirp);
  693. if (r == -1)
  694. printerr(1, "closedir");
  695. goto begin;
  696. }
  697. int
  698. main(int argc, char *argv[])
  699. {
  700. char cwd[PATH_MAX], *ipath;
  701. char *ifilter;
  702. if (getuid() == 0)
  703. ifilter = ".*";
  704. else
  705. ifilter = "^[^.].*"; /* Hide dotfiles */
  706. if (argv[1] != NULL) {
  707. ipath = argv[1];
  708. } else {
  709. ipath = getcwd(cwd, sizeof(cwd));
  710. if (ipath == NULL)
  711. ipath = "/";
  712. }
  713. /* Test initial path */
  714. if (canopendir(ipath) == 0)
  715. printerr(1, ipath);
  716. /* Set locale before curses setup */
  717. setlocale(LC_ALL, "");
  718. initcurses();
  719. browse(ipath, ifilter);
  720. exitcurses();
  721. return 0;
  722. }