My build of nnn with minor changes
 
 
 
 
 
 

733 lines
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. if (p == NULL) {
  112. free(tmp);
  113. printerr(1, "dirname");
  114. }
  115. /* Make sure this is a malloc(3)-ed string */
  116. p = xstrdup(p);
  117. free(tmp);
  118. return p;
  119. }
  120. void
  121. spawn(const char *file, const char *arg)
  122. {
  123. pid_t pid;
  124. int status;
  125. pid = fork();
  126. if (pid == 0) {
  127. execlp(file, file, arg, NULL);
  128. _exit(1);
  129. } else {
  130. /* Ignore interruptions */
  131. while (waitpid(pid, &status, 0) == -1)
  132. DPRINTF_D(status);
  133. DPRINTF_D(pid);
  134. }
  135. }
  136. char *
  137. openwith(char *file)
  138. {
  139. regex_t regex;
  140. char *bin = NULL;
  141. int i;
  142. for (i = 0; i < LEN(assocs); i++) {
  143. if (regcomp(&regex, assocs[i].regex,
  144. REG_NOSUB | REG_EXTENDED) != 0)
  145. continue;
  146. if (regexec(&regex, file, 0, NULL, 0) != REG_NOMATCH) {
  147. bin = assocs[i].bin;
  148. break;
  149. }
  150. }
  151. DPRINTF_S(bin);
  152. return bin;
  153. }
  154. int
  155. setfilter(regex_t *regex, char *filter)
  156. {
  157. char *errbuf;
  158. int r;
  159. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED);
  160. if (r != 0) {
  161. errbuf = xmalloc(COLS * sizeof(char));
  162. regerror(r, regex, errbuf, COLS * sizeof(char));
  163. printmsg(errbuf);
  164. free(errbuf);
  165. }
  166. return r;
  167. }
  168. int
  169. visible(regex_t *regex, char *file)
  170. {
  171. if (regexec(regex, file, 0, NULL, 0) != REG_NOMATCH)
  172. return 1;
  173. return 0;
  174. }
  175. int
  176. entrycmp(const void *va, const void *vb)
  177. {
  178. const struct entry *a, *b;
  179. a = (struct entry *)va;
  180. b = (struct entry *)vb;
  181. return strcmp(a->name, b->name);
  182. }
  183. void
  184. initcurses(void)
  185. {
  186. initscr();
  187. cbreak();
  188. noecho();
  189. nonl();
  190. intrflush(stdscr, FALSE);
  191. keypad(stdscr, TRUE);
  192. curs_set(FALSE); /* Hide cursor */
  193. }
  194. void
  195. exitcurses(void)
  196. {
  197. endwin(); /* Restore terminal */
  198. }
  199. /* Messages show up at the bottom */
  200. void
  201. printmsg(char *msg)
  202. {
  203. move(LINES - 1, 0);
  204. printw("%s\n", msg);
  205. }
  206. /* Display warning as a message */
  207. void
  208. printwarn(void)
  209. {
  210. printmsg(strerror(errno));
  211. }
  212. /* Kill curses and display error before exiting */
  213. void
  214. printerr(int ret, char *prefix)
  215. {
  216. exitcurses();
  217. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  218. exit(ret);
  219. }
  220. /*
  221. * Returns 0 normally
  222. * On movement it updates *cur
  223. * Returns SEL_{QUIT,BACK,GOIN,FLTR,SH,CD} otherwise
  224. */
  225. enum {
  226. SEL_QUIT = 1,
  227. SEL_BACK,
  228. SEL_GOIN,
  229. SEL_FLTR,
  230. SEL_SH,
  231. SEL_CD,
  232. };
  233. int
  234. nextsel(int *cur, int max)
  235. {
  236. int c;
  237. c = getch();
  238. switch (c) {
  239. case 'q':
  240. return SEL_QUIT;
  241. /* Back */
  242. case KEY_BACKSPACE:
  243. case KEY_LEFT:
  244. case 'h':
  245. return SEL_BACK;
  246. /* Inside */
  247. case KEY_ENTER:
  248. case '\r':
  249. case KEY_RIGHT:
  250. case 'l':
  251. return SEL_GOIN;
  252. /* Filter */
  253. case '/':
  254. case '&':
  255. return SEL_FLTR;
  256. /* Next */
  257. case 'j':
  258. case KEY_DOWN:
  259. case CONTROL('N'):
  260. if (*cur < max - 1)
  261. (*cur)++;
  262. break;
  263. /* Previous */
  264. case 'k':
  265. case KEY_UP:
  266. case CONTROL('P'):
  267. if (*cur > 0)
  268. (*cur)--;
  269. break;
  270. /* Page down */
  271. case KEY_NPAGE:
  272. case CONTROL('D'):
  273. if (*cur < max -1)
  274. (*cur) += MIN((LINES - 4) / 2, max - 1 - *cur);
  275. break;
  276. /* Page up */
  277. case KEY_PPAGE:
  278. case CONTROL('U'):
  279. if (*cur > 0)
  280. (*cur) -= MIN((LINES - 4) / 2, *cur);
  281. break;
  282. case '!':
  283. return SEL_SH;
  284. case 'c':
  285. return SEL_CD;
  286. }
  287. return 0;
  288. }
  289. char *
  290. readln(void)
  291. {
  292. int c;
  293. int i = 0;
  294. char *ln = NULL;
  295. int y, x, x0;
  296. echo();
  297. curs_set(TRUE);
  298. /* Starting point */
  299. getyx(stdscr, y, x);
  300. x0 = x;
  301. while (c = getch()) {
  302. if (c == KEY_ENTER || c == '\r')
  303. break;
  304. if (c == KEY_BACKSPACE) {
  305. getyx(stdscr, y, x);
  306. if (x >= x0) {
  307. if (i > 0) {
  308. ln = xrealloc(ln, (i - 1) * sizeof(*ln));
  309. i--;
  310. } else {
  311. free(ln);
  312. ln = NULL;
  313. }
  314. move(y, x);
  315. printw("%c", ' ');
  316. move(y, x);
  317. } else {
  318. move(y, x0);
  319. }
  320. continue;
  321. }
  322. ln = xrealloc(ln, (i + 1) * sizeof(*ln));
  323. ln[i] = c;
  324. i++;
  325. }
  326. if (ln != NULL) {
  327. ln = xrealloc(ln, (i + 1) * sizeof(*ln));
  328. ln[i] = '\0';
  329. }
  330. curs_set(FALSE);
  331. noecho();
  332. return ln;
  333. }
  334. int
  335. testopendir(char *path)
  336. {
  337. DIR *dirp;
  338. dirp = opendir(path);
  339. if (dirp == NULL) {
  340. return 0;
  341. } else {
  342. closedir(dirp);
  343. return 1;
  344. }
  345. }
  346. void
  347. printent(struct entry *ent, int active)
  348. {
  349. char *name;
  350. unsigned int maxlen = COLS - strlen(CURSR) - 1;
  351. char cm = 0;
  352. /* Copy name locally */
  353. name = xstrdup(ent->name);
  354. if (S_ISDIR(ent->mode)) {
  355. cm = '/';
  356. maxlen--;
  357. } else if (S_ISLNK(ent->mode)) {
  358. cm = '@';
  359. maxlen--;
  360. } else if (ent->mode & S_IXUSR) {
  361. cm = '*';
  362. maxlen--;
  363. }
  364. /* No text wrapping in entries */
  365. if (strlen(name) > maxlen)
  366. name[maxlen] = '\0';
  367. if (cm == 0)
  368. printw("%s%s\n", active ? CURSR : EMPTY, name);
  369. else
  370. printw("%s%s%c\n", active ? CURSR : EMPTY, name, cm);
  371. free(name);
  372. }
  373. void
  374. browse(const char *ipath, const char *ifilter)
  375. {
  376. DIR *dirp;
  377. int dfd;
  378. struct dirent *dp;
  379. struct entry *dents;
  380. int i, n, cur;
  381. int r, ret;
  382. char *path = xrealpath(ipath);
  383. char *filter = xstrdup(ifilter);
  384. regex_t filter_re;
  385. char *cwd;
  386. struct stat sb;
  387. cur = 0;
  388. begin:
  389. /* Path and filter should be malloc(3)-ed strings at all times */
  390. n = 0;
  391. dents = NULL;
  392. dirp = opendir(path);
  393. if (dirp == NULL) {
  394. printwarn();
  395. goto nochange;
  396. } else {
  397. if (chdir(path) == -1)
  398. printwarn();
  399. }
  400. /* Search filter */
  401. r = setfilter(&filter_re, filter);
  402. if (r != 0)
  403. goto nochange;
  404. while ((dp = readdir(dirp)) != NULL) {
  405. char *name;
  406. /* Skip self and parent */
  407. if (strcmp(dp->d_name, ".") == 0
  408. || strcmp(dp->d_name, "..") == 0)
  409. continue;
  410. if (!visible(&filter_re, dp->d_name))
  411. continue;
  412. /* Deep copy because readdir(3) reuses the entries */
  413. dents = xrealloc(dents, (n + 1) * sizeof(*dents));
  414. dents[n].name = xstrdup(dp->d_name);
  415. /* Handle root case */
  416. if (strcmp(path, "/") == 0)
  417. asprintf(&name, "/%s", dents[n].name);
  418. else
  419. asprintf(&name, "%s/%s", path, dents[n].name);
  420. /* Get mode flags */
  421. r = lstat(name, &sb);
  422. free(name);
  423. if (r == -1)
  424. printerr(1, "stat");
  425. dents[n].mode = sb.st_mode;
  426. n++;
  427. }
  428. /* Make sure cur is in range */
  429. cur = MIN(cur, n - 1);
  430. qsort(dents, n, sizeof(*dents), entrycmp);
  431. for (;;) {
  432. int nlines;
  433. int maxlen;
  434. int odd;
  435. char *pathnew;
  436. char *name;
  437. char *bin;
  438. char *dir;
  439. char *tmp;
  440. regex_t re;
  441. struct history *hist;
  442. redraw:
  443. nlines = MIN(LINES - 4, n);
  444. /* Clean screen */
  445. erase();
  446. DPRINTF_D(cur);
  447. DPRINTF_S(path);
  448. /* No text wrapping in cwd line */
  449. cwd = xmalloc(COLS * sizeof(char));
  450. strlcpy(cwd, path, COLS * sizeof(char));
  451. cwd[COLS - strlen(CWD) - 1] = '\0';
  452. printw(CWD "%s\n\n", cwd);
  453. /* Print listing */
  454. odd = ISODD(nlines);
  455. if (cur < nlines / 2) {
  456. for (i = 0; i < nlines; i++)
  457. printent(&dents[i], i == cur);
  458. } else if (cur >= n - nlines / 2) {
  459. for (i = n - nlines; i < n; i++)
  460. printent(&dents[i], i == cur);
  461. } else {
  462. for (i = cur - nlines / 2;
  463. i < cur + nlines / 2 + odd; i++)
  464. printent(&dents[i], i == cur);
  465. }
  466. nochange:
  467. ret = nextsel(&cur, n);
  468. switch (ret) {
  469. case SEL_QUIT:
  470. free(path);
  471. free(filter);
  472. /* Forget history */
  473. while (!SLIST_EMPTY(&histhead)) {
  474. hist = SLIST_FIRST(&histhead);
  475. SLIST_REMOVE_HEAD(&histhead, entry);
  476. free(hist);
  477. }
  478. return;
  479. case SEL_BACK:
  480. /* There is no going back */
  481. if (strcmp(path, "/") == 0) {
  482. goto nochange;
  483. } else {
  484. dir = xdirname(path);
  485. free(path);
  486. path = dir;
  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. }