My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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