My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1442 lines
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. #ifdef SUPPORT_CHKSUM
  692. /* Calculating checksums can take VERY long */
  693. /* Show md5 */
  694. sprintf(buf, "openssl md5 \"%s\" 2>&1", fpath);
  695. p = get_output(buf, PATH_MAX + 48);
  696. if (p) {
  697. p = xmemrchr(buf, ' ', strlen(buf));
  698. if (!p)
  699. p = buf;
  700. else
  701. p++;
  702. printw("\n md5: %s", p);
  703. }
  704. /* Show sha256 */
  705. sprintf(buf, "openssl sha256 \"%s\" 2>&1", fpath);
  706. p = get_output(buf, PATH_MAX + 48);
  707. if (p) {
  708. p = xmemrchr(buf, ' ', strlen(buf));
  709. if (!p)
  710. p = buf;
  711. else
  712. p++;
  713. printw(" sha256: %s", p);
  714. }
  715. #endif
  716. }
  717. /* Show exit keys */
  718. printw("\n\n << (q/Esc)");
  719. for (*buf = getch(); *buf != 'q' && *buf != 27; *buf = getch())
  720. if (*buf == 'q' || *buf == 27)
  721. return;
  722. }
  723. void
  724. show_help(void)
  725. {
  726. char c;
  727. clear();
  728. printw("\n\
  729. << Key >> << Function >>\n\n\
  730. [Up], k, ^P Previous entry\n\
  731. [Down], j, ^N Next entry\n\
  732. [PgUp], ^U Scroll half page up\n\
  733. [PgDn], ^D Scroll half page down\n\
  734. [Home], g, ^, ^A Jump to first entry\n\
  735. [End], G, $, ^E Jump to last entry\n\
  736. [Right], [Enter], l, ^M Open file or enter dir\n\
  737. [Left], [Backspace], h, ^H Go to parent dir\n\
  738. ~ Jump to HOME dir\n\
  739. /, & Filter dir contents\n\
  740. c Show change dir prompt\n\
  741. d Toggle detail view\n\
  742. D Show details of selected file\n\
  743. . Toggle hide .dot files\n\
  744. s Toggle sort by file size\n\
  745. t Toggle sort by modified time\n\
  746. ! Spawn SHELL in PWD (fallback sh)\n\
  747. z Run top\n\
  748. e Edit entry in EDITOR (fallback vi)\n\
  749. p Open entry in PAGER (fallback less)\n\
  750. ^K Invoke file name copier\n\
  751. ^L Force a redraw\n\
  752. ? Show help\n\
  753. q Quit\n");
  754. /* Show exit keys */
  755. printw("\n\n << (q/Esc)");
  756. for (c = getch(); c != 'q' && c != 27; c = getch())
  757. if (c == 'q' || c == 27)
  758. return;
  759. }
  760. static int
  761. dentfill(char *path, struct entry **dents,
  762. int (*filter)(regex_t *, char *), regex_t *re)
  763. {
  764. char newpath[PATH_MAX];
  765. DIR *dirp;
  766. struct dirent *dp;
  767. struct stat sb;
  768. int r, n = 0;
  769. dirp = opendir(path);
  770. if (dirp == NULL)
  771. return 0;
  772. while ((dp = readdir(dirp)) != NULL) {
  773. /* Skip self and parent */
  774. if (strcmp(dp->d_name, ".") == 0 ||
  775. strcmp(dp->d_name, "..") == 0)
  776. continue;
  777. if (filter(re, dp->d_name) == 0)
  778. continue;
  779. *dents = xrealloc(*dents, (n + 1) * sizeof(**dents));
  780. xstrlcpy((*dents)[n].name, dp->d_name, sizeof((*dents)[n].name));
  781. /* Get mode flags */
  782. mkpath(path, dp->d_name, newpath, sizeof(newpath));
  783. r = lstat(newpath, &sb);
  784. if (r == -1)
  785. printerr(1, "lstat");
  786. (*dents)[n].mode = sb.st_mode;
  787. (*dents)[n].t = sb.st_mtime;
  788. (*dents)[n].size = sb.st_size;
  789. n++;
  790. }
  791. /* Should never be null */
  792. r = closedir(dirp);
  793. if (r == -1)
  794. printerr(1, "closedir");
  795. return n;
  796. }
  797. static void
  798. dentfree(struct entry *dents)
  799. {
  800. free(dents);
  801. }
  802. /* Return the position of the matching entry or 0 otherwise */
  803. static int
  804. dentfind(struct entry *dents, int n, char *path)
  805. {
  806. if (!path)
  807. return 0;
  808. int i;
  809. char *p = xmemrchr(path, '/', strlen(path));
  810. if (!p)
  811. p = path;
  812. else
  813. /* We are assuming an entry with actual
  814. name ending in '/' will not appear */
  815. p++;
  816. DPRINTF_S(p);
  817. for (i = 0; i < n; i++)
  818. if (strcmp(p, dents[i].name) == 0)
  819. return i;
  820. return 0;
  821. }
  822. static int
  823. populate(char *path, char *oldpath, char *fltr)
  824. {
  825. regex_t re;
  826. int r;
  827. /* Can fail when permissions change while browsing */
  828. if (canopendir(path) == 0)
  829. return -1;
  830. /* Search filter */
  831. r = setfilter(&re, fltr);
  832. if (r != 0)
  833. return -1;
  834. dentfree(dents);
  835. ndents = 0;
  836. dents = NULL;
  837. ndents = dentfill(path, &dents, visible, &re);
  838. qsort(dents, ndents, sizeof(*dents), entrycmp);
  839. /* Find cur from history */
  840. cur = dentfind(dents, ndents, oldpath);
  841. return 0;
  842. }
  843. static void
  844. redraw(char *path)
  845. {
  846. static char cwd[PATH_MAX];
  847. static int nlines, odd;
  848. static int i;
  849. nlines = MIN(LINES - 4, ndents);
  850. /* Clean screen */
  851. erase();
  852. /* Strip trailing slashes */
  853. for (i = strlen(path) - 1; i > 0; i--)
  854. if (path[i] == '/')
  855. path[i] = '\0';
  856. else
  857. break;
  858. DPRINTF_D(cur);
  859. DPRINTF_S(path);
  860. /* No text wrapping in cwd line */
  861. if (!realpath(path, cwd)) {
  862. printmsg("Cannot resolve path");
  863. return;
  864. }
  865. printw(CWD "%s\n\n", cwd);
  866. /* Print listing */
  867. odd = ISODD(nlines);
  868. if (cur < (nlines >> 1)) {
  869. for (i = 0; i < nlines; i++)
  870. printptr(&dents[i], i == cur);
  871. } else if (cur >= ndents - (nlines >> 1)) {
  872. for (i = ndents - nlines; i < ndents; i++)
  873. printptr(&dents[i], i == cur);
  874. } else {
  875. nlines >>= 1;
  876. for (i = cur - nlines; i < cur + nlines + odd; i++)
  877. printptr(&dents[i], i == cur);
  878. }
  879. if (showdetail) {
  880. if (ndents) {
  881. static char ind[2] = "\0\0";
  882. static char sort[9];
  883. if (mtimeorder)
  884. sprintf(sort, "by time ");
  885. else if (sizeorder)
  886. sprintf(sort, "by size ");
  887. else
  888. sort[0] = '\0';
  889. if (S_ISDIR(dents[cur].mode))
  890. ind[0] = '/';
  891. else if (S_ISLNK(dents[cur].mode))
  892. ind[0] = '@';
  893. else if (S_ISSOCK(dents[cur].mode))
  894. ind[0] = '=';
  895. else if (S_ISFIFO(dents[cur].mode))
  896. ind[0] = '|';
  897. else if (dents[cur].mode & S_IXUSR)
  898. ind[0] = '*';
  899. else
  900. ind[0] = '\0';
  901. sprintf(cwd, "total %d %s[%s%s]", ndents, sort,
  902. dents[cur].name, ind);
  903. printmsg(cwd);
  904. } else
  905. printmsg("0 items");
  906. }
  907. }
  908. static void
  909. browse(char *ipath, char *ifilter)
  910. {
  911. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX];
  912. static char fltr[LINE_MAX];
  913. char *bin, *dir, *tmp, *run, *env;
  914. struct stat sb;
  915. regex_t re;
  916. int r, fd;
  917. xstrlcpy(path, ipath, sizeof(path));
  918. xstrlcpy(fltr, ifilter, sizeof(fltr));
  919. oldpath[0] = '\0';
  920. newpath[0] = '\0';
  921. begin:
  922. r = populate(path, oldpath, fltr);
  923. if (r == -1) {
  924. printwarn();
  925. goto nochange;
  926. }
  927. for (;;) {
  928. redraw(path);
  929. nochange:
  930. switch (nextsel(&run, &env)) {
  931. case SEL_QUIT:
  932. dentfree(dents);
  933. return;
  934. case SEL_BACK:
  935. /* There is no going back */
  936. if (strcmp(path, "/") == 0 ||
  937. strcmp(path, ".") == 0 ||
  938. strchr(path, '/') == NULL) {
  939. printmsg("You are at /");
  940. goto nochange;
  941. }
  942. dir = xdirname(path);
  943. if (canopendir(dir) == 0) {
  944. printwarn();
  945. goto nochange;
  946. }
  947. /* Save history */
  948. xstrlcpy(oldpath, path, sizeof(oldpath));
  949. xstrlcpy(path, dir, sizeof(path));
  950. /* Reset filter */
  951. xstrlcpy(fltr, ifilter, sizeof(fltr));
  952. goto begin;
  953. case SEL_GOIN:
  954. /* Cannot descend in empty directories */
  955. if (ndents == 0)
  956. goto nochange;
  957. mkpath(path, dents[cur].name, newpath, sizeof(newpath));
  958. DPRINTF_S(newpath);
  959. /* Get path info */
  960. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  961. if (fd == -1) {
  962. printwarn();
  963. goto nochange;
  964. }
  965. r = fstat(fd, &sb);
  966. if (r == -1) {
  967. printwarn();
  968. close(fd);
  969. goto nochange;
  970. }
  971. close(fd);
  972. DPRINTF_U(sb.st_mode);
  973. switch (sb.st_mode & S_IFMT) {
  974. case S_IFDIR:
  975. if (canopendir(newpath) == 0) {
  976. printwarn();
  977. goto nochange;
  978. }
  979. xstrlcpy(path, newpath, sizeof(path));
  980. /* Reset filter */
  981. xstrlcpy(fltr, ifilter, sizeof(fltr));
  982. goto begin;
  983. case S_IFREG:
  984. {
  985. static char cmd[MAX_CMD_LEN];
  986. static char *runvi = "vi";
  987. static int status;
  988. static FILE *fp;
  989. /* If default mime opener is set, use it */
  990. if (opener) {
  991. snprintf(cmd, MAX_CMD_LEN,
  992. "%s \"%s\" > /dev/null 2>&1",
  993. opener, newpath);
  994. status = system(cmd);
  995. continue;
  996. }
  997. /* Try custom applications */
  998. bin = openwith(newpath);
  999. if (bin == NULL) {
  1000. /* If a custom handler application is
  1001. not set, open plain text files with
  1002. vi, then try fallback_opener */
  1003. snprintf(cmd, MAX_CMD_LEN,
  1004. "file \"%s\"", newpath);
  1005. fp = popen(cmd, "r");
  1006. if (fp == NULL)
  1007. goto nochange;
  1008. if (fgets(cmd, MAX_CMD_LEN, fp) == NULL) {
  1009. pclose(fp);
  1010. goto nochange;
  1011. }
  1012. pclose(fp);
  1013. if (strstr(cmd, "ASCII text") != NULL)
  1014. bin = runvi;
  1015. else if (fallback_opener) {
  1016. snprintf(cmd, MAX_CMD_LEN,
  1017. "%s \"%s\" > \
  1018. /dev/null 2>&1",
  1019. fallback_opener,
  1020. newpath);
  1021. status = system(cmd);
  1022. continue;
  1023. } else {
  1024. status++; /* Dummy operation */
  1025. printmsg("No association");
  1026. goto nochange;
  1027. }
  1028. }
  1029. exitcurses();
  1030. spawn(bin, newpath, NULL);
  1031. initcurses();
  1032. continue;
  1033. }
  1034. default:
  1035. printmsg("Unsupported file");
  1036. goto nochange;
  1037. }
  1038. case SEL_FLTR:
  1039. /* Read filter */
  1040. printprompt("filter: ");
  1041. tmp = readln();
  1042. if (tmp == NULL)
  1043. tmp = ifilter;
  1044. /* Check and report regex errors */
  1045. r = setfilter(&re, tmp);
  1046. if (r != 0)
  1047. goto nochange;
  1048. xstrlcpy(fltr, tmp, sizeof(fltr));
  1049. DPRINTF_S(fltr);
  1050. /* Save current */
  1051. if (ndents > 0)
  1052. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1053. goto begin;
  1054. case SEL_NEXT:
  1055. if (cur < ndents - 1)
  1056. cur++;
  1057. else if (ndents)
  1058. /* Roll over, set cursor to first entry */
  1059. cur = 0;
  1060. break;
  1061. case SEL_PREV:
  1062. if (cur > 0)
  1063. cur--;
  1064. else if (ndents)
  1065. /* Roll over, set cursor to last entry */
  1066. cur = ndents - 1;
  1067. break;
  1068. case SEL_PGDN:
  1069. if (cur < ndents - 1)
  1070. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1071. break;
  1072. case SEL_PGUP:
  1073. if (cur > 0)
  1074. cur -= MIN((LINES - 4) / 2, cur);
  1075. break;
  1076. case SEL_HOME:
  1077. cur = 0;
  1078. break;
  1079. case SEL_END:
  1080. cur = ndents - 1;
  1081. break;
  1082. case SEL_CD:
  1083. /* Read target dir */
  1084. printprompt("chdir: ");
  1085. tmp = readln();
  1086. if (tmp == NULL) {
  1087. clearprompt();
  1088. goto nochange;
  1089. }
  1090. mkpath(path, tmp, newpath, sizeof(newpath));
  1091. if (canopendir(newpath) == 0) {
  1092. printwarn();
  1093. goto nochange;
  1094. }
  1095. xstrlcpy(path, newpath, sizeof(path));
  1096. /* Reset filter */
  1097. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1098. DPRINTF_S(path);
  1099. goto begin;
  1100. case SEL_CDHOME:
  1101. tmp = getenv("HOME");
  1102. if (tmp == NULL) {
  1103. clearprompt();
  1104. goto nochange;
  1105. }
  1106. if (canopendir(tmp) == 0) {
  1107. printwarn();
  1108. goto nochange;
  1109. }
  1110. xstrlcpy(path, tmp, sizeof(path));
  1111. /* Reset filter */
  1112. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1113. DPRINTF_S(path);
  1114. goto begin;
  1115. case SEL_TOGGLEDOT:
  1116. showhidden ^= 1;
  1117. initfilter(showhidden, &ifilter);
  1118. xstrlcpy(fltr, ifilter, sizeof(fltr));
  1119. goto begin;
  1120. case SEL_DETAIL:
  1121. showdetail = !showdetail;
  1122. showdetail ? (printptr = &printent_long)
  1123. : (printptr = &printent);
  1124. /* Save current */
  1125. if (ndents > 0)
  1126. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1127. goto begin;
  1128. case SEL_STATS:
  1129. {
  1130. struct stat sb;
  1131. if (ndents > 0)
  1132. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1133. r = lstat(oldpath, &sb);
  1134. if (r == -1)
  1135. printerr(1, "lstat");
  1136. else
  1137. show_stats(oldpath, dents[cur].name, &sb);
  1138. goto begin;
  1139. }
  1140. case SEL_FSIZE:
  1141. sizeorder = !sizeorder;
  1142. mtimeorder = 0;
  1143. /* Save current */
  1144. if (ndents > 0)
  1145. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1146. goto begin;
  1147. case SEL_MTIME:
  1148. mtimeorder = !mtimeorder;
  1149. sizeorder = 0;
  1150. /* Save current */
  1151. if (ndents > 0)
  1152. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1153. goto begin;
  1154. case SEL_REDRAW:
  1155. /* Save current */
  1156. if (ndents > 0)
  1157. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1158. goto begin;
  1159. case SEL_COPY:
  1160. if (copier && ndents) {
  1161. char abspath[PATH_MAX];
  1162. if (strcmp(path, "/") == 0)
  1163. snprintf(abspath, PATH_MAX, "/%s",
  1164. dents[cur].name);
  1165. else
  1166. snprintf(abspath, PATH_MAX, "%s/%s",
  1167. path, dents[cur].name);
  1168. spawn(copier, abspath, NULL);
  1169. printmsg(abspath);
  1170. } else if (!copier)
  1171. printmsg("NNN_COPIER is not set");
  1172. goto nochange;
  1173. case SEL_HELP:
  1174. show_help();
  1175. /* Save current */
  1176. if (ndents > 0)
  1177. mkpath(path, dents[cur].name, oldpath, sizeof(oldpath));
  1178. goto begin;
  1179. case SEL_RUN:
  1180. run = xgetenv(env, run);
  1181. exitcurses();
  1182. spawn(run, NULL, path);
  1183. initcurses();
  1184. /* Re-populate as directory content may have changed */
  1185. goto begin;
  1186. case SEL_RUNARG:
  1187. run = xgetenv(env, run);
  1188. exitcurses();
  1189. spawn(run, dents[cur].name, path);
  1190. initcurses();
  1191. break;
  1192. }
  1193. /* Screensaver */
  1194. if (idletimeout != 0 && idle == idletimeout) {
  1195. idle = 0;
  1196. exitcurses();
  1197. spawn(idlecmd, NULL, NULL);
  1198. initcurses();
  1199. }
  1200. }
  1201. }
  1202. static void
  1203. usage(void)
  1204. {
  1205. fprintf(stderr, "usage: nnn [-d] [dir]\n");
  1206. exit(1);
  1207. }
  1208. int
  1209. main(int argc, char *argv[])
  1210. {
  1211. char cwd[PATH_MAX], *ipath;
  1212. char *ifilter;
  1213. int opt = 0;
  1214. /* Confirm we are in a terminal */
  1215. if (!isatty(0) || !isatty(1)) {
  1216. fprintf(stderr, "stdin or stdout is not a tty\n");
  1217. exit(1);
  1218. }
  1219. if (argc > 3)
  1220. usage();
  1221. while ((opt = getopt(argc, argv, "d")) != -1) {
  1222. switch (opt) {
  1223. case 'd':
  1224. /* Open in detail mode, if set */
  1225. showdetail = 1;
  1226. printptr = &printent_long;
  1227. break;
  1228. default:
  1229. usage();
  1230. }
  1231. }
  1232. if (argc == optind) {
  1233. /* Start in the current directory */
  1234. ipath = getcwd(cwd, sizeof(cwd));
  1235. if (ipath == NULL)
  1236. ipath = "/";
  1237. } else {
  1238. ipath = realpath(argv[optind], cwd);
  1239. if (!ipath) {
  1240. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  1241. exit(1);
  1242. }
  1243. }
  1244. if (getuid() == 0)
  1245. showhidden = 1;
  1246. initfilter(showhidden, &ifilter);
  1247. /* Get the default desktop mime opener, if set */
  1248. opener = getenv("NNN_OPENER");
  1249. /* Get the fallback desktop mime opener, if set */
  1250. fallback_opener = getenv("NNN_FALLBACK_OPENER");
  1251. /* Get the default copier, if set */
  1252. copier = getenv("NNN_COPIER");
  1253. signal(SIGINT, SIG_IGN);
  1254. /* Test initial path */
  1255. if (canopendir(ipath) == 0) {
  1256. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  1257. exit(1);
  1258. }
  1259. /* Set locale before curses setup */
  1260. setlocale(LC_ALL, "");
  1261. initcurses();
  1262. browse(ipath, ifilter);
  1263. exitcurses();
  1264. exit(0);
  1265. }