My build of nnn with minor changes
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.
 
 
 
 
 
 

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