My build of nnn with minor changes
 
 
 
 
 
 

1096 lines
22 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 <limits.h>
  10. #include <locale.h>
  11. #include <regex.h>
  12. #include <signal.h>
  13. #include <stdarg.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. #include <time.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. #define TOUPPER(ch) \
  38. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  39. #define MAX_CMD_LEN (PATH_MAX << 1)
  40. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  41. struct assoc {
  42. char *regex; /* Regex to match on filename */
  43. char *bin; /* Program */
  44. };
  45. /* Supported actions */
  46. enum action {
  47. SEL_QUIT = 1,
  48. SEL_BACK,
  49. SEL_GOIN,
  50. SEL_FLTR,
  51. SEL_NEXT,
  52. SEL_PREV,
  53. SEL_PGDN,
  54. SEL_PGUP,
  55. SEL_HOME,
  56. SEL_END,
  57. SEL_CD,
  58. SEL_CDHOME,
  59. SEL_TOGGLEDOT,
  60. SEL_DETAIL,
  61. SEL_FSIZE,
  62. SEL_MTIME,
  63. SEL_REDRAW,
  64. SEL_COPY,
  65. SEL_RUN,
  66. SEL_RUNARG,
  67. };
  68. struct key {
  69. int sym; /* Key pressed */
  70. enum action act; /* Action */
  71. char *run; /* Program to run */
  72. char *env; /* Environment variable to run */
  73. };
  74. #include "config.h"
  75. typedef struct entry {
  76. char name[PATH_MAX];
  77. mode_t mode;
  78. time_t t;
  79. off_t size;
  80. } *pEntry;
  81. /* Global context */
  82. static struct entry *dents;
  83. static int ndents, cur;
  84. static int idle;
  85. static char *opener;
  86. static char *fallback_opener;
  87. static char *copier;
  88. static const char* size_units[] = {"B", "K", "M", "G", "T", "P", "E", "Z", "Y"};
  89. /*
  90. * Layout:
  91. * .---------
  92. * | cwd: /mnt/path
  93. * |
  94. * | file0
  95. * | file1
  96. * | > file2
  97. * | file3
  98. * | file4
  99. * ...
  100. * | filen
  101. * |
  102. * | Permission denied
  103. * '------
  104. */
  105. static void printmsg(char *);
  106. static void printwarn(void);
  107. static void printerr(int, char *);
  108. #undef dprintf
  109. static int
  110. dprintf(int fd, const char *fmt, ...)
  111. {
  112. char buf[BUFSIZ];
  113. int r;
  114. va_list ap;
  115. va_start(ap, fmt);
  116. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  117. if (r > 0)
  118. r = write(fd, buf, r);
  119. va_end(ap);
  120. return r;
  121. }
  122. static void *
  123. xrealloc(void *p, size_t size)
  124. {
  125. p = realloc(p, size);
  126. if (p == NULL)
  127. printerr(1, "realloc");
  128. return p;
  129. }
  130. /*
  131. * The poor man's implementation of memrchr().
  132. * We are only looking for '/' in this program.
  133. */
  134. static void *
  135. xmemrchr(const void *s, int c, size_t n)
  136. {
  137. unsigned char *p;
  138. unsigned char ch = (unsigned char)c;
  139. if (!s || !n)
  140. return NULL;
  141. p = (unsigned char *)s + n - 1;
  142. while(n--)
  143. if ((*p--) == ch)
  144. return ++p;
  145. return NULL;
  146. }
  147. #if 0
  148. /* Some implementations of dirname(3) may modify `path' and some
  149. * return a pointer inside `path'. */
  150. static char *
  151. xdirname(const char *path)
  152. {
  153. static char out[PATH_MAX];
  154. char tmp[PATH_MAX], *p;
  155. strlcpy(tmp, path, sizeof(tmp));
  156. p = dirname(tmp);
  157. if (p == NULL)
  158. printerr(1, "dirname");
  159. strlcpy(out, p, sizeof(out));
  160. return out;
  161. }
  162. #endif
  163. /*
  164. * The following dirname() implementation does not
  165. * change the input. We use a copy of the original.
  166. *
  167. * Modified from the glibc (GNU LGPL) version.
  168. */
  169. static char *
  170. xdirname(const char *path)
  171. {
  172. static char name[PATH_MAX];
  173. char *last_slash;
  174. strlcpy(name, path, PATH_MAX);
  175. /* Find last '/'. */
  176. last_slash = name != NULL ? strrchr(name, '/') : NULL;
  177. if (last_slash != NULL && last_slash != name && last_slash[1] == '\0') {
  178. /* Determine whether all remaining characters are slashes. */
  179. char *runp;
  180. for (runp = last_slash; runp != name; --runp)
  181. if (runp[-1] != '/')
  182. break;
  183. /* The '/' is the last character, we have to look further. */
  184. if (runp != name)
  185. last_slash = xmemrchr(name, '/', runp - name);
  186. }
  187. if (last_slash != NULL) {
  188. /* Determine whether all remaining characters are slashes. */
  189. char *runp;
  190. for (runp = last_slash; runp != name; --runp)
  191. if (runp[-1] != '/')
  192. break;
  193. /* Terminate the name. */
  194. if (runp == name) {
  195. /* The last slash is the first character in the string.
  196. We have to return "/". As a special case we have to
  197. return "//" if there are exactly two slashes at the
  198. beginning of the string. See XBD 4.10 Path Name
  199. Resolution for more information. */
  200. if (last_slash == name + 1)
  201. ++last_slash;
  202. else
  203. last_slash = name + 1;
  204. } else
  205. last_slash = runp;
  206. last_slash[0] = '\0';
  207. } else {
  208. /* This assignment is ill-designed but the XPG specs require to
  209. return a string containing "." in any case no directory part
  210. is found and so a static and constant string is required. */
  211. name[0] = '.';
  212. name[1] = '\0';
  213. }
  214. return name;
  215. }
  216. static void
  217. spawn(char *file, char *arg, char *dir)
  218. {
  219. pid_t pid;
  220. int status;
  221. pid = fork();
  222. if (pid == 0) {
  223. if (dir != NULL)
  224. status = chdir(dir);
  225. execlp(file, file, arg, NULL);
  226. _exit(1);
  227. } else {
  228. /* Ignore interruptions */
  229. while (waitpid(pid, &status, 0) == -1)
  230. DPRINTF_D(status);
  231. DPRINTF_D(pid);
  232. }
  233. }
  234. static char *
  235. xgetenv(char *name, char *fallback)
  236. {
  237. char *value;
  238. if (name == NULL)
  239. return fallback;
  240. value = getenv(name);
  241. return value && value[0] ? value : fallback;
  242. }
  243. static int
  244. xstricmp(const char *s1, const char *s2)
  245. {
  246. while (*s2 != 0 && TOUPPER(*s1) == TOUPPER(*s2))
  247. s1++, s2++;
  248. /* In case of alphabetically same names, make sure
  249. lower case one comes before upper case one */
  250. if (!*s1 && !*s2)
  251. return 1;
  252. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  253. }
  254. static char *
  255. openwith(char *file)
  256. {
  257. regex_t regex;
  258. char *bin = NULL;
  259. unsigned int i;
  260. for (i = 0; i < LEN(assocs); i++) {
  261. if (regcomp(&regex, assocs[i].regex,
  262. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  263. continue;
  264. if (regexec(&regex, file, 0, NULL, 0) == 0) {
  265. bin = assocs[i].bin;
  266. break;
  267. }
  268. }
  269. DPRINTF_S(bin);
  270. return bin;
  271. }
  272. static int
  273. setfilter(regex_t *regex, char *filter)
  274. {
  275. char errbuf[LINE_MAX];
  276. size_t len;
  277. int r;
  278. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  279. if (r != 0) {
  280. len = COLS;
  281. if (len > sizeof(errbuf))
  282. len = sizeof(errbuf);
  283. regerror(r, regex, errbuf, len);
  284. printmsg(errbuf);
  285. }
  286. return r;
  287. }
  288. static void
  289. initfilter(int dot, char **ifilter)
  290. {
  291. *ifilter = dot ? "." : "^[^.]";
  292. }
  293. static int
  294. visible(regex_t *regex, char *file)
  295. {
  296. return regexec(regex, file, 0, NULL, 0) == 0;
  297. }
  298. static int
  299. entrycmp(const void *va, const void *vb)
  300. {
  301. if (mtimeorder)
  302. return ((pEntry)vb)->t - ((pEntry)va)->t;
  303. if (sizeorder)
  304. return ((pEntry)vb)->size - ((pEntry)va)->size;
  305. return xstricmp(((pEntry)va)->name, ((pEntry)vb)->name);
  306. }
  307. static void
  308. initcurses(void)
  309. {
  310. if (initscr() == NULL) {
  311. char *term = getenv("TERM");
  312. if (term != NULL)
  313. fprintf(stderr, "error opening terminal: %s\n", term);
  314. else
  315. fprintf(stderr, "failed to initialize curses\n");
  316. exit(1);
  317. }
  318. cbreak();
  319. noecho();
  320. nonl();
  321. intrflush(stdscr, FALSE);
  322. keypad(stdscr, TRUE);
  323. curs_set(FALSE); /* Hide cursor */
  324. timeout(1000); /* One second */
  325. }
  326. static void
  327. exitcurses(void)
  328. {
  329. endwin(); /* Restore terminal */
  330. }
  331. /* Messages show up at the bottom */
  332. static void
  333. printmsg(char *msg)
  334. {
  335. move(LINES - 1, 0);
  336. printw("%s\n", msg);
  337. }
  338. /* Display warning as a message */
  339. static void
  340. printwarn(void)
  341. {
  342. printmsg(strerror(errno));
  343. }
  344. /* Kill curses and display error before exiting */
  345. static void
  346. printerr(int ret, char *prefix)
  347. {
  348. exitcurses();
  349. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  350. exit(ret);
  351. }
  352. /* Clear the last line */
  353. static void
  354. clearprompt(void)
  355. {
  356. printmsg("");
  357. }
  358. /* Print prompt on the last line */
  359. static void
  360. printprompt(char *str)
  361. {
  362. clearprompt();
  363. printw(str);
  364. }
  365. /* Returns SEL_* if key is bound and 0 otherwise.
  366. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}) */
  367. static int
  368. nextsel(char **run, char **env)
  369. {
  370. int c;
  371. unsigned int i;
  372. c = getch();
  373. if (c == -1)
  374. idle++;
  375. else
  376. idle = 0;
  377. for (i = 0; i < LEN(bindings); i++)
  378. if (c == bindings[i].sym) {
  379. *run = bindings[i].run;
  380. *env = bindings[i].env;
  381. return bindings[i].act;
  382. }
  383. return 0;
  384. }
  385. static char *
  386. readln(void)
  387. {
  388. static char ln[LINE_MAX];
  389. timeout(-1);
  390. echo();
  391. curs_set(TRUE);
  392. memset(ln, 0, sizeof(ln));
  393. wgetnstr(stdscr, ln, sizeof(ln) - 1);
  394. noecho();
  395. curs_set(FALSE);
  396. timeout(1000);
  397. return ln[0] ? ln : NULL;
  398. }
  399. static int
  400. canopendir(char *path)
  401. {
  402. DIR *dirp;
  403. dirp = opendir(path);
  404. if (dirp == NULL)
  405. return 0;
  406. closedir(dirp);
  407. return 1;
  408. }
  409. static char *
  410. mkpath(char *dir, char *name, char *out, size_t n)
  411. {
  412. /* Handle absolute path */
  413. if (name[0] == '/')
  414. strlcpy(out, name, n);
  415. else {
  416. /* Handle root case */
  417. if (strcmp(dir, "/") == 0)
  418. snprintf(out, n, "/%s", name);
  419. else
  420. snprintf(out, n, "%s/%s", dir, name);
  421. }
  422. return out;
  423. }
  424. static void
  425. printent(struct entry *ent, int active)
  426. {
  427. if (S_ISDIR(ent->mode))
  428. printw("%s%s/\n", active ? CURSR : EMPTY, ent->name);
  429. else if (S_ISLNK(ent->mode))
  430. printw("%s%s@\n", active ? CURSR : EMPTY, ent->name);
  431. else if (S_ISSOCK(ent->mode))
  432. printw("%s%s=\n", active ? CURSR : EMPTY, ent->name);
  433. else if (S_ISFIFO(ent->mode))
  434. printw("%s%s|\n", active ? CURSR : EMPTY, ent->name);
  435. else if (ent->mode & S_IXUSR)
  436. printw("%s%s*\n", active ? CURSR : EMPTY, ent->name);
  437. else
  438. printw("%s%s\n", active ? CURSR : EMPTY, ent->name);
  439. }
  440. static void (*printptr)(struct entry *ent, int active) = &printent;
  441. static char*
  442. coolsize(off_t size)
  443. {
  444. static char size_buf[12]; /* Buffer to hold human readable size */
  445. int i = 0;
  446. long double fsize = (double)size;
  447. while (fsize > 1024) {
  448. fsize /= 1024;
  449. i++;
  450. }
  451. snprintf(size_buf, 12, "%.*Lf%s", i, fsize, size_units[i]);
  452. return size_buf;
  453. }
  454. static void
  455. printent_long(struct entry *ent, int active)
  456. {
  457. static char buf[18];
  458. static const struct tm *p;
  459. p = localtime(&ent->t);
  460. strftime(buf, 18, "%b %d %H:%M %Y", p);
  461. if (active)
  462. attron(A_REVERSE);
  463. if (S_ISDIR(ent->mode))
  464. printw("%s%-17.17s / %s/\n",
  465. CURSYM(active), buf, ent->name);
  466. else if (S_ISLNK(ent->mode))
  467. printw("%s%-17.17s @ %s@\n",
  468. CURSYM(active), buf, ent->name);
  469. else if (S_ISSOCK(ent->mode))
  470. printw("%s%-17.17s = %s=\n",
  471. CURSYM(active), buf, ent->name);
  472. else if (S_ISFIFO(ent->mode))
  473. printw("%s%-17.17s | %s|\n",
  474. CURSYM(active), buf, ent->name);
  475. else if (S_ISBLK(ent->mode))
  476. printw("%s%-17.17s b %s\n",
  477. CURSYM(active), buf, ent->name);
  478. else if (S_ISCHR(ent->mode))
  479. printw("%s%-17.17s c %s\n",
  480. CURSYM(active), buf, ent->name);
  481. else if (ent->mode & S_IXUSR)
  482. printw("%s%-17.17s %8.8s* %s*\n", CURSYM(active),
  483. buf, coolsize(ent->size), ent->name);
  484. else
  485. printw("%s%-17.17s %8.8s %s\n", CURSYM(active),
  486. buf, coolsize(ent->size), ent->name);
  487. if (active)
  488. attroff(A_REVERSE);
  489. }
  490. static int
  491. dentfill(char *path, struct entry **dents,
  492. int (*filter)(regex_t *, char *), regex_t *re)
  493. {
  494. char newpath[PATH_MAX];
  495. DIR *dirp;
  496. struct dirent *dp;
  497. struct stat sb;
  498. int r, n = 0;
  499. dirp = opendir(path);
  500. if (dirp == NULL)
  501. return 0;
  502. while ((dp = readdir(dirp)) != NULL) {
  503. /* Skip self and parent */
  504. if (strcmp(dp->d_name, ".") == 0 ||
  505. strcmp(dp->d_name, "..") == 0)
  506. continue;
  507. if (filter(re, dp->d_name) == 0)
  508. continue;
  509. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  510. strlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  511. /* Get mode flags */
  512. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  513. r = lstat(newpath, &sb);
  514. if (r == -1)
  515. printerr(1, "lstat");
  516. (*dents)[n].mode = sb.st_mode;
  517. (*dents)[n].t = sb.st_mtime;
  518. (*dents)[n].size = sb.st_size;
  519. n++;
  520. }
  521. /* Should never be null */
  522. r = closedir(dirp);
  523. if (r == -1)
  524. printerr(1, "closedir");
  525. return n;
  526. }
  527. static void
  528. dentfree(struct entry *dents)
  529. {
  530. free(dents);
  531. }
  532. /* Return the position of the matching entry or 0 otherwise */
  533. static int
  534. dentfind(struct entry *dents, int n, char *cwd, char *path)
  535. {
  536. char tmp[PATH_MAX];
  537. int i;
  538. if (path == NULL)
  539. return 0;
  540. for (i = 0; i < n; i++) {
  541. mkpath(cwd, dents[i].name, tmp, sizeof(tmp));
  542. DPRINTF_S(path);
  543. DPRINTF_S(tmp);
  544. if (strcmp(tmp, path) == 0)
  545. return i;
  546. }
  547. return 0;
  548. }
  549. static int
  550. populate(char *path, char *oldpath, char *fltr)
  551. {
  552. regex_t re;
  553. int r;
  554. /* Can fail when permissions change while browsing */
  555. if (canopendir(path) == 0)
  556. return -1;
  557. /* Search filter */
  558. r = setfilter(&re, fltr);
  559. if (r != 0)
  560. return -1;
  561. dentfree(dents);
  562. ndents = 0;
  563. dents = NULL;
  564. ndents = dentfill(path, &dents, visible, &re);
  565. qsort(dents, ndents, sizeof(*dents), entrycmp);
  566. /* Find cur from history */
  567. cur = dentfind(dents, ndents, path, oldpath);
  568. return 0;
  569. }
  570. static void
  571. redraw(char *path)
  572. {
  573. static char cwd[PATH_MAX];
  574. static int nlines, odd;
  575. static int i;
  576. nlines = MIN(LINES - 4, ndents);
  577. /* Clean screen */
  578. erase();
  579. /* Strip trailing slashes */
  580. for (i = strlen(path) - 1; i > 0; i--)
  581. if (path[i] == '/')
  582. path[i] = '\0';
  583. else
  584. break;
  585. DPRINTF_D(cur);
  586. DPRINTF_S(path);
  587. /* No text wrapping in cwd line */
  588. if (!realpath(path, cwd)) {
  589. printmsg("Cannot resolve path");
  590. return;
  591. }
  592. printw(CWD "%s\n\n", cwd);
  593. /* Print listing */
  594. odd = ISODD(nlines);
  595. if (cur < (nlines >> 1)) {
  596. for (i = 0; i < nlines; i++)
  597. printptr(&dents[i], i == cur);
  598. } else if (cur >= ndents - (nlines >> 1)) {
  599. for (i = ndents - nlines; i < ndents; i++)
  600. printptr(&dents[i], i == cur);
  601. } else {
  602. nlines >>= 1;
  603. for (i = cur - nlines; i < cur + nlines + odd; i++)
  604. printptr(&dents[i], i == cur);
  605. }
  606. if (showdetail) {
  607. if (ndents) {
  608. static char ind[2] = "\0\0";
  609. static char sort[9];
  610. if (mtimeorder)
  611. sprintf(sort, "by time ");
  612. else if (sizeorder)
  613. sprintf(sort, "by size ");
  614. else
  615. sort[0] = '\0';
  616. if (S_ISDIR(dents[cur].mode))
  617. ind[0] = '/';
  618. else if (S_ISLNK(dents[cur].mode))
  619. ind[0] = '@';
  620. else if (S_ISSOCK(dents[cur].mode))
  621. ind[0] = '=';
  622. else if (S_ISFIFO(dents[cur].mode))
  623. ind[0] = '|';
  624. else if (dents[cur].mode & S_IXUSR)
  625. ind[0] = '*';
  626. else
  627. ind[0] = '\0';
  628. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  629. dents[cur].name, ind);
  630. printmsg(cwd);
  631. } else
  632. printmsg("0 items");
  633. }
  634. }
  635. static void
  636. browse(char *ipath, char *ifilter)
  637. {
  638. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  639. static char fltr[LINE_MAX];
  640. char *bin, *dir, *tmp, *run, *env;
  641. struct stat sb;
  642. regex_t re;
  643. int r, fd;
  644. strlcpy(path, ipath, sizeof(path));
  645. strlcpy(fltr, ifilter, sizeof(fltr));
  646. oldpath[0] = '\0';
  647. newpath[0] = '\0';
  648. begin:
  649. r = populate(path, oldpath, fltr);
  650. if (r == -1) {
  651. printwarn();
  652. goto nochange;
  653. }
  654. for (;;) {
  655. redraw(path);
  656. nochange:
  657. switch (nextsel(&run, &env)) {
  658. case SEL_QUIT:
  659. dentfree(dents);
  660. return;
  661. case SEL_BACK:
  662. /* There is no going back */
  663. if (strcmp(path, "/") == 0 ||
  664. strcmp(path, ".") == 0 ||
  665. strchr(path, '/') == NULL)
  666. goto nochange;
  667. dir = xdirname(path);
  668. if (canopendir(dir) == 0) {
  669. printwarn();
  670. goto nochange;
  671. }
  672. /* Save history */
  673. strlcpy(oldpath, path, sizeof(oldpath));
  674. strlcpy(path, dir, sizeof(path));
  675. /* Reset filter */
  676. strlcpy(fltr, ifilter, sizeof(fltr));
  677. goto begin;
  678. case SEL_GOIN:
  679. /* Cannot descend in empty directories */
  680. if (ndents == 0)
  681. goto nochange;
  682. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  683. DPRINTF_S(newpath);
  684. /* Get path info */
  685. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  686. if (fd == -1) {
  687. printwarn();
  688. goto nochange;
  689. }
  690. r = fstat(fd, &sb);
  691. if (r == -1) {
  692. printwarn();
  693. close(fd);
  694. goto nochange;
  695. }
  696. close(fd);
  697. DPRINTF_U(sb.st_mode);
  698. switch (sb.st_mode & S_IFMT) {
  699. case S_IFDIR:
  700. if (canopendir(newpath) == 0) {
  701. printwarn();
  702. goto nochange;
  703. }
  704. strlcpy(path, newpath, sizeof(path));
  705. /* Reset filter */
  706. strlcpy(fltr, ifilter, sizeof(fltr));
  707. goto begin;
  708. case S_IFREG:
  709. {
  710. static char cmd[MAX_CMD_LEN];
  711. static char *runvi = "vi";
  712. static int status;
  713. static FILE *fp;
  714. /* If default mime opener is set, use it */
  715. if (opener) {
  716. snprintf(cmd, MAX_CMD_LEN,
  717. "%s \"%s\" > /dev/null 2>&1",
  718. opener, newpath);
  719. status = system(cmd);
  720. continue;
  721. }
  722. /* Try custom applications */
  723. bin = openwith(newpath);
  724. if (bin == NULL) {
  725. /* If a custom handler application is
  726. not set, open plain text files with
  727. vi, then try fallback_opener */
  728. snprintf(cmd, MAX_CMD_LEN,
  729. "file \"%s\"", newpath);
  730. fp = popen(cmd, "r");
  731. if (fp == NULL)
  732. goto nochange;
  733. if (fgets(cmd, MAX_CMD_LEN, fp) == NULL) {
  734. pclose(fp);
  735. goto nochange;
  736. }
  737. pclose(fp);
  738. if (strstr(cmd, "ASCII text") != NULL)
  739. bin = runvi;
  740. else if (fallback_opener) {
  741. snprintf(cmd, MAX_CMD_LEN,
  742. "%s \"%s\" > \
  743. /dev/null 2>&1",
  744. fallback_opener,
  745. newpath);
  746. status = system(cmd);
  747. continue;
  748. } else {
  749. printmsg("No association");
  750. goto nochange;
  751. }
  752. }
  753. exitcurses();
  754. spawn(bin, newpath, NULL);
  755. initcurses();
  756. continue;
  757. }
  758. default:
  759. printmsg("Unsupported file");
  760. goto nochange;
  761. }
  762. case SEL_FLTR:
  763. /* Read filter */
  764. printprompt("filter: ");
  765. tmp = readln();
  766. if (tmp == NULL)
  767. tmp = ifilter;
  768. /* Check and report regex errors */
  769. r = setfilter(&re, tmp);
  770. if (r != 0)
  771. goto nochange;
  772. strlcpy(fltr, tmp, sizeof(fltr));
  773. DPRINTF_S(fltr);
  774. /* Save current */
  775. if (ndents > 0)
  776. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  777. goto begin;
  778. case SEL_NEXT:
  779. if (cur < ndents - 1)
  780. cur++;
  781. else if (ndents)
  782. /* Roll over, set cursor to first entry */
  783. cur = 0;
  784. break;
  785. case SEL_PREV:
  786. if (cur > 0)
  787. cur--;
  788. else if (ndents)
  789. /* Roll over, set cursor to last entry */
  790. cur = ndents - 1;
  791. break;
  792. case SEL_PGDN:
  793. if (cur < ndents - 1)
  794. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  795. break;
  796. case SEL_PGUP:
  797. if (cur > 0)
  798. cur -= MIN((LINES - 4) / 2, cur);
  799. break;
  800. case SEL_HOME:
  801. cur = 0;
  802. break;
  803. case SEL_END:
  804. cur = ndents - 1;
  805. break;
  806. case SEL_CD:
  807. /* Read target dir */
  808. printprompt("chdir: ");
  809. tmp = readln();
  810. if (tmp == NULL) {
  811. clearprompt();
  812. goto nochange;
  813. }
  814. mkpath(path, tmp, newpath, sizeof(newpath));
  815. if (canopendir(newpath) == 0) {
  816. printwarn();
  817. goto nochange;
  818. }
  819. strlcpy(path, newpath, sizeof(path));
  820. /* Reset filter */
  821. strlcpy(fltr, ifilter, sizeof(fltr))
  822. DPRINTF_S(path);
  823. goto begin;
  824. case SEL_CDHOME:
  825. tmp = getenv("HOME");
  826. if (tmp == NULL) {
  827. clearprompt();
  828. goto nochange;
  829. }
  830. if (canopendir(tmp) == 0) {
  831. printwarn();
  832. goto nochange;
  833. }
  834. strlcpy(path, tmp, sizeof(path));
  835. /* Reset filter */
  836. strlcpy(fltr, ifilter, sizeof(fltr));
  837. DPRINTF_S(path);
  838. goto begin;
  839. case SEL_TOGGLEDOT:
  840. showhidden ^= 1;
  841. initfilter(showhidden, &ifilter);
  842. strlcpy(fltr, ifilter, sizeof(fltr));
  843. goto begin;
  844. case SEL_DETAIL:
  845. showdetail = !showdetail;
  846. showdetail ? (printptr = &printent_long)
  847. : (printptr = &printent);
  848. /* Save current */
  849. if (ndents > 0)
  850. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  851. goto begin;
  852. case SEL_FSIZE:
  853. sizeorder = !sizeorder;
  854. mtimeorder = 0;
  855. /* Save current */
  856. if (ndents > 0)
  857. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  858. goto begin;
  859. case SEL_MTIME:
  860. mtimeorder = !mtimeorder;
  861. sizeorder = 0;
  862. /* Save current */
  863. if (ndents > 0)
  864. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  865. goto begin;
  866. case SEL_REDRAW:
  867. /* Save current */
  868. if (ndents > 0)
  869. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  870. goto begin;
  871. case SEL_COPY:
  872. if (copier && ndents) {
  873. char abspath[PATH_MAX];
  874. if (strcmp(path, "/") == 0)
  875. snprintf(abspath, PATH_MAX, "/%s",
  876. dents[cur].name);
  877. else
  878. snprintf(abspath, PATH_MAX, "%s/%s",
  879. path, dents[cur].name);
  880. spawn(copier, abspath, NULL);
  881. printmsg(abspath);
  882. } else if (!copier)
  883. printmsg("NNN_COPIER is not set");
  884. goto nochange;
  885. case SEL_RUN:
  886. run = xgetenv(env, run);
  887. exitcurses();
  888. spawn(run, NULL, path);
  889. initcurses();
  890. /* Re-populate as directory content may have changed */
  891. goto begin;
  892. case SEL_RUNARG:
  893. run = xgetenv(env, run);
  894. exitcurses();
  895. spawn(run, dents[cur].name, path);
  896. initcurses();
  897. break;
  898. }
  899. /* Screensaver */
  900. if (idletimeout != 0 && idle == idletimeout) {
  901. idle = 0;
  902. exitcurses();
  903. spawn(idlecmd, NULL, NULL);
  904. initcurses();
  905. }
  906. }
  907. }
  908. static void
  909. usage(void)
  910. {
  911. fprintf(stderr, "usage: nnn [-d] [dir]\n");
  912. exit(1);
  913. }
  914. int
  915. main(int argc, char *argv[])
  916. {
  917. char cwd[PATH_MAX], *ipath;
  918. char *ifilter;
  919. int opt = 0;
  920. /* Confirm we are in a terminal */
  921. if (!isatty(0) || !isatty(1)) {
  922. fprintf(stderr, "stdin or stdout is not a tty\n");
  923. exit(1);
  924. }
  925. if (argc > 3)
  926. usage();
  927. while ((opt = getopt(argc, argv, "d")) != -1) {
  928. switch (opt) {
  929. case 'd':
  930. /* Open in detail mode, if set */
  931. showdetail = 1;
  932. printptr = &printent_long;
  933. break;
  934. default:
  935. usage();
  936. }
  937. }
  938. if (argc == optind) {
  939. /* Start in the current directory */
  940. ipath = getcwd(cwd, sizeof(cwd));
  941. if (ipath == NULL)
  942. ipath = "/";
  943. } else {
  944. ipath = realpath(argv[optind], cwd);
  945. if (!ipath) {
  946. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  947. exit(1);
  948. }
  949. }
  950. if (getuid() == 0)
  951. showhidden = 1;
  952. initfilter(showhidden, &ifilter);
  953. /* Get the default desktop mime opener, if set */
  954. opener = getenv("NNN_OPENER");
  955. /* Get the fallback desktop mime opener, if set */
  956. fallback_opener = getenv("NNN_FALLBACK_OPENER");
  957. /* Get the default copier, if set */
  958. copier = getenv("NNN_COPIER");
  959. signal(SIGINT, SIG_IGN);
  960. /* Test initial path */
  961. if (canopendir(ipath) == 0) {
  962. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  963. exit(1);
  964. }
  965. /* Set locale before curses setup */
  966. setlocale(LC_ALL, "");
  967. initcurses();
  968. browse(ipath, ifilter);
  969. exitcurses();
  970. exit(0);
  971. }