My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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