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.
 
 
 
 
 
 

1439 linhas
30 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 <pwd.h>
  20. #include <grp.h>
  21. #ifdef DEBUG
  22. static int
  23. xprintf(int fd, const char *fmt, ...)
  24. {
  25. char buf[BUFSIZ];
  26. int r;
  27. va_list ap;
  28. va_start(ap, fmt);
  29. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  30. if (r > 0)
  31. r = write(fd, buf, r);
  32. va_end(ap);
  33. return r;
  34. }
  35. #define DEBUG_FD 8
  36. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  37. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  38. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  39. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=0x%p\n", x)
  40. #else
  41. #define DPRINTF_D(x)
  42. #define DPRINTF_U(x)
  43. #define DPRINTF_S(x)
  44. #define DPRINTF_P(x)
  45. #endif /* DEBUG */
  46. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  47. #undef MIN
  48. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  49. #define ISODD(x) ((x) & 1)
  50. #define CONTROL(c) ((c) ^ 0x40)
  51. #define TOUPPER(ch) \
  52. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  53. #define MAX_CMD_LEN (PATH_MAX << 1)
  54. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  55. struct assoc {
  56. char *regex; /* Regex to match on filename */
  57. char *bin; /* Program */
  58. };
  59. /* Supported actions */
  60. enum action {
  61. SEL_QUIT = 1,
  62. SEL_BACK,
  63. SEL_GOIN,
  64. SEL_FLTR,
  65. SEL_NEXT,
  66. SEL_PREV,
  67. SEL_PGDN,
  68. SEL_PGUP,
  69. SEL_HOME,
  70. SEL_END,
  71. SEL_CD,
  72. SEL_CDHOME,
  73. SEL_TOGGLEDOT,
  74. SEL_DETAIL,
  75. SEL_STATS,
  76. SEL_FSIZE,
  77. SEL_MTIME,
  78. SEL_REDRAW,
  79. SEL_COPY,
  80. SEL_HELP,
  81. SEL_RUN,
  82. SEL_RUNARG,
  83. };
  84. struct key {
  85. int sym; /* Key pressed */
  86. enum action act; /* Action */
  87. char *run; /* Program to run */
  88. char *env; /* Environment variable to run */
  89. };
  90. #include "config.h"
  91. typedef struct entry {
  92. char name[PATH_MAX];
  93. mode_t mode;
  94. time_t t;
  95. off_t size;
  96. } *pEntry;
  97. typedef unsigned long ulong;
  98. /* Global context */
  99. static struct entry *dents;
  100. static int ndents, cur;
  101. static int idle;
  102. static char *opener;
  103. static char *fallback_opener;
  104. static char *copier;
  105. static const char* size_units[] = {"B", "K", "M", "G", "T", "P", "E", "Z", "Y"};
  106. /*
  107. * Layout:
  108. * .---------
  109. * | cwd: /mnt/path
  110. * |
  111. * | file0
  112. * | file1
  113. * | > file2
  114. * | file3
  115. * | file4
  116. * ...
  117. * | filen
  118. * |
  119. * | Permission denied
  120. * '------
  121. */
  122. static void printmsg(char *);
  123. static void printwarn(void);
  124. static void printerr(int, char *);
  125. static void *
  126. xrealloc(void *p, size_t size)
  127. {
  128. p = realloc(p, size);
  129. if (p == NULL)
  130. printerr(1, "realloc");
  131. return p;
  132. }
  133. static size_t
  134. xstrlcpy(char *dest, const char *src, size_t n)
  135. {
  136. size_t i;
  137. for (i = 0; i < n && *src; i++)
  138. *dest++ = *src++;
  139. if (n) {
  140. *dest = '\0';
  141. #ifdef CHECK_XSTRLCPY_RET
  142. /* Compiling this out as we are not checking
  143. the return value anywhere (controlled case).
  144. Just returning the number of bytes copied. */
  145. while(*src++)
  146. i++;
  147. #endif
  148. }
  149. return i;
  150. }
  151. /*
  152. * The poor man's implementation of memrchr(3).
  153. * We are only looking for '/' in this program.
  154. */
  155. static void *
  156. xmemrchr(const void *s, int c, size_t n)
  157. {
  158. unsigned char *p;
  159. unsigned char ch = (unsigned char)c;
  160. if (!s || !n)
  161. return NULL;
  162. p = (unsigned char *)s + n - 1;
  163. while(n--)
  164. if ((*p--) == ch)
  165. return ++p;
  166. return NULL;
  167. }
  168. #if 0
  169. /* Some implementations of dirname(3) may modify `path' and some
  170. * return a pointer inside `path'. */
  171. static char *
  172. xdirname(const char *path)
  173. {
  174. static char out[PATH_MAX];
  175. char tmp[PATH_MAX], *p;
  176. xstrlcpy(tmp, path, sizeof(tmp));
  177. p = dirname(tmp);
  178. if (p == NULL)
  179. printerr(1, "dirname");
  180. xstrlcpy(out, p, sizeof(out));
  181. return out;
  182. }
  183. #endif
  184. /*
  185. * The following dirname(3) implementation does not
  186. * change the input. We use a copy of the original.
  187. *
  188. * Modified from the glibc (GNU LGPL) version.
  189. */
  190. static char *
  191. xdirname(const char *path)
  192. {
  193. static char name[PATH_MAX];
  194. char *last_slash;
  195. xstrlcpy(name, path, PATH_MAX);
  196. /* Find last '/'. */
  197. last_slash = strrchr(name, '/');
  198. if (last_slash != NULL && last_slash != name && last_slash[1] == '\0') {
  199. /* Determine whether all remaining characters are slashes. */
  200. char *runp;
  201. for (runp = last_slash; runp != name; --runp)
  202. if (runp[-1] != '/')
  203. break;
  204. /* The '/' is the last character, we have to look further. */
  205. if (runp != name)
  206. last_slash = xmemrchr(name, '/', runp - name);
  207. }
  208. if (last_slash != NULL) {
  209. /* Determine whether all remaining characters are slashes. */
  210. char *runp;
  211. for (runp = last_slash; runp != name; --runp)
  212. if (runp[-1] != '/')
  213. break;
  214. /* Terminate the name. */
  215. if (runp == name) {
  216. /* The last slash is the first character in the string.
  217. We have to return "/". As a special case we have to
  218. return "//" if there are exactly two slashes at the
  219. beginning of the string. See XBD 4.10 Path Name
  220. Resolution for more information. */
  221. if (last_slash == name + 1)
  222. ++last_slash;
  223. else
  224. last_slash = name + 1;
  225. } else
  226. last_slash = runp;
  227. last_slash[0] = '\0';
  228. } else {
  229. /* This assignment is ill-designed but the XPG specs require to
  230. return a string containing "." in any case no directory part
  231. is found and so a static and constant string is required. */
  232. name[0] = '.';
  233. name[1] = '\0';
  234. }
  235. return name;
  236. }
  237. static void
  238. spawn(char *file, char *arg, char *dir)
  239. {
  240. pid_t pid;
  241. int status;
  242. pid = fork();
  243. if (pid == 0) {
  244. if (dir != NULL)
  245. status = chdir(dir);
  246. fprintf(stdout, "\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  247. execlp(file, file, arg, NULL);
  248. _exit(1);
  249. } else {
  250. /* Ignore interruptions */
  251. while (waitpid(pid, &status, 0) == -1)
  252. DPRINTF_D(status);
  253. DPRINTF_D(pid);
  254. }
  255. }
  256. static char *
  257. xgetenv(char *name, char *fallback)
  258. {
  259. char *value;
  260. if (name == NULL)
  261. return fallback;
  262. value = getenv(name);
  263. return value && value[0] ? value : fallback;
  264. }
  265. int xisdigit(const char c) {
  266. if (c >= '0' && c <= '9') \
  267. return 1; \
  268. return 0;
  269. }
  270. /*
  271. * We assume none of the strings are NULL.
  272. *
  273. * Let's have the logic to sort numeric names in numeric order.
  274. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  275. *
  276. * If the absolute numeric values are same, we fallback to alphasort.
  277. */
  278. static int
  279. xstricmp(const char *s1, const char *s2)
  280. {
  281. static char *c1, *c2;
  282. static long long num1, num2;
  283. num1 = strtoll(s1, &c1, 10);
  284. num2 = strtoll(s2, &c2, 10);
  285. if (*c1 == '\0' && *c2 == '\0') {
  286. if (num1 != num2) {
  287. if (num1 > num2)
  288. return 1;
  289. else
  290. return -1;
  291. }
  292. } else if (*c1 == '\0' && *c2 != '\0')
  293. return -1;
  294. else if (*c1 != '\0' && *c2 == '\0')
  295. return 1;
  296. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  297. s1++, s2++;
  298. /* In case of alphabetically same names, make sure
  299. lower case one comes before upper case one */
  300. if (!*s1 && !*s2)
  301. return 1;
  302. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  303. }
  304. static char *
  305. openwith(char *file)
  306. {
  307. regex_t regex;
  308. char *bin = NULL;
  309. unsigned int i;
  310. for (i = 0; i < LEN(assocs); i++) {
  311. if (regcomp(&regex, assocs[i].regex,
  312. REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  313. continue;
  314. if (regexec(&regex, file, 0, NULL, 0) == 0) {
  315. bin = assocs[i].bin;
  316. break;
  317. }
  318. }
  319. DPRINTF_S(bin);
  320. return bin;
  321. }
  322. static int
  323. setfilter(regex_t *regex, char *filter)
  324. {
  325. char errbuf[LINE_MAX];
  326. size_t len;
  327. int r;
  328. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  329. if (r != 0) {
  330. len = COLS;
  331. if (len > sizeof(errbuf))
  332. len = sizeof(errbuf);
  333. regerror(r, regex, errbuf, len);
  334. printmsg(errbuf);
  335. }
  336. return r;
  337. }
  338. static void
  339. initfilter(int dot, char **ifilter)
  340. {
  341. *ifilter = dot ? "." : "^[^.]";
  342. }
  343. static int
  344. visible(regex_t *regex, char *file)
  345. {
  346. return regexec(regex, file, 0, NULL, 0) == 0;
  347. }
  348. static int
  349. entrycmp(const void *va, const void *vb)
  350. {
  351. static pEntry pa, pb;
  352. pa = (pEntry)va;
  353. pb = (pEntry)vb;
  354. /* Sort directories first */
  355. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  356. return 1;
  357. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  358. return -1;
  359. /* Do the actual sorting */
  360. if (mtimeorder)
  361. return pb->t - pa->t;
  362. if (sizeorder)
  363. if (pb->size != pa->size)
  364. return pb->size - pa->size;
  365. return xstricmp(pa->name, pb->name);
  366. }
  367. static void
  368. initcurses(void)
  369. {
  370. if (initscr() == NULL) {
  371. char *term = getenv("TERM");
  372. if (term != NULL)
  373. fprintf(stderr, "error opening terminal: %s\n", term);
  374. else
  375. fprintf(stderr, "failed to initialize curses\n");
  376. exit(1);
  377. }
  378. cbreak();
  379. noecho();
  380. nonl();
  381. intrflush(stdscr, FALSE);
  382. keypad(stdscr, TRUE);
  383. curs_set(FALSE); /* Hide cursor */
  384. timeout(1000); /* One second */
  385. }
  386. static void
  387. exitcurses(void)
  388. {
  389. endwin(); /* Restore terminal */
  390. }
  391. /* Messages show up at the bottom */
  392. static void
  393. printmsg(char *msg)
  394. {
  395. move(LINES - 1, 0);
  396. printw("%s\n", msg);
  397. }
  398. /* Display warning as a message */
  399. static void
  400. printwarn(void)
  401. {
  402. printmsg(strerror(errno));
  403. }
  404. /* Kill curses and display error before exiting */
  405. static void
  406. printerr(int ret, char *prefix)
  407. {
  408. exitcurses();
  409. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  410. exit(ret);
  411. }
  412. /* Clear the last line */
  413. static void
  414. clearprompt(void)
  415. {
  416. printmsg("");
  417. }
  418. /* Print prompt on the last line */
  419. static void
  420. printprompt(char *str)
  421. {
  422. clearprompt();
  423. printw(str);
  424. }
  425. /* Returns SEL_* if key is bound and 0 otherwise.
  426. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}) */
  427. static int
  428. nextsel(char **run, char **env)
  429. {
  430. int c;
  431. unsigned int i;
  432. c = getch();
  433. if (c == -1)
  434. idle++;
  435. else
  436. idle = 0;
  437. for (i = 0; i < LEN(bindings); i++)
  438. if (c == bindings[i].sym) {
  439. *run = bindings[i].run;
  440. *env = bindings[i].env;
  441. return bindings[i].act;
  442. }
  443. return 0;
  444. }
  445. static char *
  446. readln(void)
  447. {
  448. static char ln[LINE_MAX];
  449. timeout(-1);
  450. echo();
  451. curs_set(TRUE);
  452. memset(ln, 0, sizeof(ln));
  453. wgetnstr(stdscr, ln, sizeof(ln) - 1);
  454. noecho();
  455. curs_set(FALSE);
  456. timeout(1000);
  457. return ln[0] ? ln : NULL;
  458. }
  459. static int
  460. canopendir(char *path)
  461. {
  462. DIR *dirp;
  463. dirp = opendir(path);
  464. if (dirp == NULL)
  465. return 0;
  466. closedir(dirp);
  467. return 1;
  468. }
  469. /*
  470. * Returns "dir/name or "/name"
  471. */
  472. static char *
  473. mkpath(char *dir, char *name, char *out, size_t n)
  474. {
  475. /* Handle absolute path */
  476. if (name[0] == '/')
  477. xstrlcpy(out, name, n);
  478. else {
  479. /* Handle root case */
  480. if (strcmp(dir, "/") == 0)
  481. snprintf(out, n, "/%s", name);
  482. else
  483. snprintf(out, n, "%s/%s", dir, name);
  484. }
  485. return out;
  486. }
  487. static void
  488. printent(struct entry *ent, int active)
  489. {
  490. if (S_ISDIR(ent->mode))
  491. printw("%s%s/\n", CURSYM(active), ent->name);
  492. else if (S_ISLNK(ent->mode))
  493. printw("%s%s@\n", CURSYM(active), ent->name);
  494. else if (S_ISSOCK(ent->mode))
  495. printw("%s%s=\n", CURSYM(active), ent->name);
  496. else if (S_ISFIFO(ent->mode))
  497. printw("%s%s|\n", CURSYM(active), ent->name);
  498. else if (ent->mode & S_IXUSR)
  499. printw("%s%s*\n", CURSYM(active), ent->name);
  500. else
  501. printw("%s%s\n", CURSYM(active), ent->name);
  502. }
  503. static void (*printptr)(struct entry *ent, int active) = &printent;
  504. static char*
  505. coolsize(off_t size)
  506. {
  507. static char size_buf[12]; /* Buffer to hold human readable size */
  508. int i = 0;
  509. long double fsize = (double)size;
  510. while (fsize > 1024) {
  511. fsize /= 1024;
  512. i++;
  513. }
  514. snprintf(size_buf, 12, "%.*Lf%s", i, fsize, size_units[i]);
  515. return size_buf;
  516. }
  517. static void
  518. printent_long(struct entry *ent, int active)
  519. {
  520. static char buf[18];
  521. strftime(buf, 18, "%b %d %H:%M %Y", localtime(&ent->t));
  522. if (active)
  523. attron(A_REVERSE);
  524. if (S_ISDIR(ent->mode))
  525. printw("%s%-17.17s / %s/\n",
  526. CURSYM(active), buf, ent->name);
  527. else if (S_ISLNK(ent->mode))
  528. printw("%s%-17.17s @ %s@\n",
  529. CURSYM(active), buf, ent->name);
  530. else if (S_ISSOCK(ent->mode))
  531. printw("%s%-17.17s = %s=\n",
  532. CURSYM(active), buf, ent->name);
  533. else if (S_ISFIFO(ent->mode))
  534. printw("%s%-17.17s | %s|\n",
  535. CURSYM(active), buf, ent->name);
  536. else if (S_ISBLK(ent->mode))
  537. printw("%s%-17.17s b %s\n",
  538. CURSYM(active), buf, ent->name);
  539. else if (S_ISCHR(ent->mode))
  540. printw("%s%-17.17s c %s\n",
  541. CURSYM(active), buf, ent->name);
  542. else if (ent->mode & S_IXUSR)
  543. printw("%s%-17.17s %8.8s* %s*\n", CURSYM(active),
  544. buf, coolsize(ent->size), ent->name);
  545. else
  546. printw("%s%-17.17s %8.8s %s\n", CURSYM(active),
  547. buf, coolsize(ent->size), ent->name);
  548. if (active)
  549. attroff(A_REVERSE);
  550. }
  551. static char
  552. get_fileind(mode_t mode, char *desc)
  553. {
  554. char c;
  555. if (S_ISREG(mode)) {
  556. c = '-';
  557. sprintf(desc, "%s", "regular file");
  558. if (mode & S_IXUSR)
  559. strcat(desc, ", executable");
  560. } else if (S_ISDIR(mode)) {
  561. c = 'd';
  562. sprintf(desc, "%s", "directory");
  563. } else if (S_ISBLK(mode)) {
  564. c = 'b';
  565. sprintf(desc, "%s", "block special device");
  566. } else if (S_ISCHR(mode)) {
  567. c = 'c';
  568. sprintf(desc, "%s", "character special device");
  569. #ifdef S_ISFIFO
  570. } else if (S_ISFIFO(mode)) {
  571. c = 'p';
  572. sprintf(desc, "%s", "FIFO");
  573. #endif /* S_ISFIFO */
  574. #ifdef S_ISLNK
  575. } else if (S_ISLNK(mode)) {
  576. c = 'l';
  577. sprintf(desc, "%s", "symbolic link");
  578. #endif /* S_ISLNK */
  579. #ifdef S_ISSOCK
  580. } else if (S_ISSOCK(mode)) {
  581. c = 's';
  582. sprintf(desc, "%s", "socket");
  583. #endif /* S_ISSOCK */
  584. #ifdef S_ISDOOR
  585. /* Solaris 2.6, etc. */
  586. } else if (S_ISDOOR(mode)) {
  587. c = 'D';
  588. desc[0] = '\0';
  589. #endif /* S_ISDOOR */
  590. } else {
  591. /* Unknown type -- possibly a regular file? */
  592. c = '?';
  593. desc[0] = '\0';
  594. }
  595. return(c);
  596. }
  597. /* Convert a mode field into "ls -l" type perms field. */
  598. static char *
  599. get_lsperms(mode_t mode, char *desc)
  600. {
  601. static const char *rwx[] = {"---", "--x", "-w-", "-wx",
  602. "r--", "r-x", "rw-", "rwx"};
  603. static char bits[11];
  604. bits[0] = get_fileind(mode, desc);
  605. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  606. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  607. strcpy(&bits[7], rwx[(mode & 7)]);
  608. if (mode & S_ISUID)
  609. bits[3] = (mode & S_IXUSR) ? 's' : 'S';
  610. if (mode & S_ISGID)
  611. bits[6] = (mode & S_IXGRP) ? 's' : 'l';
  612. if (mode & S_ISVTX)
  613. bits[9] = (mode & S_IXOTH) ? 't' : 'T';
  614. bits[10] = '\0';
  615. return(bits);
  616. }
  617. char *
  618. get_output(char *buf, size_t bytes)
  619. {
  620. char *ret;
  621. FILE *pf = popen(buf, "r");
  622. if (pf) {
  623. ret = fgets(buf, bytes, pf);
  624. pclose(pf);
  625. return ret;
  626. }
  627. return NULL;
  628. }
  629. /*
  630. * Follows the stat(1) output closely
  631. */
  632. void
  633. show_stats(char* fpath, char* fname, struct stat *sb)
  634. {
  635. char buf[PATH_MAX + 48];
  636. char *perms = get_lsperms(sb->st_mode, buf);
  637. char *p, *begin = buf;
  638. clear();
  639. /* Show file name or 'symlink' -> 'target' */
  640. if (perms[0] == 'l') {
  641. char symtgt[PATH_MAX];
  642. ssize_t len = readlink(fpath, symtgt, PATH_MAX);
  643. if (len != -1) {
  644. symtgt[len] = '\0';
  645. printw("\n\n File: '%s' -> '%s'", fname, symtgt);
  646. }
  647. } else
  648. printw("\n File: '%s'", fname);
  649. /* Show size, blocks, file type */
  650. printw("\n Size: %-15llu Blocks: %-10llu IO Block: %-6llu %s",
  651. sb->st_size, sb->st_blocks, sb->st_blksize, buf);
  652. /* Show containing device, inode, hardlink count */
  653. sprintf(buf, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  654. printw("\n Device: %-15s Inode: %-11lu Links: %-9lu",
  655. buf, sb->st_ino, sb->st_nlink);
  656. /* Show major, minor number for block or char device */
  657. if (perms[0] == 'b' || perms[0] == 'c')
  658. printw(" Device type: %lx,%lx",
  659. major(sb->st_rdev), minor(sb->st_rdev));
  660. /* Show permissions, owner, group */
  661. printw("\n Access: 0%d%d%d/%s Uid: (%lu/%s) Gid: (%lu/%s)",
  662. (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7, sb->st_mode & 7,
  663. perms,
  664. sb->st_uid, (getpwuid(sb->st_uid))->pw_name,
  665. sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  666. /* Show last access time */
  667. strftime(buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  668. printw("\n\n Access: %s", buf);
  669. /* Show last modification time */
  670. strftime(buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  671. printw("\n Modify: %s", buf);
  672. /* Show last status change time */
  673. strftime(buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  674. printw("\n Change: %s", buf);
  675. if (S_ISREG(sb->st_mode)) {
  676. /* Show file(1) output */
  677. sprintf(buf, "file -b \"%s\" 2>&1", fpath);
  678. p = get_output(buf, PATH_MAX + 48);
  679. if (p) {
  680. printw("\n\n ");
  681. while (*p) {
  682. if (*p == ',') {
  683. *p = '\0';
  684. printw(" %s\n", begin);
  685. begin = p + 1;
  686. }
  687. p++;
  688. }
  689. printw(" %s", begin);
  690. }
  691. /* Show md5 */
  692. sprintf(buf, "openssl md5 \"%s\" 2>&1", fpath);
  693. p = get_output(buf, PATH_MAX + 48);
  694. if (p) {
  695. p = xmemrchr(buf, ' ', strlen(buf));
  696. if (!p)
  697. p = buf;
  698. else
  699. p++;
  700. printw("\n md5: %s", p);
  701. }
  702. /* Show sha256 */
  703. sprintf(buf, "openssl sha256 \"%s\" 2>&1", fpath);
  704. p = get_output(buf, PATH_MAX + 48);
  705. if (p) {
  706. p = xmemrchr(buf, ' ', strlen(buf));
  707. if (!p)
  708. p = buf;
  709. else
  710. p++;
  711. printw(" sha256: %s", p);
  712. }
  713. }
  714. /* Show exit keys */
  715. printw("\n\n << (q/Esc)");
  716. for (*buf = getch(); *buf != 'q' && *buf != 27; *buf = getch())
  717. if (*buf == 'q' || *buf == 27)
  718. return;
  719. }
  720. void
  721. show_help(void)
  722. {
  723. char c;
  724. clear();
  725. printw("\n\
  726. << Key >> << Function >>\n\n\
  727. [Up], k, ^P Previous entry\n\
  728. [Down], j, ^N Next entry\n\
  729. [PgUp], ^U Scroll half page up\n\
  730. [PgDn], ^D Scroll half page down\n\
  731. [Home], g, ^, ^A Jump to first entry\n\
  732. [End], G, $, ^E Jump to last entry\n\
  733. [Right], [Enter], l, ^M Open file or enter dir\n\
  734. [Left], [Backspace], h, ^H Go to parent dir\n\
  735. ~ Jump to HOME dir\n\
  736. /, & Filter dir contents\n\
  737. c Show change dir prompt\n\
  738. d Toggle detail view\n\
  739. D Show details of selected file\n\
  740. . Toggle hide .dot files\n\
  741. s Toggle sort by file size\n\
  742. t Toggle sort by modified time\n\
  743. ! Spawn SHELL in PWD (fallback sh)\n\
  744. z Run top\n\
  745. e Edit entry in EDITOR (fallback vi)\n\
  746. p Open entry in PAGER (fallback less)\n\
  747. ^K Invoke file name copier\n\
  748. ^L Force a redraw\n\
  749. ? Show help\n\
  750. q Quit\n");
  751. /* Show exit keys */
  752. printw("\n\n << (q/Esc)");
  753. for (c = getch(); c != 'q' && c != 27; c = getch())
  754. if (c == 'q' || c == 27)
  755. return;
  756. }
  757. static int
  758. dentfill(char *path, struct entry **dents,
  759. int (*filter)(regex_t *, char *), regex_t *re)
  760. {
  761. char newpath[PATH_MAX];
  762. DIR *dirp;
  763. struct dirent *dp;
  764. struct stat sb;
  765. int r, n = 0;
  766. dirp = opendir(path);
  767. if (dirp == NULL)
  768. return 0;
  769. while ((dp = readdir(dirp)) != NULL) {
  770. /* Skip self and parent */
  771. if (strcmp(dp->d_name, ".") == 0 ||
  772. strcmp(dp->d_name, "..") == 0)
  773. continue;
  774. if (filter(re, dp->d_name) == 0)
  775. continue;
  776. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  777. xstrlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  778. /* Get mode flags */
  779. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  780. r = lstat(newpath, &sb);
  781. if (r == -1)
  782. printerr(1, "lstat");
  783. (*dents)[n].mode = sb.st_mode;
  784. (*dents)[n].t = sb.st_mtime;
  785. (*dents)[n].size = sb.st_size;
  786. n++;
  787. }
  788. /* Should never be null */
  789. r = closedir(dirp);
  790. if (r == -1)
  791. printerr(1, "closedir");
  792. return n;
  793. }
  794. static void
  795. dentfree(struct entry *dents)
  796. {
  797. free(dents);
  798. }
  799. /* Return the position of the matching entry or 0 otherwise */
  800. static int
  801. dentfind(struct entry *dents, int n, char *path)
  802. {
  803. if (!path)
  804. return 0;
  805. int i;
  806. char *p = xmemrchr(path, '/', strlen(path));
  807. if (!p)
  808. p = path;
  809. else
  810. /* We are assuming an entry with actual
  811. name ending in '/' will not appear */
  812. p++;
  813. DPRINTF_S(p);
  814. for (i = 0; i < n; i++)
  815. if (strcmp(p, dents[i].name) == 0)
  816. return i;
  817. return 0;
  818. }
  819. static int
  820. populate(char *path, char *oldpath, char *fltr)
  821. {
  822. regex_t re;
  823. int r;
  824. /* Can fail when permissions change while browsing */
  825. if (canopendir(path) == 0)
  826. return -1;
  827. /* Search filter */
  828. r = setfilter(&re, fltr);
  829. if (r != 0)
  830. return -1;
  831. dentfree(dents);
  832. ndents = 0;
  833. dents = NULL;
  834. ndents = dentfill(path, &dents, visible, &re);
  835. qsort(dents, ndents, sizeof(*dents), entrycmp);
  836. /* Find cur from history */
  837. cur = dentfind(dents, ndents, oldpath);
  838. return 0;
  839. }
  840. static void
  841. redraw(char *path)
  842. {
  843. static char cwd[PATH_MAX];
  844. static int nlines, odd;
  845. static int i;
  846. nlines = MIN(LINES - 4, ndents);
  847. /* Clean screen */
  848. erase();
  849. /* Strip trailing slashes */
  850. for (i = strlen(path) - 1; i > 0; i--)
  851. if (path[i] == '/')
  852. path[i] = '\0';
  853. else
  854. break;
  855. DPRINTF_D(cur);
  856. DPRINTF_S(path);
  857. /* No text wrapping in cwd line */
  858. if (!realpath(path, cwd)) {
  859. printmsg("Cannot resolve path");
  860. return;
  861. }
  862. printw(CWD "%s\n\n", cwd);
  863. /* Print listing */
  864. odd = ISODD(nlines);
  865. if (cur < (nlines >> 1)) {
  866. for (i = 0; i < nlines; i++)
  867. printptr(&dents[i], i == cur);
  868. } else if (cur >= ndents - (nlines >> 1)) {
  869. for (i = ndents - nlines; i < ndents; i++)
  870. printptr(&dents[i], i == cur);
  871. } else {
  872. nlines >>= 1;
  873. for (i = cur - nlines; i < cur + nlines + odd; i++)
  874. printptr(&dents[i], i == cur);
  875. }
  876. if (showdetail) {
  877. if (ndents) {
  878. static char ind[2] = "\0\0";
  879. static char sort[9];
  880. if (mtimeorder)
  881. sprintf(sort, "by time ");
  882. else if (sizeorder)
  883. sprintf(sort, "by size ");
  884. else
  885. sort[0] = '\0';
  886. if (S_ISDIR(dents[cur].mode))
  887. ind[0] = '/';
  888. else if (S_ISLNK(dents[cur].mode))
  889. ind[0] = '@';
  890. else if (S_ISSOCK(dents[cur].mode))
  891. ind[0] = '=';
  892. else if (S_ISFIFO(dents[cur].mode))
  893. ind[0] = '|';
  894. else if (dents[cur].mode & S_IXUSR)
  895. ind[0] = '*';
  896. else
  897. ind[0] = '\0';
  898. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  899. dents[cur].name, ind);
  900. printmsg(cwd);
  901. } else
  902. printmsg("0 items");
  903. }
  904. }
  905. static void
  906. browse(char *ipath, char *ifilter)
  907. {
  908. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  909. static char fltr[LINE_MAX];
  910. char *bin, *dir, *tmp, *run, *env;
  911. struct stat sb;
  912. regex_t re;
  913. int r, fd;
  914. xstrlcpy(path, ipath, sizeof(path));
  915. xstrlcpy(fltr, ifilter, sizeof(fltr));
  916. oldpath[0] = '\0';
  917. newpath[0] = '\0';
  918. begin:
  919. r = populate(path, oldpath, fltr);
  920. if (r == -1) {
  921. printwarn();
  922. goto nochange;
  923. }
  924. for (;;) {
  925. redraw(path);
  926. nochange:
  927. switch (nextsel(&run, &env)) {
  928. case SEL_QUIT:
  929. dentfree(dents);
  930. return;
  931. case SEL_BACK:
  932. /* There is no going back */
  933. if (strcmp(path, "/") == 0 ||
  934. strcmp(path, ".") == 0 ||
  935. strchr(path, '/') == NULL) {
  936. printmsg("You are at /");
  937. goto nochange;
  938. }
  939. dir = xdirname(path);
  940. if (canopendir(dir) == 0) {
  941. printwarn();
  942. goto nochange;
  943. }
  944. /* Save history */
  945. xstrlcpy(oldpath, path, sizeof(oldpath));
  946. xstrlcpy(path, dir, sizeof(path));
  947. /* Reset filter */
  948. xstrlcpy(fltr, ifilter, sizeof(fltr));
  949. goto begin;
  950. case SEL_GOIN:
  951. /* Cannot descend in empty directories */
  952. if (ndents == 0)
  953. goto nochange;
  954. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  955. DPRINTF_S(newpath);
  956. /* Get path info */
  957. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  958. if (fd == -1) {
  959. printwarn();
  960. goto nochange;
  961. }
  962. r = fstat(fd, &sb);
  963. if (r == -1) {
  964. printwarn();
  965. close(fd);
  966. goto nochange;
  967. }
  968. close(fd);
  969. DPRINTF_U(sb.st_mode);
  970. switch (sb.st_mode & S_IFMT) {
  971. case S_IFDIR:
  972. if (canopendir(newpath) == 0) {
  973. printwarn();
  974. goto nochange;
  975. }
  976. xstrlcpy(path, newpath, sizeof(path));
  977. /* Reset filter */
  978. xstrlcpy(fltr, ifilter, sizeof(fltr));
  979. goto begin;
  980. case S_IFREG:
  981. {
  982. static char cmd[MAX_CMD_LEN];
  983. static char *runvi = "vi";
  984. static int status;
  985. static FILE *fp;
  986. /* If default mime opener is set, use it */
  987. if (opener) {
  988. snprintf(cmd, MAX_CMD_LEN,
  989. "%s \"%s\" > /dev/null 2>&1",
  990. opener, newpath);
  991. status = system(cmd);
  992. continue;
  993. }
  994. /* Try custom applications */
  995. bin = openwith(newpath);
  996. if (bin == NULL) {
  997. /* If a custom handler application is
  998. not set, open plain text files with
  999. vi, then try fallback_opener */
  1000. snprintf(cmd, MAX_CMD_LEN,
  1001. "file \"%s\"", newpath);
  1002. fp = popen(cmd, "r");
  1003. if (fp == NULL)
  1004. goto nochange;
  1005. if (fgets(cmd, MAX_CMD_LEN, fp) == NULL) {
  1006. pclose(fp);
  1007. goto nochange;
  1008. }
  1009. pclose(fp);
  1010. if (strstr(cmd, "ASCII text") != NULL)
  1011. bin = runvi;
  1012. else if (fallback_opener) {
  1013. snprintf(cmd, MAX_CMD_LEN,
  1014. "%s \"%s\" > \
  1015. /dev/null 2>&1",
  1016. fallback_opener,
  1017. newpath);
  1018. status = system(cmd);
  1019. continue;
  1020. } else {
  1021. status++; /* Dummy operation */
  1022. printmsg("No association");
  1023. goto nochange;
  1024. }
  1025. }
  1026. exitcurses();
  1027. spawn(bin, newpath, NULL);
  1028. initcurses();
  1029. continue;
  1030. }
  1031. default:
  1032. printmsg("Unsupported file");
  1033. goto nochange;
  1034. }
  1035. case SEL_FLTR:
  1036. /* Read filter */
  1037. printprompt("filter: ");
  1038. tmp = readln();
  1039. if (tmp == NULL)
  1040. tmp = ifilter;
  1041. /* Check and report regex errors */
  1042. r = setfilter(&re, tmp);
  1043. if (r != 0)
  1044. goto nochange;
  1045. xstrlcpy(fltr, tmp, sizeof(fltr));
  1046. DPRINTF_S(fltr);
  1047. /* Save current */
  1048. if (ndents > 0)
  1049. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1050. goto begin;
  1051. case SEL_NEXT:
  1052. if (cur < ndents - 1)
  1053. cur++;
  1054. else if (ndents)
  1055. /* Roll over, set cursor to first entry */
  1056. cur = 0;
  1057. break;
  1058. case SEL_PREV:
  1059. if (cur > 0)
  1060. cur--;
  1061. else if (ndents)
  1062. /* Roll over, set cursor to last entry */
  1063. cur = ndents - 1;
  1064. break;
  1065. case SEL_PGDN:
  1066. if (cur < ndents - 1)
  1067. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1068. break;
  1069. case SEL_PGUP:
  1070. if (cur > 0)
  1071. cur -= MIN((LINES - 4) / 2, cur);
  1072. break;
  1073. case SEL_HOME:
  1074. cur = 0;
  1075. break;
  1076. case SEL_END:
  1077. cur = ndents - 1;
  1078. break;
  1079. case SEL_CD:
  1080. /* Read target dir */
  1081. printprompt("chdir: ");
  1082. tmp = readln();
  1083. if (tmp == NULL) {
  1084. clearprompt();
  1085. goto nochange;
  1086. }
  1087. mkpath(path, tmp, newpath, sizeof(newpath));
  1088. if (canopendir(newpath) == 0) {
  1089. printwarn();
  1090. goto nochange;
  1091. }
  1092. xstrlcpy(path, newpath, sizeof(path));
  1093. /* Reset filter */
  1094. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1095. DPRINTF_S(path);
  1096. goto begin;
  1097. case SEL_CDHOME:
  1098. tmp = getenv("HOME");
  1099. if (tmp == NULL) {
  1100. clearprompt();
  1101. goto nochange;
  1102. }
  1103. if (canopendir(tmp) == 0) {
  1104. printwarn();
  1105. goto nochange;
  1106. }
  1107. xstrlcpy(path, tmp, sizeof(path));
  1108. /* Reset filter */
  1109. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1110. DPRINTF_S(path);
  1111. goto begin;
  1112. case SEL_TOGGLEDOT:
  1113. showhidden ^= 1;
  1114. initfilter(showhidden, &ifilter);
  1115. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1116. goto begin;
  1117. case SEL_DETAIL:
  1118. showdetail = !showdetail;
  1119. showdetail ? (printptr = &printent_long)
  1120. : (printptr = &printent);
  1121. /* Save current */
  1122. if (ndents > 0)
  1123. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1124. goto begin;
  1125. case SEL_STATS:
  1126. {
  1127. struct stat sb;
  1128. if (ndents > 0)
  1129. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1130. r = lstat(oldpath, &sb);
  1131. if (r == -1)
  1132. printerr(1, "lstat");
  1133. else
  1134. show_stats(oldpath, dents[cur].name, &sb);
  1135. goto begin;
  1136. }
  1137. case SEL_FSIZE:
  1138. sizeorder = !sizeorder;
  1139. mtimeorder = 0;
  1140. /* Save current */
  1141. if (ndents > 0)
  1142. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1143. goto begin;
  1144. case SEL_MTIME:
  1145. mtimeorder = !mtimeorder;
  1146. sizeorder = 0;
  1147. /* Save current */
  1148. if (ndents > 0)
  1149. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1150. goto begin;
  1151. case SEL_REDRAW:
  1152. /* Save current */
  1153. if (ndents > 0)
  1154. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1155. goto begin;
  1156. case SEL_COPY:
  1157. if (copier && ndents) {
  1158. char abspath[PATH_MAX];
  1159. if (strcmp(path, "/") == 0)
  1160. snprintf(abspath, PATH_MAX, "/%s",
  1161. dents[cur].name);
  1162. else
  1163. snprintf(abspath, PATH_MAX, "%s/%s",
  1164. path, dents[cur].name);
  1165. spawn(copier, abspath, NULL);
  1166. printmsg(abspath);
  1167. } else if (!copier)
  1168. printmsg("NNN_COPIER is not set");
  1169. goto nochange;
  1170. case SEL_HELP:
  1171. show_help();
  1172. /* Save current */
  1173. if (ndents > 0)
  1174. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1175. goto begin;
  1176. case SEL_RUN:
  1177. run = xgetenv(env, run);
  1178. exitcurses();
  1179. spawn(run, NULL, path);
  1180. initcurses();
  1181. /* Re-populate as directory content may have changed */
  1182. goto begin;
  1183. case SEL_RUNARG:
  1184. run = xgetenv(env, run);
  1185. exitcurses();
  1186. spawn(run, dents[cur].name, path);
  1187. initcurses();
  1188. break;
  1189. }
  1190. /* Screensaver */
  1191. if (idletimeout != 0 && idle == idletimeout) {
  1192. idle = 0;
  1193. exitcurses();
  1194. spawn(idlecmd, NULL, NULL);
  1195. initcurses();
  1196. }
  1197. }
  1198. }
  1199. static void
  1200. usage(void)
  1201. {
  1202. fprintf(stderr, "usage: nnn [-d] [dir]\n");
  1203. exit(1);
  1204. }
  1205. int
  1206. main(int argc, char *argv[])
  1207. {
  1208. char cwd[PATH_MAX], *ipath;
  1209. char *ifilter;
  1210. int opt = 0;
  1211. /* Confirm we are in a terminal */
  1212. if (!isatty(0) || !isatty(1)) {
  1213. fprintf(stderr, "stdin or stdout is not a tty\n");
  1214. exit(1);
  1215. }
  1216. if (argc > 3)
  1217. usage();
  1218. while ((opt = getopt(argc, argv, "d")) != -1) {
  1219. switch (opt) {
  1220. case 'd':
  1221. /* Open in detail mode, if set */
  1222. showdetail = 1;
  1223. printptr = &printent_long;
  1224. break;
  1225. default:
  1226. usage();
  1227. }
  1228. }
  1229. if (argc == optind) {
  1230. /* Start in the current directory */
  1231. ipath = getcwd(cwd, sizeof(cwd));
  1232. if (ipath == NULL)
  1233. ipath = "/";
  1234. } else {
  1235. ipath = realpath(argv[optind], cwd);
  1236. if (!ipath) {
  1237. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1238. exit(1);
  1239. }
  1240. }
  1241. if (getuid() == 0)
  1242. showhidden = 1;
  1243. initfilter(showhidden, &ifilter);
  1244. /* Get the default desktop mime opener, if set */
  1245. opener = getenv("NNN_OPENER");
  1246. /* Get the fallback desktop mime opener, if set */
  1247. fallback_opener = getenv("NNN_FALLBACK_OPENER");
  1248. /* Get the default copier, if set */
  1249. copier = getenv("NNN_COPIER");
  1250. signal(SIGINT, SIG_IGN);
  1251. /* Test initial path */
  1252. if (canopendir(ipath) == 0) {
  1253. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1254. exit(1);
  1255. }
  1256. /* Set locale before curses setup */
  1257. setlocale(LC_ALL, "");
  1258. initcurses();
  1259. browse(ipath, ifilter);
  1260. exitcurses();
  1261. exit(0);
  1262. }