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.
 
 
 
 
 
 

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