My build of nnn with minor changes
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 
 

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