My build of nnn with minor changes
 
 
 
 
 
 

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