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.
 
 
 
 
 
 

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