My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

770 lines
12 KiB

  1. #include <sys/stat.h>
  2. #include <sys/types.h>
  3. #include <sys/wait.h>
  4. #include <errno.h>
  5. #include <fcntl.h>
  6. #include <dirent.h>
  7. #include <curses.h>
  8. #include <libgen.h>
  9. #include <limits.h>
  10. #include <locale.h>
  11. #include <regex.h>
  12. #include <stdlib.h>
  13. #include <stdio.h>
  14. #include <signal.h>
  15. #include <string.h>
  16. #include <unistd.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. #undef MIN
  32. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  33. #define ISODD(x) ((x) & 1)
  34. #define CONTROL(c) ((c) ^ 0x40)
  35. struct assoc {
  36. char *regex; /* Regex to match on filename */
  37. char *bin; /* Program */
  38. };
  39. #include "config.h"
  40. struct entry {
  41. char *name;
  42. mode_t mode;
  43. };
  44. /*
  45. * Layout:
  46. * .---------
  47. * | cwd: /mnt/path
  48. * |
  49. * | file0
  50. * | file1
  51. * | > file2
  52. * | file3
  53. * | file4
  54. * ...
  55. * | filen
  56. * |
  57. * | Permission denied
  58. * '------
  59. */
  60. void printmsg(char *msg);
  61. void printwarn(void);
  62. void printerr(int ret, char *prefix);
  63. void *
  64. xmalloc(size_t size)
  65. {
  66. void *p;
  67. p = malloc(size);
  68. if (p == NULL)
  69. printerr(1, "malloc");
  70. return p;
  71. }
  72. void *
  73. xrealloc(void *p, size_t size)
  74. {
  75. p = realloc(p, size);
  76. if (p == NULL)
  77. printerr(1, "realloc");
  78. return p;
  79. }
  80. char *
  81. xstrdup(const char *s)
  82. {
  83. char *p;
  84. p = strdup(s);
  85. if (p == NULL)
  86. printerr(1, "strdup");
  87. return p;
  88. }
  89. char *
  90. xdirname(const char *path)
  91. {
  92. char *p, *tmp;
  93. /* Some implementations of dirname(3) may modify `path' and some
  94. * return a pointer inside `path` and we cannot free(3) the
  95. * original string if we lose track of it. */
  96. tmp = xstrdup(path);
  97. p = dirname(tmp);
  98. if (p == NULL) {
  99. free(tmp);
  100. printerr(1, "dirname");
  101. }
  102. /* Make sure this is a malloc(3)-ed string */
  103. p = xstrdup(p);
  104. free(tmp);
  105. return p;
  106. }
  107. void
  108. spawn(const char *file, const char *arg, const char *dir)
  109. {
  110. pid_t pid;
  111. int status;
  112. pid = fork();
  113. if (pid == 0) {
  114. if (dir != NULL)
  115. chdir(dir);
  116. execlp(file, file, arg, NULL);
  117. _exit(1);
  118. } else {
  119. /* Ignore interruptions */
  120. while (waitpid(pid, &status, 0) == -1)
  121. DPRINTF_D(status);
  122. DPRINTF_D(pid);
  123. }
  124. }
  125. char *
  126. openwith(char *file)
  127. {
  128. regex_t regex;
  129. char *bin = NULL;
  130. int i;
  131. for (i = 0; i < LEN(assocs); i++) {
  132. if (regcomp(&regex, assocs[i].regex,
  133. REG_NOSUB | REG_EXTENDED) != 0)
  134. continue;
  135. if (regexec(&regex, file, 0, NULL, 0) != REG_NOMATCH) {
  136. bin = assocs[i].bin;
  137. break;
  138. }
  139. }
  140. DPRINTF_S(bin);
  141. return bin;
  142. }
  143. int
  144. setfilter(regex_t *regex, char *filter)
  145. {
  146. char *errbuf;
  147. int r;
  148. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED);
  149. if (r != 0) {
  150. errbuf = xmalloc(COLS * sizeof(char));
  151. regerror(r, regex, errbuf, COLS * sizeof(char));
  152. printmsg(errbuf);
  153. free(errbuf);
  154. }
  155. return r;
  156. }
  157. int
  158. visible(regex_t *regex, char *file)
  159. {
  160. if (regexec(regex, file, 0, NULL, 0) != REG_NOMATCH)
  161. return 1;
  162. return 0;
  163. }
  164. int
  165. entrycmp(const void *va, const void *vb)
  166. {
  167. const struct entry *a, *b;
  168. a = (struct entry *)va;
  169. b = (struct entry *)vb;
  170. return strcmp(a->name, b->name);
  171. }
  172. void
  173. initcurses(void)
  174. {
  175. initscr();
  176. cbreak();
  177. noecho();
  178. nonl();
  179. intrflush(stdscr, FALSE);
  180. keypad(stdscr, TRUE);
  181. curs_set(FALSE); /* Hide cursor */
  182. }
  183. void
  184. exitcurses(void)
  185. {
  186. endwin(); /* Restore terminal */
  187. }
  188. /* Messages show up at the bottom */
  189. void
  190. printmsg(char *msg)
  191. {
  192. move(LINES - 1, 0);
  193. printw("%s\n", msg);
  194. }
  195. /* Display warning as a message */
  196. void
  197. printwarn(void)
  198. {
  199. printmsg(strerror(errno));
  200. }
  201. /* Kill curses and display error before exiting */
  202. void
  203. printerr(int ret, char *prefix)
  204. {
  205. exitcurses();
  206. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  207. exit(ret);
  208. }
  209. /* Clear the last line */
  210. void
  211. clearprompt(void)
  212. {
  213. printmsg("");
  214. }
  215. /* Print prompt on the last line */
  216. void
  217. printprompt(char *str)
  218. {
  219. clearprompt();
  220. printw(str);
  221. }
  222. /*
  223. * Returns 0 normally
  224. * On movement it updates *cur
  225. * Returns SEL_{QUIT,BACK,GOIN,FLTR,SH,CD} otherwise
  226. */
  227. enum {
  228. SEL_QUIT = 1,
  229. SEL_BACK,
  230. SEL_GOIN,
  231. SEL_FLTR,
  232. SEL_SH,
  233. SEL_CD,
  234. };
  235. int
  236. nextsel(int *cur, int max)
  237. {
  238. int c;
  239. c = getch();
  240. switch (c) {
  241. case 'q':
  242. return SEL_QUIT;
  243. /* Back */
  244. case KEY_BACKSPACE:
  245. case KEY_LEFT:
  246. case 'h':
  247. return SEL_BACK;
  248. /* Inside */
  249. case KEY_ENTER:
  250. case '\r':
  251. case KEY_RIGHT:
  252. case 'l':
  253. return SEL_GOIN;
  254. /* Filter */
  255. case '/':
  256. case '&':
  257. return SEL_FLTR;
  258. /* Next */
  259. case 'j':
  260. case KEY_DOWN:
  261. case CONTROL('N'):
  262. if (*cur < max - 1)
  263. (*cur)++;
  264. break;
  265. /* Previous */
  266. case 'k':
  267. case KEY_UP:
  268. case CONTROL('P'):
  269. if (*cur > 0)
  270. (*cur)--;
  271. break;
  272. /* Page down */
  273. case KEY_NPAGE:
  274. case CONTROL('D'):
  275. if (*cur < max -1)
  276. (*cur) += MIN((LINES - 4) / 2, max - 1 - *cur);
  277. break;
  278. /* Page up */
  279. case KEY_PPAGE:
  280. case CONTROL('U'):
  281. if (*cur > 0)
  282. (*cur) -= MIN((LINES - 4) / 2, *cur);
  283. break;
  284. case '!':
  285. return SEL_SH;
  286. case 'c':
  287. return SEL_CD;
  288. }
  289. return 0;
  290. }
  291. char *
  292. readln(void)
  293. {
  294. int c;
  295. int i = 0;
  296. char *ln = NULL;
  297. int y, x, x0;
  298. echo();
  299. curs_set(TRUE);
  300. /* Starting point */
  301. getyx(stdscr, y, x);
  302. x0 = x;
  303. while ((c = getch()) != ERR) {
  304. if (c == KEY_ENTER || c == '\r')
  305. break;
  306. if (c == KEY_BACKSPACE) {
  307. getyx(stdscr, y, x);
  308. if (x >= x0) {
  309. i--;
  310. if (i > 0) {
  311. ln = xrealloc(ln, i * sizeof(*ln));
  312. } else {
  313. free(ln);
  314. ln = NULL;
  315. }
  316. move(y, x);
  317. printw("%c", ' ');
  318. move(y, x);
  319. } else {
  320. move(y, x0);
  321. }
  322. continue;
  323. }
  324. ln = xrealloc(ln, (i + 1) * sizeof(*ln));
  325. ln[i] = c;
  326. i++;
  327. }
  328. if (ln != NULL) {
  329. ln = xrealloc(ln, (i + 1) * sizeof(*ln));
  330. ln[i] = '\0';
  331. }
  332. curs_set(FALSE);
  333. noecho();
  334. return ln;
  335. }
  336. int
  337. canopendir(char *path)
  338. {
  339. DIR *dirp;
  340. dirp = opendir(path);
  341. if (dirp == NULL) {
  342. return 0;
  343. } else {
  344. closedir(dirp);
  345. return 1;
  346. }
  347. }
  348. void
  349. printent(struct entry *ent, int active)
  350. {
  351. char *name;
  352. unsigned int maxlen = COLS - strlen(CURSR) - 1;
  353. char cm = 0;
  354. /* Copy name locally */
  355. name = xstrdup(ent->name);
  356. if (S_ISDIR(ent->mode)) {
  357. cm = '/';
  358. maxlen--;
  359. } else if (S_ISLNK(ent->mode)) {
  360. cm = '@';
  361. maxlen--;
  362. } else if (ent->mode & S_IXUSR) {
  363. cm = '*';
  364. maxlen--;
  365. }
  366. /* No text wrapping in entries */
  367. if (strlen(name) > maxlen)
  368. name[maxlen] = '\0';
  369. if (cm == 0)
  370. printw("%s%s\n", active ? CURSR : EMPTY, name);
  371. else
  372. printw("%s%s%c\n", active ? CURSR : EMPTY, name, cm);
  373. free(name);
  374. }
  375. int
  376. dentfill(DIR *dirp, struct entry **dents,
  377. int (*filter)(regex_t *, char *), regex_t *re)
  378. {
  379. struct dirent *dp;
  380. struct stat sb;
  381. int n = 0;
  382. int r;
  383. while ((dp = readdir(dirp)) != NULL) {
  384. /* Skip self and parent */
  385. if (strcmp(dp->d_name, ".") == 0
  386. || strcmp(dp->d_name, "..") == 0)
  387. continue;
  388. if (filter(re, dp->d_name) == 0)
  389. continue;
  390. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  391. (*dents)[n].name = xstrdup(dp->d_name);
  392. /* Get mode flags */
  393. r = fstatat(dirfd(dirp), dp->d_name, &sb,
  394. AT_SYMLINK_NOFOLLOW);
  395. if (r == -1)
  396. printerr(1, "stat");
  397. (*dents)[n].mode = sb.st_mode;
  398. n++;
  399. }
  400. return n;
  401. }
  402. void
  403. dentfree(struct entry *dents, int n)
  404. {
  405. int i;
  406. for (i = 0; i < n; i++)
  407. free(dents[i].name);
  408. free(dents);
  409. }
  410. char *
  411. makepath(char *dir, char *name)
  412. {
  413. char *path;
  414. /* Handle absolute path */
  415. if (name[0] == '/') {
  416. path = xstrdup(name);
  417. } else {
  418. /* Handle root case */
  419. if (strcmp(dir, "/") == 0)
  420. asprintf(&path, "/%s", name);
  421. else
  422. asprintf(&path, "%s/%s", dir, name);
  423. }
  424. return path;
  425. }
  426. /* Return the position of the matching entry or 0 otherwise */
  427. int
  428. dentfind(struct entry *dents, int n, char *cwd, char *path)
  429. {
  430. int i;
  431. char *tmp;
  432. if (path == NULL)
  433. return 0;
  434. for (i = 0; i < n; i++) {
  435. tmp = makepath(cwd, dents[i].name);
  436. DPRINTF_S(path);
  437. DPRINTF_S(tmp);
  438. if (strcmp(tmp, path) == 0) {
  439. free(tmp);
  440. return i;
  441. }
  442. free(tmp);
  443. }
  444. return 0;
  445. }
  446. void
  447. browse(const char *ipath, const char *ifilter)
  448. {
  449. DIR *dirp;
  450. struct entry *dents;
  451. int i, n, cur;
  452. int r, ret, fd;
  453. char *path = xstrdup(ipath);
  454. char *filter = xstrdup(ifilter);
  455. regex_t filter_re;
  456. char *cwd, *newpath;
  457. struct stat sb;
  458. char *oldpath;
  459. cur = 0;
  460. oldpath = NULL;
  461. begin:
  462. /* Path and filter should be malloc(3)-ed strings at all times */
  463. n = 0;
  464. dents = NULL;
  465. dirp = opendir(path);
  466. if (dirp == NULL) {
  467. printwarn();
  468. goto nochange;
  469. }
  470. /* Search filter */
  471. r = setfilter(&filter_re, filter);
  472. if (r != 0)
  473. goto nochange;
  474. n = dentfill(dirp, &dents, visible, &filter_re);
  475. qsort(dents, n, sizeof(*dents), entrycmp);
  476. /* Find cur from history */
  477. cur = dentfind(dents, n, path, oldpath);
  478. if (oldpath != NULL) {
  479. free(oldpath);
  480. oldpath = NULL;
  481. }
  482. for (;;) {
  483. int nlines;
  484. int odd;
  485. char *name;
  486. char *bin;
  487. char *dir;
  488. char *tmp;
  489. regex_t re;
  490. redraw:
  491. nlines = MIN(LINES - 4, n);
  492. /* Clean screen */
  493. erase();
  494. DPRINTF_D(cur);
  495. DPRINTF_S(path);
  496. /* No text wrapping in cwd line */
  497. cwd = xmalloc(COLS * sizeof(char));
  498. strlcpy(cwd, path, COLS * sizeof(char));
  499. cwd[COLS - strlen(CWD) - 1] = '\0';
  500. printw(CWD "%s\n\n", cwd);
  501. /* Print listing */
  502. odd = ISODD(nlines);
  503. if (cur < nlines / 2) {
  504. for (i = 0; i < nlines; i++)
  505. printent(&dents[i], i == cur);
  506. } else if (cur >= n - nlines / 2) {
  507. for (i = n - nlines; i < n; i++)
  508. printent(&dents[i], i == cur);
  509. } else {
  510. for (i = cur - nlines / 2;
  511. i < cur + nlines / 2 + odd; i++)
  512. printent(&dents[i], i == cur);
  513. }
  514. nochange:
  515. ret = nextsel(&cur, n);
  516. switch (ret) {
  517. case SEL_QUIT:
  518. free(path);
  519. free(filter);
  520. dentfree(dents, n);
  521. return;
  522. case SEL_BACK:
  523. /* There is no going back */
  524. if (strcmp(path, "/") == 0 ||
  525. strcmp(path, ".") == 0 ||
  526. strchr(path, '/') == NULL)
  527. goto nochange;
  528. if (canopendir(path) == 0) {
  529. printwarn();
  530. goto nochange;
  531. }
  532. dir = xdirname(path);
  533. /* Save history */
  534. oldpath = path;
  535. path = dir;
  536. /* Reset filter */
  537. free(filter);
  538. filter = xstrdup(ifilter);
  539. goto out;
  540. case SEL_GOIN:
  541. /* Cannot descend in empty directories */
  542. if (n == 0)
  543. goto nochange;
  544. name = dents[cur].name;
  545. newpath = makepath(path, name);
  546. DPRINTF_S(newpath);
  547. /* Get path info */
  548. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  549. if (fd == -1) {
  550. printwarn();
  551. free(newpath);
  552. goto nochange;
  553. }
  554. r = fstat(fd, &sb);
  555. if (r == -1) {
  556. printwarn();
  557. close(fd);
  558. free(newpath);
  559. goto nochange;
  560. }
  561. close(fd);
  562. DPRINTF_U(sb.st_mode);
  563. switch (sb.st_mode & S_IFMT) {
  564. case S_IFDIR:
  565. if (canopendir(newpath) == 0) {
  566. printwarn();
  567. free(newpath);
  568. goto nochange;
  569. }
  570. free(path);
  571. path = newpath;
  572. /* Reset filter */
  573. free(filter);
  574. filter = xstrdup(ifilter);
  575. cur = 0;
  576. goto out;
  577. case S_IFREG:
  578. bin = openwith(name);
  579. if (bin == NULL) {
  580. printmsg("No association");
  581. free(newpath);
  582. goto nochange;
  583. }
  584. exitcurses();
  585. spawn(bin, newpath, NULL);
  586. initcurses();
  587. free(newpath);
  588. goto redraw;
  589. default:
  590. printmsg("Unsupported file");
  591. goto nochange;
  592. }
  593. case SEL_FLTR:
  594. /* Read filter */
  595. printprompt("filter: ");
  596. tmp = readln();
  597. if (tmp == NULL) {
  598. clearprompt();
  599. goto nochange;
  600. }
  601. r = setfilter(&re, tmp);
  602. if (r != 0) {
  603. free(tmp);
  604. goto nochange;
  605. }
  606. free(filter);
  607. filter = tmp;
  608. filter_re = re;
  609. DPRINTF_S(filter);
  610. cur = 0;
  611. goto out;
  612. case SEL_SH:
  613. exitcurses();
  614. spawn("/bin/sh", NULL, path);
  615. initcurses();
  616. break;
  617. case SEL_CD:
  618. /* Read target dir */
  619. printprompt("chdir: ");
  620. tmp = readln();
  621. if (tmp == NULL) {
  622. clearprompt();
  623. goto nochange;
  624. }
  625. newpath = makepath(path, tmp);
  626. free(tmp);
  627. if (canopendir(newpath) == 0) {
  628. free(newpath);
  629. printwarn();
  630. goto nochange;
  631. }
  632. free(path);
  633. path = newpath;
  634. free(filter);
  635. filter = xstrdup(ifilter); /* Reset filter */
  636. DPRINTF_S(path);
  637. cur = 0;
  638. goto out;
  639. }
  640. }
  641. out:
  642. dentfree(dents, n);
  643. /* Should never be null */
  644. r = closedir(dirp);
  645. if (r == -1)
  646. printerr(1, "closedir");
  647. goto begin;
  648. }
  649. int
  650. main(int argc, char *argv[])
  651. {
  652. char cwd[PATH_MAX], *ipath;
  653. char *ifilter;
  654. if (getuid() == 0)
  655. ifilter = ".*";
  656. else
  657. ifilter = "^[^.].*"; /* Hide dotfiles */
  658. if (argv[1] != NULL) {
  659. ipath = argv[1];
  660. } else {
  661. ipath = getcwd(cwd, sizeof(cwd));
  662. if (ipath == NULL)
  663. ipath = "/";
  664. }
  665. /* Test initial path */
  666. if (canopendir(ipath) == 0)
  667. printerr(1, ipath);
  668. /* Set locale before curses setup */
  669. setlocale(LC_ALL, "");
  670. initcurses();
  671. browse(ipath, ifilter);
  672. exitcurses();
  673. return 0;
  674. }