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.
 
 
 
 
 
 

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