My build of nnn with minor changes
 
 
 
 
 
 

845 line
15 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. #include <sys/stat.h>
  3. #include <sys/types.h>
  4. #include <sys/wait.h>
  5. #include <curses.h>
  6. #include <dirent.h>
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <libgen.h>
  10. #include <limits.h>
  11. #include <locale.h>
  12. #include <regex.h>
  13. #include <signal.h>
  14. #include <stdarg.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <string.h>
  18. #include <unistd.h>
  19. #include <magic.h>
  20. #include "util.h"
  21. #ifdef DEBUG
  22. #define DEBUG_FD 8
  23. #define DPRINTF_D(x) dprintf(DEBUG_FD, #x "=%d\n", x)
  24. #define DPRINTF_U(x) dprintf(DEBUG_FD, #x "=%u\n", x)
  25. #define DPRINTF_S(x) dprintf(DEBUG_FD, #x "=%s\n", x)
  26. #define DPRINTF_P(x) dprintf(DEBUG_FD, #x "=0x%p\n", x)
  27. #else
  28. #define DPRINTF_D(x)
  29. #define DPRINTF_U(x)
  30. #define DPRINTF_S(x)
  31. #define DPRINTF_P(x)
  32. #endif /* DEBUG */
  33. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  34. #undef MIN
  35. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  36. #define ISODD(x) ((x) & 1)
  37. #define CONTROL(c) ((c) ^ 0x40)
  38. struct assoc {
  39. char *regex; /* Regex to match on filename */
  40. char *bin; /* Program */
  41. };
  42. /* Supported actions */
  43. enum action {
  44. SEL_QUIT = 1,
  45. SEL_BACK,
  46. SEL_GOIN,
  47. SEL_FLTR,
  48. SEL_NEXT,
  49. SEL_PREV,
  50. SEL_PGDN,
  51. SEL_PGUP,
  52. SEL_HOME,
  53. SEL_END,
  54. SEL_CD,
  55. SEL_CDHOME,
  56. SEL_TOGGLEDOT,
  57. SEL_MTIME,
  58. SEL_REDRAW,
  59. SEL_RUN,
  60. SEL_RUNARG,
  61. };
  62. struct key {
  63. int sym; /* Key pressed */
  64. enum action act; /* Action */
  65. char *run; /* Program to run */
  66. char *env; /* Environment variable to run */
  67. };
  68. #include "config.h"
  69. struct entry {
  70. char name[PATH_MAX];
  71. mode_t mode;
  72. time_t t;
  73. };
  74. /* Global context */
  75. struct entry *dents;
  76. int ndents, cur;
  77. int idle;
  78. /*
  79. * Layout:
  80. * .---------
  81. * | cwd: /mnt/path
  82. * |
  83. * | file0
  84. * | file1
  85. * | > file2
  86. * | file3
  87. * | file4
  88. * ...
  89. * | filen
  90. * |
  91. * | Permission denied
  92. * '------
  93. */
  94. void printmsg(char *);
  95. void printwarn(void);
  96. void printerr(int, char *);
  97. #undef dprintf
  98. int
  99. dprintf(int fd, const char *fmt, ...)
  100. {
  101. char buf[BUFSIZ];
  102. int r;
  103. va_list ap;
  104. va_start(ap, fmt);
  105. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  106. if (r > 0)
  107. r = write(fd, buf, r);
  108. va_end(ap);
  109. return r;
  110. }
  111. void *
  112. xmalloc(size_t size)
  113. {
  114. void *p;
  115. p = malloc(size);
  116. if (p == NULL)
  117. printerr(1, "malloc");
  118. return p;
  119. }
  120. void *
  121. xrealloc(void *p, size_t size)
  122. {
  123. p = realloc(p, size);
  124. if (p == NULL)
  125. printerr(1, "realloc");
  126. return p;
  127. }
  128. char *
  129. xstrdup(const char *s)
  130. {
  131. char *p;
  132. p = strdup(s);
  133. if (p == NULL)
  134. printerr(1, "strdup");
  135. return p;
  136. }
  137. /* Some implementations of dirname(3) may modify `path' and some
  138. * return a pointer inside `path'. */
  139. char *
  140. xdirname(const char *path)
  141. {
  142. static char out[PATH_MAX];
  143. char tmp[PATH_MAX], *p;
  144. strlcpy(tmp, path, sizeof(tmp));
  145. p = dirname(tmp);
  146. if (p == NULL)
  147. printerr(1, "dirname");
  148. strlcpy(out, p, sizeof(out));
  149. return out;
  150. }
  151. void
  152. spawn(char *file, char *arg, char *dir)
  153. {
  154. pid_t pid;
  155. int status;
  156. pid = fork();
  157. if (pid == 0) {
  158. if (dir != NULL)
  159. status = chdir(dir);
  160. execlp(file, file, arg, NULL);
  161. _exit(1);
  162. } else {
  163. /* Ignore interruptions */
  164. while (waitpid(pid, &status, 0) == -1)
  165. DPRINTF_D(status);
  166. DPRINTF_D(pid);
  167. }
  168. }
  169. char *
  170. xgetenv(char *name, char *fallback)
  171. {
  172. char *value;
  173. if (name == NULL)
  174. return fallback;
  175. value = getenv(name);
  176. return value && value[0] ? value : fallback;
  177. }
  178. char *
  179. openwith(char *file)
  180. {
  181. regex_t regex;
  182. char *bin = NULL;
  183. int i;
  184. const char *mime;
  185. magic_t magic;
  186. magic = magic_open(MAGIC_MIME_TYPE);
  187. magic_load(magic, NULL);
  188. magic_compile(magic, NULL);
  189. mime = magic_file(magic, file);
  190. DPRINTF_S(mime);
  191. if (strcmp(mime, "text/plain") == 0)
  192. return "vim";
  193. magic_close(magic);
  194. for (i = 0; i < LEN(assocs); i++) {
  195. if (regcomp(&regex, assocs[i].regex,
  196. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  197. continue;
  198. if (regexec(&regex, file, 0, NULL, 0) == 0) {
  199. bin = assocs[i].bin;
  200. break;
  201. }
  202. }
  203. DPRINTF_S(bin);
  204. return bin;
  205. }
  206. int
  207. setfilter(regex_t *regex, char *filter)
  208. {
  209. char errbuf[LINE_MAX];
  210. size_t len;
  211. int r;
  212. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  213. if (r != 0) {
  214. len = COLS;
  215. if (len > sizeof(errbuf))
  216. len = sizeof(errbuf);
  217. regerror(r, regex, errbuf, len);
  218. printmsg(errbuf);
  219. }
  220. return r;
  221. }
  222. int
  223. visible(regex_t *regex, char *file)
  224. {
  225. return regexec(regex, file, 0, NULL, 0) == 0;
  226. }
  227. int
  228. entrycmp(const void *va, const void *vb)
  229. {
  230. const struct entry *a = va, *b = vb;
  231. if (mtimeorder)
  232. return b->t - a->t;
  233. return strcmp(a->name, b->name);
  234. }
  235. void
  236. initcurses(void)
  237. {
  238. char *term;
  239. if (initscr() == NULL) {
  240. term = getenv("TERM");
  241. if (term != NULL)
  242. fprintf(stderr, "error opening terminal: %s\n", term);
  243. else
  244. fprintf(stderr, "failed to initialize curses\n");
  245. exit(1);
  246. }
  247. cbreak();
  248. noecho();
  249. nonl();
  250. intrflush(stdscr, FALSE);
  251. keypad(stdscr, TRUE);
  252. curs_set(FALSE); /* Hide cursor */
  253. timeout(1000); /* One second */
  254. }
  255. void
  256. exitcurses(void)
  257. {
  258. endwin(); /* Restore terminal */
  259. }
  260. /* Messages show up at the bottom */
  261. void
  262. printmsg(char *msg)
  263. {
  264. move(LINES - 1, 0);
  265. printw("%s\n", msg);
  266. }
  267. /* Display warning as a message */
  268. void
  269. printwarn(void)
  270. {
  271. printmsg(strerror(errno));
  272. }
  273. /* Kill curses and display error before exiting */
  274. void
  275. printerr(int ret, char *prefix)
  276. {
  277. exitcurses();
  278. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  279. exit(ret);
  280. }
  281. /* Clear the last line */
  282. void
  283. clearprompt(void)
  284. {
  285. printmsg("");
  286. }
  287. /* Print prompt on the last line */
  288. void
  289. printprompt(char *str)
  290. {
  291. clearprompt();
  292. printw(str);
  293. }
  294. /* Returns SEL_* if key is bound and 0 otherwise.
  295. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}) */
  296. int
  297. nextsel(char **run, char **env)
  298. {
  299. int c, i;
  300. c = getch();
  301. if (c == -1)
  302. idle++;
  303. else
  304. idle = 0;
  305. for (i = 0; i < LEN(bindings); i++)
  306. if (c == bindings[i].sym) {
  307. *run = bindings[i].run;
  308. *env = bindings[i].env;
  309. return bindings[i].act;
  310. }
  311. return 0;
  312. }
  313. char *
  314. readln(void)
  315. {
  316. static char ln[LINE_MAX];
  317. timeout(-1);
  318. echo();
  319. curs_set(TRUE);
  320. memset(ln, 0, sizeof(ln));
  321. wgetnstr(stdscr, ln, sizeof(ln) - 1);
  322. noecho();
  323. curs_set(FALSE);
  324. timeout(1000);
  325. return ln[0] ? ln : NULL;
  326. }
  327. int
  328. canopendir(char *path)
  329. {
  330. DIR *dirp;
  331. dirp = opendir(path);
  332. if (dirp == NULL)
  333. return 0;
  334. closedir(dirp);
  335. return 1;
  336. }
  337. char *
  338. mkpath(char *dir, char *name, char *out, size_t n)
  339. {
  340. /* Handle absolute path */
  341. if (name[0] == '/') {
  342. strlcpy(out, name, n);
  343. } else {
  344. /* Handle root case */
  345. if (strcmp(dir, "/") == 0) {
  346. strlcpy(out, "/", n);
  347. strlcat(out, name, n);
  348. } else {
  349. strlcpy(out, dir, n);
  350. strlcat(out, "/", n);
  351. strlcat(out, name, n);
  352. }
  353. }
  354. return out;
  355. }
  356. void
  357. printent(struct entry *ent, int active)
  358. {
  359. char name[PATH_MAX];
  360. unsigned int maxlen = COLS - strlen(CURSR) - 1;
  361. char cm = 0;
  362. /* Copy name locally */
  363. strlcpy(name, ent->name, sizeof(name));
  364. if (S_ISDIR(ent->mode)) {
  365. cm = '/';
  366. maxlen--;
  367. } else if (S_ISLNK(ent->mode)) {
  368. cm = '@';
  369. maxlen--;
  370. } else if (S_ISSOCK(ent->mode)) {
  371. cm = '=';
  372. maxlen--;
  373. } else if (S_ISFIFO(ent->mode)) {
  374. cm = '|';
  375. maxlen--;
  376. } else if (ent->mode & S_IXUSR) {
  377. cm = '*';
  378. maxlen--;
  379. }
  380. /* No text wrapping in entries */
  381. if (strlen(name) > maxlen)
  382. name[maxlen] = '\0';
  383. if (cm == 0)
  384. printw("%s%s\n", active ? CURSR : EMPTY, name);
  385. else
  386. printw("%s%s%c\n", active ? CURSR : EMPTY, name, cm);
  387. }
  388. int
  389. dentfill(char *path, struct entry **dents,
  390. int (*filter)(regex_t *, char *), regex_t *re)
  391. {
  392. char newpath[PATH_MAX];
  393. DIR *dirp;
  394. struct dirent *dp;
  395. struct stat sb;
  396. int r, n = 0;
  397. dirp = opendir(path);
  398. if (dirp == NULL)
  399. return 0;
  400. while ((dp = readdir(dirp)) != NULL) {
  401. /* Skip self and parent */
  402. if (strcmp(dp->d_name, ".") == 0 ||
  403. strcmp(dp->d_name, "..") == 0)
  404. continue;
  405. if (filter(re, dp->d_name) == 0)
  406. continue;
  407. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  408. strlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  409. /* Get mode flags */
  410. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  411. r = lstat(newpath, &sb);
  412. if (r == -1)
  413. printerr(1, "lstat");
  414. (*dents)[n].mode = sb.st_mode;
  415. (*dents)[n].t = sb.st_mtime;
  416. n++;
  417. }
  418. /* Should never be null */
  419. r = closedir(dirp);
  420. if (r == -1)
  421. printerr(1, "closedir");
  422. return n;
  423. }
  424. void
  425. dentfree(struct entry *dents)
  426. {
  427. free(dents);
  428. }
  429. /* Return the position of the matching entry or 0 otherwise */
  430. int
  431. dentfind(struct entry *dents, int n, char *cwd, char *path)
  432. {
  433. char tmp[PATH_MAX];
  434. int i;
  435. if (path == NULL)
  436. return 0;
  437. for (i = 0; i < n; i++) {
  438. mkpath(cwd, dents[i].name, tmp, sizeof(tmp));
  439. DPRINTF_S(path);
  440. DPRINTF_S(tmp);
  441. if (strcmp(tmp, path) == 0)
  442. return i;
  443. }
  444. return 0;
  445. }
  446. int
  447. populate(char *path, char *oldpath, char *fltr)
  448. {
  449. regex_t re;
  450. int r;
  451. /* Can fail when permissions change while browsing */
  452. if (canopendir(path) == 0)
  453. return -1;
  454. /* Search filter */
  455. r = setfilter(&re, fltr);
  456. if (r != 0)
  457. return -1;
  458. dentfree(dents);
  459. ndents = 0;
  460. dents = NULL;
  461. ndents = dentfill(path, &dents, visible, &re);
  462. qsort(dents, ndents, sizeof(*dents), entrycmp);
  463. /* Find cur from history */
  464. cur = dentfind(dents, ndents, path, oldpath);
  465. return 0;
  466. }
  467. void
  468. redraw(char *path)
  469. {
  470. char cwd[PATH_MAX], cwdresolved[PATH_MAX];
  471. size_t ncols;
  472. int nlines, odd;
  473. int i;
  474. nlines = MIN(LINES - 4, ndents);
  475. /* Clean screen */
  476. erase();
  477. /* Strip trailing slashes */
  478. for (i = strlen(path) - 1; i > 0; i--)
  479. if (path[i] == '/')
  480. path[i] = '\0';
  481. else
  482. break;
  483. DPRINTF_D(cur);
  484. DPRINTF_S(path);
  485. /* No text wrapping in cwd line */
  486. ncols = COLS;
  487. if (ncols > PATH_MAX)
  488. ncols = PATH_MAX;
  489. strlcpy(cwd, path, ncols);
  490. cwd[ncols - strlen(CWD) - 1] = '\0';
  491. if (!realpath(cwd, cwdresolved)) {
  492. printmsg("Cannot resolve path");
  493. return;
  494. }
  495. printw(CWD "%s\n\n", cwdresolved);
  496. /* Print listing */
  497. odd = ISODD(nlines);
  498. if (cur < nlines / 2) {
  499. for (i = 0; i < nlines; i++)
  500. printent(&dents[i], i == cur);
  501. } else if (cur >= ndents - nlines / 2) {
  502. for (i = ndents - nlines; i < ndents; i++)
  503. printent(&dents[i], i == cur);
  504. } else {
  505. for (i = cur - nlines / 2;
  506. i < cur + nlines / 2 + odd; i++)
  507. printent(&dents[i], i == cur);
  508. }
  509. }
  510. void
  511. browse(char *ipath, char *ifilter)
  512. {
  513. char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  514. char fltr[LINE_MAX];
  515. char *bin, *dir, *tmp, *run, *env;
  516. struct stat sb;
  517. regex_t re;
  518. int r, fd;
  519. strlcpy(path, ipath, sizeof(path));
  520. strlcpy(fltr, ifilter, sizeof(fltr));
  521. oldpath[0] = '\0';
  522. begin:
  523. r = populate(path, oldpath, fltr);
  524. if (r == -1) {
  525. printwarn();
  526. goto nochange;
  527. }
  528. for (;;) {
  529. redraw(path);
  530. nochange:
  531. switch (nextsel(&run, &env)) {
  532. case SEL_QUIT:
  533. dentfree(dents);
  534. return;
  535. case SEL_BACK:
  536. /* There is no going back */
  537. if (strcmp(path, "/") == 0 ||
  538. strcmp(path, ".") == 0 ||
  539. strchr(path, '/') == NULL)
  540. goto nochange;
  541. dir = xdirname(path);
  542. if (canopendir(dir) == 0) {
  543. printwarn();
  544. goto nochange;
  545. }
  546. /* Save history */
  547. strlcpy(oldpath, path, sizeof(oldpath));
  548. strlcpy(path, dir, sizeof(path));
  549. /* Reset filter */
  550. strlcpy(fltr, ifilter, sizeof(fltr));
  551. goto begin;
  552. case SEL_GOIN:
  553. /* Cannot descend in empty directories */
  554. if (ndents == 0)
  555. goto nochange;
  556. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  557. DPRINTF_S(newpath);
  558. /* Get path info */
  559. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  560. if (fd == -1) {
  561. printwarn();
  562. goto nochange;
  563. }
  564. r = fstat(fd, &sb);
  565. if (r == -1) {
  566. printwarn();
  567. close(fd);
  568. goto nochange;
  569. }
  570. close(fd);
  571. DPRINTF_U(sb.st_mode);
  572. switch (sb.st_mode & S_IFMT) {
  573. case S_IFDIR:
  574. if (canopendir(newpath) == 0) {
  575. printwarn();
  576. goto nochange;
  577. }
  578. strlcpy(path, newpath, sizeof(path));
  579. /* Reset filter */
  580. strlcpy(fltr, ifilter, sizeof(fltr));
  581. goto begin;
  582. case S_IFREG:
  583. bin = openwith(newpath);
  584. if (bin == NULL) {
  585. char cmd[512];
  586. int status;
  587. sprintf(cmd, "xdg-open \"%s\" > /dev/null 2>&1", newpath);
  588. status = system(cmd);
  589. continue;
  590. }
  591. exitcurses();
  592. spawn(bin, newpath, NULL);
  593. initcurses();
  594. continue;
  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. tmp = ifilter;
  605. /* Check and report regex errors */
  606. r = setfilter(&re, tmp);
  607. if (r != 0)
  608. goto nochange;
  609. strlcpy(fltr, tmp, sizeof(fltr));
  610. DPRINTF_S(fltr);
  611. /* Save current */
  612. if (ndents > 0)
  613. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  614. goto begin;
  615. case SEL_NEXT:
  616. if (cur < ndents - 1)
  617. cur++;
  618. break;
  619. case SEL_PREV:
  620. if (cur > 0)
  621. cur--;
  622. break;
  623. case SEL_PGDN:
  624. if (cur < ndents - 1)
  625. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  626. break;
  627. case SEL_PGUP:
  628. if (cur > 0)
  629. cur -= MIN((LINES - 4) / 2, cur);
  630. break;
  631. case SEL_HOME:
  632. cur = 0;
  633. break;
  634. case SEL_END:
  635. cur = ndents - 1;
  636. break;
  637. case SEL_CD:
  638. /* Read target dir */
  639. printprompt("chdir: ");
  640. tmp = readln();
  641. if (tmp == NULL) {
  642. clearprompt();
  643. goto nochange;
  644. }
  645. mkpath(path, tmp, newpath, sizeof(newpath));
  646. if (canopendir(newpath) == 0) {
  647. printwarn();
  648. goto nochange;
  649. }
  650. strlcpy(path, newpath, sizeof(path));
  651. /* Reset filter */
  652. strlcpy(fltr, ifilter, sizeof(fltr))
  653. DPRINTF_S(path);
  654. goto begin;
  655. case SEL_CDHOME:
  656. tmp = getenv("HOME");
  657. if (tmp == NULL) {
  658. clearprompt();
  659. goto nochange;
  660. }
  661. if (canopendir(tmp) == 0) {
  662. printwarn();
  663. goto nochange;
  664. }
  665. strlcpy(path, tmp, sizeof(path));
  666. /* Reset filter */
  667. strlcpy(fltr, ifilter, sizeof(fltr));
  668. DPRINTF_S(path);
  669. goto begin;
  670. case SEL_TOGGLEDOT:
  671. if (strcmp(fltr, ifilter) != 0)
  672. strlcpy(fltr, ifilter, sizeof(fltr));
  673. else
  674. strlcpy(fltr, ".", sizeof(fltr));
  675. goto begin;
  676. case SEL_MTIME:
  677. mtimeorder = !mtimeorder;
  678. /* Save current */
  679. if (ndents > 0)
  680. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  681. goto begin;
  682. case SEL_REDRAW:
  683. /* Save current */
  684. if (ndents > 0)
  685. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  686. goto begin;
  687. case SEL_RUN:
  688. run = xgetenv(env, run);
  689. exitcurses();
  690. spawn(run, NULL, path);
  691. initcurses();
  692. break;
  693. case SEL_RUNARG:
  694. run = xgetenv(env, run);
  695. exitcurses();
  696. spawn(run, dents[cur].name, path);
  697. initcurses();
  698. break;
  699. }
  700. /* Screensaver */
  701. if (idletimeout != 0 && idle == idletimeout) {
  702. idle = 0;
  703. exitcurses();
  704. spawn(idlecmd, NULL, NULL);
  705. initcurses();
  706. }
  707. }
  708. }
  709. void
  710. usage(char *argv0)
  711. {
  712. fprintf(stderr, "usage: %s [dir]\n", argv0);
  713. exit(1);
  714. }
  715. int
  716. main(int argc, char *argv[])
  717. {
  718. char cwd[PATH_MAX], *ipath;
  719. char *ifilter;
  720. if (argc > 2)
  721. usage(argv[0]);
  722. /* Confirm we are in a terminal */
  723. if (!isatty(0) || !isatty(1)) {
  724. fprintf(stderr, "stdin or stdout is not a tty\n");
  725. exit(1);
  726. }
  727. if (getuid() == 0)
  728. ifilter = ".";
  729. else
  730. ifilter = "^[^.]"; /* Hide dotfiles */
  731. if (argv[1] != NULL) {
  732. ipath = argv[1];
  733. } else {
  734. ipath = getcwd(cwd, sizeof(cwd));
  735. if (ipath == NULL)
  736. ipath = "/";
  737. }
  738. signal(SIGINT, SIG_IGN);
  739. /* Test initial path */
  740. if (canopendir(ipath) == 0) {
  741. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  742. exit(1);
  743. }
  744. /* Set locale before curses setup */
  745. setlocale(LC_ALL, "");
  746. initcurses();
  747. browse(ipath, ifilter);
  748. exitcurses();
  749. exit(0);
  750. }