My build of nnn with minor changes
Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 
 
 

1152 Zeilen
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. /*
  447. * Returns "dir/name or "/name"
  448. */
  449. static char *
  450. mkpath(char *dir, char *name, char *out, size_t n)
  451. {
  452. /* Handle absolute path */
  453. if (name[0] == '/')
  454. strlcpy(out, name, n);
  455. else {
  456. /* Handle root case */
  457. if (strcmp(dir, "/") == 0)
  458. snprintf(out, n, "/%s", name);
  459. else
  460. snprintf(out, n, "%s/%s", dir, name);
  461. }
  462. return out;
  463. }
  464. static void
  465. printent(struct entry *ent, int active)
  466. {
  467. if (S_ISDIR(ent->mode))
  468. printw("%s%s/\n", CURSYM(active), ent->name);
  469. else if (S_ISLNK(ent->mode))
  470. printw("%s%s@\n", CURSYM(active), ent->name);
  471. else if (S_ISSOCK(ent->mode))
  472. printw("%s%s=\n", CURSYM(active), ent->name);
  473. else if (S_ISFIFO(ent->mode))
  474. printw("%s%s|\n", CURSYM(active), ent->name);
  475. else if (ent->mode & S_IXUSR)
  476. printw("%s%s*\n", CURSYM(active), ent->name);
  477. else
  478. printw("%s%s\n", CURSYM(active), ent->name);
  479. }
  480. static void (*printptr)(struct entry *ent, int active) = &printent;
  481. static char*
  482. coolsize(off_t size)
  483. {
  484. static char size_buf[12]; /* Buffer to hold human readable size */
  485. int i = 0;
  486. long double fsize = (double)size;
  487. while (fsize > 1024) {
  488. fsize /= 1024;
  489. i++;
  490. }
  491. snprintf(size_buf, 12, "%.*Lf%s", i, fsize, size_units[i]);
  492. return size_buf;
  493. }
  494. static void
  495. printent_long(struct entry *ent, int active)
  496. {
  497. static char buf[18];
  498. static const struct tm *p;
  499. p = localtime(&ent->t);
  500. strftime(buf, 18, "%b %d %H:%M %Y", p);
  501. if (active)
  502. attron(A_REVERSE);
  503. if (S_ISDIR(ent->mode))
  504. printw("%s%-17.17s / %s/\n",
  505. CURSYM(active), buf, ent->name);
  506. else if (S_ISLNK(ent->mode))
  507. printw("%s%-17.17s @ %s@\n",
  508. CURSYM(active), buf, ent->name);
  509. else if (S_ISSOCK(ent->mode))
  510. printw("%s%-17.17s = %s=\n",
  511. CURSYM(active), buf, ent->name);
  512. else if (S_ISFIFO(ent->mode))
  513. printw("%s%-17.17s | %s|\n",
  514. CURSYM(active), buf, ent->name);
  515. else if (S_ISBLK(ent->mode))
  516. printw("%s%-17.17s b %s\n",
  517. CURSYM(active), buf, ent->name);
  518. else if (S_ISCHR(ent->mode))
  519. printw("%s%-17.17s c %s\n",
  520. CURSYM(active), buf, ent->name);
  521. else if (ent->mode & S_IXUSR)
  522. printw("%s%-17.17s %8.8s* %s*\n", CURSYM(active),
  523. buf, coolsize(ent->size), ent->name);
  524. else
  525. printw("%s%-17.17s %8.8s %s\n", CURSYM(active),
  526. buf, coolsize(ent->size), ent->name);
  527. if (active)
  528. attroff(A_REVERSE);
  529. }
  530. static int
  531. dentfill(char *path, struct entry **dents,
  532. int (*filter)(regex_t *, char *), regex_t *re)
  533. {
  534. char newpath[PATH_MAX];
  535. DIR *dirp;
  536. struct dirent *dp;
  537. struct stat sb;
  538. int r, n = 0;
  539. dirp = opendir(path);
  540. if (dirp == NULL)
  541. return 0;
  542. while ((dp = readdir(dirp)) != NULL) {
  543. /* Skip self and parent */
  544. if (strcmp(dp->d_name, ".") == 0 ||
  545. strcmp(dp->d_name, "..") == 0)
  546. continue;
  547. if (filter(re, dp->d_name) == 0)
  548. continue;
  549. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  550. strlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  551. /* Get mode flags */
  552. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  553. r = lstat(newpath, &sb);
  554. if (r == -1)
  555. printerr(1, "lstat");
  556. (*dents)[n].mode = sb.st_mode;
  557. (*dents)[n].t = sb.st_mtime;
  558. (*dents)[n].size = sb.st_size;
  559. n++;
  560. }
  561. /* Should never be null */
  562. r = closedir(dirp);
  563. if (r == -1)
  564. printerr(1, "closedir");
  565. return n;
  566. }
  567. static void
  568. dentfree(struct entry *dents)
  569. {
  570. free(dents);
  571. }
  572. /* Return the position of the matching entry or 0 otherwise */
  573. static int
  574. dentfind(struct entry *dents, int n, char *path)
  575. {
  576. if (!path)
  577. return 0;
  578. char *p = xmemrchr(path, '/', strlen(path));
  579. if (!p)
  580. p = path;
  581. else
  582. /* We are assuming an entry with actual
  583. name ending in '/' will not appear */
  584. p++;
  585. DPRINTF_S(p);
  586. for (int i = 0; i < n; i++)
  587. if (strcmp(p, dents[i].name) == 0)
  588. return i;
  589. return 0;
  590. }
  591. static int
  592. populate(char *path, char *oldpath, char *fltr)
  593. {
  594. regex_t re;
  595. int r;
  596. /* Can fail when permissions change while browsing */
  597. if (canopendir(path) == 0)
  598. return -1;
  599. /* Search filter */
  600. r = setfilter(&re, fltr);
  601. if (r != 0)
  602. return -1;
  603. dentfree(dents);
  604. ndents = 0;
  605. dents = NULL;
  606. ndents = dentfill(path, &dents, visible, &re);
  607. qsort(dents, ndents, sizeof(*dents), entrycmp);
  608. /* Find cur from history */
  609. cur = dentfind(dents, ndents, oldpath);
  610. return 0;
  611. }
  612. static void
  613. redraw(char *path)
  614. {
  615. static char cwd[PATH_MAX];
  616. static int nlines, odd;
  617. static int i;
  618. nlines = MIN(LINES - 4, ndents);
  619. /* Clean screen */
  620. erase();
  621. /* Strip trailing slashes */
  622. for (i = strlen(path) - 1; i > 0; i--)
  623. if (path[i] == '/')
  624. path[i] = '\0';
  625. else
  626. break;
  627. DPRINTF_D(cur);
  628. DPRINTF_S(path);
  629. /* No text wrapping in cwd line */
  630. if (!realpath(path, cwd)) {
  631. printmsg("Cannot resolve path");
  632. return;
  633. }
  634. printw(CWD "%s\n\n", cwd);
  635. /* Print listing */
  636. odd = ISODD(nlines);
  637. if (cur < (nlines >> 1)) {
  638. for (i = 0; i < nlines; i++)
  639. printptr(&dents[i], i == cur);
  640. } else if (cur >= ndents - (nlines >> 1)) {
  641. for (i = ndents - nlines; i < ndents; i++)
  642. printptr(&dents[i], i == cur);
  643. } else {
  644. nlines >>= 1;
  645. for (i = cur - nlines; i < cur + nlines + odd; i++)
  646. printptr(&dents[i], i == cur);
  647. }
  648. if (showdetail) {
  649. if (ndents) {
  650. static char ind[2] = "\0\0";
  651. static char sort[9];
  652. if (mtimeorder)
  653. sprintf(sort, "by time ");
  654. else if (sizeorder)
  655. sprintf(sort, "by size ");
  656. else
  657. sort[0] = '\0';
  658. if (S_ISDIR(dents[cur].mode))
  659. ind[0] = '/';
  660. else if (S_ISLNK(dents[cur].mode))
  661. ind[0] = '@';
  662. else if (S_ISSOCK(dents[cur].mode))
  663. ind[0] = '=';
  664. else if (S_ISFIFO(dents[cur].mode))
  665. ind[0] = '|';
  666. else if (dents[cur].mode & S_IXUSR)
  667. ind[0] = '*';
  668. else
  669. ind[0] = '\0';
  670. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  671. dents[cur].name, ind);
  672. printmsg(cwd);
  673. } else
  674. printmsg("0 items");
  675. }
  676. }
  677. static void
  678. browse(char *ipath, char *ifilter)
  679. {
  680. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  681. static char fltr[LINE_MAX];
  682. char *bin, *dir, *tmp, *run, *env;
  683. struct stat sb;
  684. regex_t re;
  685. int r, fd;
  686. strlcpy(path, ipath, sizeof(path));
  687. strlcpy(fltr, ifilter, sizeof(fltr));
  688. oldpath[0] = '\0';
  689. newpath[0] = '\0';
  690. begin:
  691. r = populate(path, oldpath, fltr);
  692. if (r == -1) {
  693. printwarn();
  694. goto nochange;
  695. }
  696. for (;;) {
  697. redraw(path);
  698. nochange:
  699. switch (nextsel(&run, &env)) {
  700. case SEL_QUIT:
  701. dentfree(dents);
  702. return;
  703. case SEL_BACK:
  704. /* There is no going back */
  705. if (strcmp(path, "/") == 0 ||
  706. strcmp(path, ".") == 0 ||
  707. strchr(path, '/') == NULL) {
  708. printmsg("You are at /");
  709. goto nochange;
  710. }
  711. dir = xdirname(path);
  712. if (canopendir(dir) == 0) {
  713. printwarn();
  714. goto nochange;
  715. }
  716. /* Save history */
  717. strlcpy(oldpath, path, sizeof(oldpath));
  718. strlcpy(path, dir, sizeof(path));
  719. /* Reset filter */
  720. strlcpy(fltr, ifilter, sizeof(fltr));
  721. goto begin;
  722. case SEL_GOIN:
  723. /* Cannot descend in empty directories */
  724. if (ndents == 0)
  725. goto nochange;
  726. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  727. DPRINTF_S(newpath);
  728. /* Get path info */
  729. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  730. if (fd == -1) {
  731. printwarn();
  732. goto nochange;
  733. }
  734. r = fstat(fd, &sb);
  735. if (r == -1) {
  736. printwarn();
  737. close(fd);
  738. goto nochange;
  739. }
  740. close(fd);
  741. DPRINTF_U(sb.st_mode);
  742. switch (sb.st_mode & S_IFMT) {
  743. case S_IFDIR:
  744. if (canopendir(newpath) == 0) {
  745. printwarn();
  746. goto nochange;
  747. }
  748. strlcpy(path, newpath, sizeof(path));
  749. /* Reset filter */
  750. strlcpy(fltr, ifilter, sizeof(fltr));
  751. goto begin;
  752. case S_IFREG:
  753. {
  754. static char cmd[MAX_CMD_LEN];
  755. static char *runvi = "vi";
  756. static int status;
  757. static FILE *fp;
  758. /* If default mime opener is set, use it */
  759. if (opener) {
  760. snprintf(cmd, MAX_CMD_LEN,
  761. "%s \"%s\" > /dev/null 2>&1",
  762. opener, newpath);
  763. status = system(cmd);
  764. continue;
  765. }
  766. /* Try custom applications */
  767. bin = openwith(newpath);
  768. if (bin == NULL) {
  769. /* If a custom handler application is
  770. not set, open plain text files with
  771. vi, then try fallback_opener */
  772. snprintf(cmd, MAX_CMD_LEN,
  773. "file \"%s\"", newpath);
  774. fp = popen(cmd, "r");
  775. if (fp == NULL)
  776. goto nochange;
  777. if (fgets(cmd, MAX_CMD_LEN, fp) == NULL) {
  778. pclose(fp);
  779. goto nochange;
  780. }
  781. pclose(fp);
  782. if (strstr(cmd, "ASCII text") != NULL)
  783. bin = runvi;
  784. else if (fallback_opener) {
  785. snprintf(cmd, MAX_CMD_LEN,
  786. "%s \"%s\" > \
  787. /dev/null 2>&1",
  788. fallback_opener,
  789. newpath);
  790. status = system(cmd);
  791. continue;
  792. } else {
  793. printmsg("No association");
  794. goto nochange;
  795. }
  796. }
  797. exitcurses();
  798. spawn(bin, newpath, NULL);
  799. initcurses();
  800. continue;
  801. }
  802. default:
  803. printmsg("Unsupported file");
  804. goto nochange;
  805. }
  806. case SEL_FLTR:
  807. /* Read filter */
  808. printprompt("filter: ");
  809. tmp = readln();
  810. if (tmp == NULL)
  811. tmp = ifilter;
  812. /* Check and report regex errors */
  813. r = setfilter(&re, tmp);
  814. if (r != 0)
  815. goto nochange;
  816. strlcpy(fltr, tmp, sizeof(fltr));
  817. DPRINTF_S(fltr);
  818. /* Save current */
  819. if (ndents > 0)
  820. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  821. goto begin;
  822. case SEL_NEXT:
  823. if (cur < ndents - 1)
  824. cur++;
  825. else if (ndents)
  826. /* Roll over, set cursor to first entry */
  827. cur = 0;
  828. break;
  829. case SEL_PREV:
  830. if (cur > 0)
  831. cur--;
  832. else if (ndents)
  833. /* Roll over, set cursor to last entry */
  834. cur = ndents - 1;
  835. break;
  836. case SEL_PGDN:
  837. if (cur < ndents - 1)
  838. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  839. break;
  840. case SEL_PGUP:
  841. if (cur > 0)
  842. cur -= MIN((LINES - 4) / 2, cur);
  843. break;
  844. case SEL_HOME:
  845. cur = 0;
  846. break;
  847. case SEL_END:
  848. cur = ndents - 1;
  849. break;
  850. case SEL_CD:
  851. /* Read target dir */
  852. printprompt("chdir: ");
  853. tmp = readln();
  854. if (tmp == NULL) {
  855. clearprompt();
  856. goto nochange;
  857. }
  858. mkpath(path, tmp, newpath, sizeof(newpath));
  859. if (canopendir(newpath) == 0) {
  860. printwarn();
  861. goto nochange;
  862. }
  863. strlcpy(path, newpath, sizeof(path));
  864. /* Reset filter */
  865. strlcpy(fltr, ifilter, sizeof(fltr));
  866. DPRINTF_S(path);
  867. goto begin;
  868. case SEL_CDHOME:
  869. tmp = getenv("HOME");
  870. if (tmp == NULL) {
  871. clearprompt();
  872. goto nochange;
  873. }
  874. if (canopendir(tmp) == 0) {
  875. printwarn();
  876. goto nochange;
  877. }
  878. strlcpy(path, tmp, sizeof(path));
  879. /* Reset filter */
  880. strlcpy(fltr, ifilter, sizeof(fltr));
  881. DPRINTF_S(path);
  882. goto begin;
  883. case SEL_TOGGLEDOT:
  884. showhidden ^= 1;
  885. initfilter(showhidden, &ifilter);
  886. strlcpy(fltr, ifilter, sizeof(fltr));
  887. goto begin;
  888. case SEL_DETAIL:
  889. showdetail = !showdetail;
  890. showdetail ? (printptr = &printent_long)
  891. : (printptr = &printent);
  892. /* Save current */
  893. if (ndents > 0)
  894. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  895. goto begin;
  896. case SEL_FSIZE:
  897. sizeorder = !sizeorder;
  898. mtimeorder = 0;
  899. /* Save current */
  900. if (ndents > 0)
  901. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  902. goto begin;
  903. case SEL_MTIME:
  904. mtimeorder = !mtimeorder;
  905. sizeorder = 0;
  906. /* Save current */
  907. if (ndents > 0)
  908. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  909. goto begin;
  910. case SEL_REDRAW:
  911. /* Save current */
  912. if (ndents > 0)
  913. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  914. goto begin;
  915. case SEL_COPY:
  916. if (copier && ndents) {
  917. char abspath[PATH_MAX];
  918. if (strcmp(path, "/") == 0)
  919. snprintf(abspath, PATH_MAX, "/%s",
  920. dents[cur].name);
  921. else
  922. snprintf(abspath, PATH_MAX, "%s/%s",
  923. path, dents[cur].name);
  924. spawn(copier, abspath, NULL);
  925. printmsg(abspath);
  926. } else if (!copier)
  927. printmsg("NNN_COPIER is not set");
  928. goto nochange;
  929. case SEL_RUN:
  930. run = xgetenv(env, run);
  931. exitcurses();
  932. spawn(run, NULL, path);
  933. initcurses();
  934. /* Re-populate as directory content may have changed */
  935. goto begin;
  936. case SEL_RUNARG:
  937. run = xgetenv(env, run);
  938. exitcurses();
  939. spawn(run, dents[cur].name, path);
  940. initcurses();
  941. break;
  942. }
  943. /* Screensaver */
  944. if (idletimeout != 0 && idle == idletimeout) {
  945. idle = 0;
  946. exitcurses();
  947. spawn(idlecmd, NULL, NULL);
  948. initcurses();
  949. }
  950. }
  951. }
  952. static void
  953. usage(void)
  954. {
  955. fprintf(stderr, "usage: nnn [-d] [dir]\n");
  956. exit(1);
  957. }
  958. int
  959. main(int argc, char *argv[])
  960. {
  961. char cwd[PATH_MAX], *ipath;
  962. char *ifilter;
  963. int opt = 0;
  964. /* Confirm we are in a terminal */
  965. if (!isatty(0) || !isatty(1)) {
  966. fprintf(stderr, "stdin or stdout is not a tty\n");
  967. exit(1);
  968. }
  969. if (argc > 3)
  970. usage();
  971. while ((opt = getopt(argc, argv, "d")) != -1) {
  972. switch (opt) {
  973. case 'd':
  974. /* Open in detail mode, if set */
  975. showdetail = 1;
  976. printptr = &printent_long;
  977. break;
  978. default:
  979. usage();
  980. }
  981. }
  982. if (argc == optind) {
  983. /* Start in the current directory */
  984. ipath = getcwd(cwd, sizeof(cwd));
  985. if (ipath == NULL)
  986. ipath = "/";
  987. } else {
  988. ipath = realpath(argv[optind], cwd);
  989. if (!ipath) {
  990. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  991. exit(1);
  992. }
  993. }
  994. if (getuid() == 0)
  995. showhidden = 1;
  996. initfilter(showhidden, &ifilter);
  997. /* Get the default desktop mime opener, if set */
  998. opener = getenv("NNN_OPENER");
  999. /* Get the fallback desktop mime opener, if set */
  1000. fallback_opener = getenv("NNN_FALLBACK_OPENER");
  1001. /* Get the default copier, if set */
  1002. copier = getenv("NNN_COPIER");
  1003. signal(SIGINT, SIG_IGN);
  1004. /* Test initial path */
  1005. if (canopendir(ipath) == 0) {
  1006. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1007. exit(1);
  1008. }
  1009. /* Set locale before curses setup */
  1010. setlocale(LC_ALL, "");
  1011. initcurses();
  1012. browse(ipath, ifilter);
  1013. exitcurses();
  1014. exit(0);
  1015. }