My build of nnn with minor changes
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

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