My build of nnn with minor changes
 
 
 
 
 
 

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