My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

1161 lignes
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. printmsg("You are at /");
  717. goto nochange;
  718. }
  719. dir = xdirname(path);
  720. if (canopendir(dir) == 0) {
  721. printwarn();
  722. goto nochange;
  723. }
  724. /* Save history */
  725. strlcpy(oldpath, path, sizeof(oldpath));
  726. strlcpy(path, dir, sizeof(path));
  727. /* Reset filter */
  728. strlcpy(fltr, ifilter, sizeof(fltr));
  729. goto begin;
  730. case SEL_GOIN:
  731. /* Cannot descend in empty directories */
  732. if (ndents == 0)
  733. goto nochange;
  734. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  735. DPRINTF_S(newpath);
  736. /* Get path info */
  737. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  738. if (fd == -1) {
  739. printwarn();
  740. goto nochange;
  741. }
  742. r = fstat(fd, &sb);
  743. if (r == -1) {
  744. printwarn();
  745. close(fd);
  746. goto nochange;
  747. }
  748. close(fd);
  749. DPRINTF_U(sb.st_mode);
  750. switch (sb.st_mode & S_IFMT) {
  751. case S_IFDIR:
  752. if (canopendir(newpath) == 0) {
  753. printwarn();
  754. goto nochange;
  755. }
  756. strlcpy(path, newpath, sizeof(path));
  757. /* Reset filter */
  758. strlcpy(fltr, ifilter, sizeof(fltr));
  759. goto begin;
  760. case S_IFREG:
  761. {
  762. static char cmd[MAX_CMD_LEN];
  763. static char *runvi = "vi";
  764. static int status;
  765. static FILE *fp;
  766. /* If default mime opener is set, use it */
  767. if (opener) {
  768. snprintf(cmd, MAX_CMD_LEN,
  769. "%s \"%s\" > /dev/null 2>&1",
  770. opener, newpath);
  771. status = system(cmd);
  772. continue;
  773. }
  774. /* Try custom applications */
  775. bin = openwith(newpath);
  776. if (bin == NULL) {
  777. /* If a custom handler application is
  778. not set, open plain text files with
  779. vi, then try fallback_opener */
  780. snprintf(cmd, MAX_CMD_LEN,
  781. "file \"%s\"", newpath);
  782. fp = popen(cmd, "r");
  783. if (fp == NULL)
  784. goto nochange;
  785. if (fgets(cmd, MAX_CMD_LEN, fp) == NULL) {
  786. pclose(fp);
  787. goto nochange;
  788. }
  789. pclose(fp);
  790. if (strstr(cmd, "ASCII text") != NULL)
  791. bin = runvi;
  792. else if (fallback_opener) {
  793. snprintf(cmd, MAX_CMD_LEN,
  794. "%s \"%s\" > \
  795. /dev/null 2>&1",
  796. fallback_opener,
  797. newpath);
  798. status = system(cmd);
  799. continue;
  800. } else {
  801. printmsg("No association");
  802. goto nochange;
  803. }
  804. }
  805. exitcurses();
  806. spawn(bin, newpath, NULL);
  807. initcurses();
  808. continue;
  809. }
  810. default:
  811. printmsg("Unsupported file");
  812. goto nochange;
  813. }
  814. case SEL_FLTR:
  815. /* Read filter */
  816. printprompt("filter: ");
  817. tmp = readln();
  818. if (tmp == NULL)
  819. tmp = ifilter;
  820. /* Check and report regex errors */
  821. r = setfilter(&re, tmp);
  822. if (r != 0)
  823. goto nochange;
  824. strlcpy(fltr, tmp, sizeof(fltr));
  825. DPRINTF_S(fltr);
  826. /* Save current */
  827. if (ndents > 0)
  828. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  829. goto begin;
  830. case SEL_NEXT:
  831. if (cur < ndents - 1)
  832. cur++;
  833. else if (ndents)
  834. /* Roll over, set cursor to first entry */
  835. cur = 0;
  836. break;
  837. case SEL_PREV:
  838. if (cur > 0)
  839. cur--;
  840. else if (ndents)
  841. /* Roll over, set cursor to last entry */
  842. cur = ndents - 1;
  843. break;
  844. case SEL_PGDN:
  845. if (cur < ndents - 1)
  846. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  847. break;
  848. case SEL_PGUP:
  849. if (cur > 0)
  850. cur -= MIN((LINES - 4) / 2, cur);
  851. break;
  852. case SEL_HOME:
  853. cur = 0;
  854. break;
  855. case SEL_END:
  856. cur = ndents - 1;
  857. break;
  858. case SEL_CD:
  859. /* Read target dir */
  860. printprompt("chdir: ");
  861. tmp = readln();
  862. if (tmp == NULL) {
  863. clearprompt();
  864. goto nochange;
  865. }
  866. mkpath(path, tmp, newpath, sizeof(newpath));
  867. if (canopendir(newpath) == 0) {
  868. printwarn();
  869. goto nochange;
  870. }
  871. strlcpy(path, newpath, sizeof(path));
  872. /* Reset filter */
  873. strlcpy(fltr, ifilter, sizeof(fltr));
  874. DPRINTF_S(path);
  875. goto begin;
  876. case SEL_CDHOME:
  877. tmp = getenv("HOME");
  878. if (tmp == NULL) {
  879. clearprompt();
  880. goto nochange;
  881. }
  882. if (canopendir(tmp) == 0) {
  883. printwarn();
  884. goto nochange;
  885. }
  886. strlcpy(path, tmp, sizeof(path));
  887. /* Reset filter */
  888. strlcpy(fltr, ifilter, sizeof(fltr));
  889. DPRINTF_S(path);
  890. goto begin;
  891. case SEL_TOGGLEDOT:
  892. showhidden ^= 1;
  893. initfilter(showhidden, &ifilter);
  894. strlcpy(fltr, ifilter, sizeof(fltr));
  895. goto begin;
  896. case SEL_DETAIL:
  897. showdetail = !showdetail;
  898. showdetail ? (printptr = &printent_long)
  899. : (printptr = &printent);
  900. /* Save current */
  901. if (ndents > 0)
  902. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  903. goto begin;
  904. case SEL_FSIZE:
  905. sizeorder = !sizeorder;
  906. mtimeorder = 0;
  907. /* Save current */
  908. if (ndents > 0)
  909. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  910. goto begin;
  911. case SEL_MTIME:
  912. mtimeorder = !mtimeorder;
  913. sizeorder = 0;
  914. /* Save current */
  915. if (ndents > 0)
  916. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  917. goto begin;
  918. case SEL_REDRAW:
  919. /* Save current */
  920. if (ndents > 0)
  921. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  922. goto begin;
  923. case SEL_COPY:
  924. if (copier && ndents) {
  925. char abspath[PATH_MAX];
  926. if (strcmp(path, "/") == 0)
  927. snprintf(abspath, PATH_MAX, "/%s",
  928. dents[cur].name);
  929. else
  930. snprintf(abspath, PATH_MAX, "%s/%s",
  931. path, dents[cur].name);
  932. spawn(copier, abspath, NULL);
  933. printmsg(abspath);
  934. } else if (!copier)
  935. printmsg("NNN_COPIER is not set");
  936. goto nochange;
  937. case SEL_RUN:
  938. run = xgetenv(env, run);
  939. exitcurses();
  940. spawn(run, NULL, path);
  941. initcurses();
  942. /* Re-populate as directory content may have changed */
  943. goto begin;
  944. case SEL_RUNARG:
  945. run = xgetenv(env, run);
  946. exitcurses();
  947. spawn(run, dents[cur].name, path);
  948. initcurses();
  949. break;
  950. }
  951. /* Screensaver */
  952. if (idletimeout != 0 && idle == idletimeout) {
  953. idle = 0;
  954. exitcurses();
  955. spawn(idlecmd, NULL, NULL);
  956. initcurses();
  957. }
  958. }
  959. }
  960. static void
  961. usage(void)
  962. {
  963. fprintf(stderr, "usage: nnn [-d] [dir]\n");
  964. exit(1);
  965. }
  966. int
  967. main(int argc, char *argv[])
  968. {
  969. char cwd[PATH_MAX], *ipath;
  970. char *ifilter;
  971. int opt = 0;
  972. /* Confirm we are in a terminal */
  973. if (!isatty(0) || !isatty(1)) {
  974. fprintf(stderr, "stdin or stdout is not a tty\n");
  975. exit(1);
  976. }
  977. if (argc > 3)
  978. usage();
  979. while ((opt = getopt(argc, argv, "d")) != -1) {
  980. switch (opt) {
  981. case 'd':
  982. /* Open in detail mode, if set */
  983. showdetail = 1;
  984. printptr = &printent_long;
  985. break;
  986. default:
  987. usage();
  988. }
  989. }
  990. if (argc == optind) {
  991. /* Start in the current directory */
  992. ipath = getcwd(cwd, sizeof(cwd));
  993. if (ipath == NULL)
  994. ipath = "/";
  995. } else {
  996. ipath = realpath(argv[optind], cwd);
  997. if (!ipath) {
  998. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  999. exit(1);
  1000. }
  1001. }
  1002. if (getuid() == 0)
  1003. showhidden = 1;
  1004. initfilter(showhidden, &ifilter);
  1005. /* Get the default desktop mime opener, if set */
  1006. opener = getenv("NNN_OPENER");
  1007. /* Get the fallback desktop mime opener, if set */
  1008. fallback_opener = getenv("NNN_FALLBACK_OPENER");
  1009. /* Get the default copier, if set */
  1010. copier = getenv("NNN_COPIER");
  1011. signal(SIGINT, SIG_IGN);
  1012. /* Test initial path */
  1013. if (canopendir(ipath) == 0) {
  1014. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1015. exit(1);
  1016. }
  1017. /* Set locale before curses setup */
  1018. setlocale(LC_ALL, "");
  1019. initcurses();
  1020. browse(ipath, ifilter);
  1021. exitcurses();
  1022. exit(0);
  1023. }