My build of nnn with minor changes
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

758 lines
12 KiB

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