My build of nnn with minor changes
 
 
 
 
 
 

813 строки
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;
  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. free(hpath);
  525. hpath = NULL;
  526. for (;;) {
  527. int nlines;
  528. int odd;
  529. char *name;
  530. char *bin;
  531. char *dir;
  532. char *tmp;
  533. regex_t re;
  534. redraw:
  535. nlines = MIN(LINES - 4, n);
  536. /* Clean screen */
  537. erase();
  538. DPRINTF_D(cur);
  539. DPRINTF_S(path);
  540. /* No text wrapping in cwd line */
  541. cwd = xmalloc(COLS * sizeof(char));
  542. strlcpy(cwd, path, COLS * sizeof(char));
  543. cwd[COLS - strlen(CWD) - 1] = '\0';
  544. printw(CWD "%s\n\n", cwd);
  545. /* Print listing */
  546. odd = ISODD(nlines);
  547. if (cur < nlines / 2) {
  548. for (i = 0; i < nlines; i++)
  549. printent(&dents[i], i == cur);
  550. } else if (cur >= n - nlines / 2) {
  551. for (i = n - nlines; i < n; i++)
  552. printent(&dents[i], i == cur);
  553. } else {
  554. for (i = cur - nlines / 2;
  555. i < cur + nlines / 2 + odd; i++)
  556. printent(&dents[i], i == cur);
  557. }
  558. nochange:
  559. ret = nextsel(&cur, n);
  560. switch (ret) {
  561. case SEL_QUIT:
  562. free(path);
  563. free(filter);
  564. forgethist();
  565. dentfree(dents, n);
  566. return;
  567. case SEL_BACK:
  568. /* There is no going back */
  569. if (strcmp(path, "/") == 0)
  570. goto nochange;
  571. if (canopendir(path) == 0) {
  572. printwarn();
  573. goto nochange;
  574. }
  575. dir = xdirname(path);
  576. free(path);
  577. path = dir;
  578. /* Reset filter */
  579. free(filter);
  580. filter = xstrdup(ifilter);
  581. /* Recall history */
  582. hpath = pophist();
  583. goto out;
  584. case SEL_GOIN:
  585. /* Cannot descend in empty directories */
  586. if (n == 0)
  587. goto nochange;
  588. name = dents[cur].name;
  589. DPRINTF_S(name);
  590. /* Get path info */
  591. r = fstatat(dirfd(dirp), name, &sb, 0);
  592. if (r == -1) {
  593. printwarn();
  594. goto nochange;
  595. }
  596. DPRINTF_U(sb.st_mode);
  597. switch (sb.st_mode & S_IFMT) {
  598. case S_IFDIR:
  599. if (canopendir(path) == 0) {
  600. printwarn();
  601. goto nochange;
  602. }
  603. free(path);
  604. path = xrealpath(name);
  605. /* Reset filter */
  606. free(filter);
  607. filter = xstrdup(ifilter);
  608. /* Remember history */
  609. pushhist(path);
  610. cur = 0;
  611. goto out;
  612. case S_IFREG:
  613. bin = openwith(name);
  614. if (bin == NULL) {
  615. printmsg("No association");
  616. goto nochange;
  617. }
  618. exitcurses();
  619. spawn(bin, name);
  620. initcurses();
  621. goto redraw;
  622. default:
  623. printmsg("Unsupported file");
  624. goto nochange;
  625. }
  626. case SEL_FLTR:
  627. /* Read filter */
  628. printprompt("filter: ");
  629. tmp = readln();
  630. if (tmp == NULL) {
  631. clearprompt();
  632. goto nochange;
  633. }
  634. r = setfilter(&re, tmp);
  635. if (r != 0) {
  636. free(tmp);
  637. goto nochange;
  638. }
  639. free(filter);
  640. filter = tmp;
  641. filter_re = re;
  642. DPRINTF_S(filter);
  643. cur = 0;
  644. goto out;
  645. case SEL_SH:
  646. exitcurses();
  647. spawn("/bin/sh", NULL);
  648. initcurses();
  649. break;
  650. case SEL_CD:
  651. /* Read target dir */
  652. printprompt("chdir: ");
  653. tmp = readln();
  654. if (tmp == NULL) {
  655. clearprompt();
  656. goto nochange;
  657. }
  658. if (canopendir(tmp) == 0) {
  659. printwarn();
  660. goto nochange;
  661. }
  662. free(path);
  663. path = xrealpath(tmp);
  664. free(tmp);
  665. free(filter);
  666. filter = xstrdup(ifilter); /* Reset filter */
  667. forgethist();
  668. DPRINTF_S(path);
  669. cur = 0;
  670. goto out;
  671. }
  672. }
  673. out:
  674. dentfree(dents, n);
  675. /* Should never be null */
  676. r = closedir(dirp);
  677. if (r == -1)
  678. printerr(1, "closedir");
  679. goto begin;
  680. }
  681. int
  682. main(int argc, char *argv[])
  683. {
  684. char cwd[PATH_MAX], *ipath;
  685. char *ifilter;
  686. if (getuid() == 0)
  687. ifilter = ".*";
  688. else
  689. ifilter = "^[^.].*"; /* Hide dotfiles */
  690. if (argv[1] != NULL) {
  691. ipath = argv[1];
  692. } else {
  693. ipath = getcwd(cwd, sizeof(cwd));
  694. if (ipath == NULL)
  695. ipath = "/";
  696. }
  697. /* Test initial path */
  698. if (canopendir(ipath) == 0)
  699. printerr(1, ipath);
  700. /* Set locale before curses setup */
  701. setlocale(LC_ALL, "");
  702. initcurses();
  703. browse(ipath, ifilter);
  704. exitcurses();
  705. return 0;
  706. }