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.
 
 
 
 
 
 

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