My build of nnn with minor changes
 
 
 
 
 
 

2817 lines
58 KiB

  1. /* See LICENSE file for copyright and license details. */
  2. #ifdef __linux__
  3. #include <sys/inotify.h>
  4. #define LINUX_INOTIFY
  5. #endif
  6. #include <sys/resource.h>
  7. #include <sys/stat.h>
  8. #include <sys/statvfs.h>
  9. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  10. # include <sys/types.h>
  11. #include <sys/event.h>
  12. #include <sys/time.h>
  13. #define BSD_KQUEUE
  14. #else
  15. # include <sys/sysmacros.h>
  16. #endif
  17. #include <sys/wait.h>
  18. #include <ctype.h>
  19. #include <curses.h>
  20. #include <dirent.h>
  21. #include <errno.h>
  22. #include <fcntl.h>
  23. #include <grp.h>
  24. #include <libgen.h>
  25. #include <limits.h>
  26. #ifdef __gnu_hurd__
  27. #define PATH_MAX 4096
  28. #endif
  29. #include <locale.h>
  30. #include <pwd.h>
  31. #include <regex.h>
  32. #include <signal.h>
  33. #include <stdarg.h>
  34. #include <stdio.h>
  35. #include <stdlib.h>
  36. #include <string.h>
  37. #include <time.h>
  38. #include <unistd.h>
  39. #include <wchar.h>
  40. #include <readline/readline.h>
  41. #ifndef __USE_XOPEN_EXTENDED
  42. #define __USE_XOPEN_EXTENDED 1
  43. #endif
  44. #include <ftw.h>
  45. #include "config.h"
  46. #ifdef DEBUGMODE
  47. static int DEBUG_FD;
  48. static int
  49. xprintf(int fd, const char *fmt, ...)
  50. {
  51. char buf[BUFSIZ];
  52. int r;
  53. va_list ap;
  54. va_start(ap, fmt);
  55. r = vsnprintf(buf, sizeof(buf), fmt, ap);
  56. if (r > 0)
  57. r = write(fd, buf, r);
  58. va_end(ap);
  59. return r;
  60. }
  61. static int
  62. enabledbg()
  63. {
  64. FILE *fp = fopen("/tmp/nnn_debug", "w");
  65. if (!fp) {
  66. fprintf(stderr, "Cannot open debug file\n");
  67. return -1;
  68. }
  69. DEBUG_FD = fileno(fp);
  70. if (DEBUG_FD == -1) {
  71. fprintf(stderr, "Cannot open debug file descriptor\n");
  72. return -1;
  73. }
  74. return 0;
  75. }
  76. static void
  77. disabledbg()
  78. {
  79. close(DEBUG_FD);
  80. }
  81. #define DPRINTF_D(x) xprintf(DEBUG_FD, #x "=%d\n", x)
  82. #define DPRINTF_U(x) xprintf(DEBUG_FD, #x "=%u\n", x)
  83. #define DPRINTF_S(x) xprintf(DEBUG_FD, #x "=%s\n", x)
  84. #define DPRINTF_P(x) xprintf(DEBUG_FD, #x "=0x%p\n", x)
  85. #else
  86. #define DPRINTF_D(x)
  87. #define DPRINTF_U(x)
  88. #define DPRINTF_S(x)
  89. #define DPRINTF_P(x)
  90. #endif /* DEBUGMODE */
  91. /* Macro definitions */
  92. #define VERSION "1.3"
  93. #define LEN(x) (sizeof(x) / sizeof(*(x)))
  94. #undef MIN
  95. #define MIN(x, y) ((x) < (y) ? (x) : (y))
  96. #define ISODD(x) ((x) & 1)
  97. #define TOUPPER(ch) \
  98. (((ch) >= 'a' && (ch) <= 'z') ? ((ch) - 'a' + 'A') : (ch))
  99. #define MAX_CMD_LEN 5120
  100. #define CWD "cwd: "
  101. #define CURSR " > "
  102. #define EMPTY " "
  103. #define CURSYM(flag) (flag ? CURSR : EMPTY)
  104. #define FILTER '/'
  105. #define REGEX_MAX 128
  106. #define MAX_BM 10
  107. /* Macros to define process spawn behaviour as flags */
  108. #define F_NONE 0x00 /* no flag set */
  109. #define F_MARKER 0x01 /* draw marker to indicate nnn spawned (e.g. shell) */
  110. #define F_NOWAIT 0x02 /* don't wait for child process (e.g. file manager) */
  111. #define F_NOTRACE 0x04 /* suppress stdout and strerr (no traces) */
  112. #define F_SIGINT 0x08 /* restore default SIGINT handler */
  113. #define F_NORMAL 0x80 /* spawn child process in non-curses regular mode */
  114. #define exitcurses() endwin()
  115. #define clearprompt() printmsg("")
  116. #define printwarn() printmsg(strerror(errno))
  117. #define istopdir(path) (path[1] == '\0' && path[0] == '/')
  118. #define settimeout() timeout(1000)
  119. #define cleartimeout() timeout(-1)
  120. #ifdef LINUX_INOTIFY
  121. #define EVENT_SIZE (sizeof(struct inotify_event))
  122. #define EVENT_BUF_LEN (1024 * (EVENT_SIZE + 16))
  123. #elif defined(BSD_KQUEUE)
  124. #define NUM_EVENT_SLOTS 1
  125. #define NUM_EVENT_FDS 1
  126. #endif
  127. typedef unsigned long ulong;
  128. typedef unsigned int uint;
  129. typedef unsigned char uchar;
  130. /* Directory entry */
  131. typedef struct entry {
  132. char name[NAME_MAX];
  133. mode_t mode;
  134. time_t t;
  135. off_t size;
  136. blkcnt_t blocks; /* number of 512B blocks allocated */
  137. } *pEntry;
  138. /* Bookmark */
  139. typedef struct {
  140. char *key;
  141. char *loc;
  142. } bm;
  143. /* Settings */
  144. typedef struct {
  145. uchar filtermode : 1; /* Set to enter filter mode */
  146. uchar mtimeorder : 1; /* Set to sort by time modified */
  147. uchar sizeorder : 1; /* Set to sort by file size */
  148. uchar blkorder : 1; /* Set to sort by blocks used (disk usage) */
  149. uchar showhidden : 1; /* Set to show hidden files */
  150. uchar showdetail : 1; /* Clear to show fewer file info */
  151. uchar showcolor : 1; /* Set to show dirs in blue */
  152. uchar dircolor : 1; /* Current status of dir color */
  153. } settings;
  154. /* Externs */
  155. #ifdef __APPLE__
  156. extern int add_history(const char *string);
  157. #else
  158. extern void add_history(const char *string);
  159. #endif
  160. extern int wget_wch(WINDOW *win, wint_t *wch);
  161. /* Globals */
  162. /* Configuration */
  163. static settings cfg = {0, 0, 0, 0, 0, 1, 1, 0};
  164. static struct entry *dents;
  165. static int ndents, cur, total_dents;
  166. static uint idle;
  167. static uint idletimeout;
  168. static char *player;
  169. static char *copier;
  170. static char *editor;
  171. static char *desktop_manager;
  172. static blkcnt_t ent_blocks;
  173. static blkcnt_t dir_blocks;
  174. static ulong num_files;
  175. static size_t fs_free;
  176. static uint open_max;
  177. static bm bookmark[MAX_BM];
  178. static const double div_2_pow_10 = 1.0 / 1024.0;
  179. static uint _WSHIFT = (sizeof(ulong) == 8) ? 3 : 2;
  180. static uchar color = 4;
  181. #ifdef LINUX_INOTIFY
  182. static int inotify_fd, inotify_wd = -1;
  183. static uint INOTIFY_MASK = IN_ATTRIB | IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVED_TO;
  184. #elif defined(BSD_KQUEUE)
  185. static int kq, event_fd = -1;
  186. static struct kevent events_to_monitor[NUM_EVENT_FDS];
  187. static uint KQUEUE_FFLAGS = NOTE_DELETE | NOTE_EXTEND | NOTE_LINK | NOTE_RENAME | NOTE_REVOKE | NOTE_WRITE;
  188. static struct timespec gtimeout;
  189. #endif
  190. /* Utilities to open files, run actions */
  191. static char * const utils[] = {
  192. #ifdef __APPLE__
  193. "/usr/bin/open",
  194. #else
  195. "/usr/bin/xdg-open",
  196. #endif
  197. "nlay",
  198. "mediainfo",
  199. "exiftool"
  200. };
  201. static char *metaviewer;
  202. /* For use in functions which are isolated and don't return the buffer */
  203. static char g_buf[MAX_CMD_LEN];
  204. /* Common message strings */
  205. static char *STR_NFTWFAIL = "nftw(3) failed";
  206. static char *STR_ATROOT = "You are at /";
  207. static char *STR_NOHOME = "HOME not set";
  208. /*
  209. * Layout:
  210. * .---------
  211. * | cwd: /mnt/path
  212. * |
  213. * | file0
  214. * | file1
  215. * | > file2
  216. * | file3
  217. * | file4
  218. * ...
  219. * | filen
  220. * |
  221. * | Permission denied
  222. * '------
  223. */
  224. /* Forward declarations */
  225. static void printmsg(char *);
  226. static void printerr(int, char *);
  227. static void redraw(char *path);
  228. /* Functions */
  229. /* Increase the limit on open file descriptors, if possible */
  230. static rlim_t
  231. max_openfds()
  232. {
  233. struct rlimit rl;
  234. rlim_t limit = getrlimit(RLIMIT_NOFILE, &rl);
  235. if (limit != 0)
  236. return 32;
  237. limit = rl.rlim_cur;
  238. rl.rlim_cur = rl.rlim_max;
  239. /* Return ~75% of max possible */
  240. if (setrlimit(RLIMIT_NOFILE, &rl) == 0) {
  241. limit = rl.rlim_max - (rl.rlim_max >> 2);
  242. /*
  243. * 20K is arbitrary> If the limit is set to max possible
  244. * value, the memory usage increases to more than double.
  245. */
  246. return limit > 20480 ? 20480 : limit;
  247. }
  248. return limit;
  249. }
  250. /*
  251. * Custom xstrlen()
  252. */
  253. static size_t
  254. xstrlen(const char *s)
  255. {
  256. static size_t len;
  257. if (!s)
  258. return 0;
  259. len = 0;
  260. while (*s)
  261. ++len, ++s;
  262. return len;
  263. }
  264. /*
  265. * Just a safe strncpy(3)
  266. * Always null ('\0') terminates if both src and dest are valid pointers.
  267. * Returns the number of bytes copied including terminating null byte.
  268. */
  269. static size_t
  270. xstrlcpy(char *dest, const char *src, size_t n)
  271. {
  272. static size_t len, blocks;
  273. if (!src || !dest)
  274. return 0;
  275. len = xstrlen(src) + 1;
  276. if (n > len)
  277. n = len;
  278. else if (len > n)
  279. /* Save total number of bytes to copy in len */
  280. len = n;
  281. blocks = n >> _WSHIFT;
  282. n -= (blocks << _WSHIFT);
  283. if (blocks) {
  284. static ulong *s, *d;
  285. s = (ulong *)src;
  286. d = (ulong *)dest;
  287. while (blocks) {
  288. *d = *s;
  289. ++d, ++s;
  290. --blocks;
  291. }
  292. if (!n) {
  293. dest = (char *)d;
  294. *--dest = '\0';
  295. return len;
  296. }
  297. src = (char *)s;
  298. dest = (char *)d;
  299. }
  300. while (--n && (*dest = *src))
  301. ++dest, ++src;
  302. if (!n)
  303. *dest = '\0';
  304. return len;
  305. }
  306. /*
  307. * Custom strcmp(), just what we need.
  308. * Returns 0 if same, else -1
  309. */
  310. static int
  311. xstrcmp(const char *s1, const char *s2)
  312. {
  313. if (!s1 || !s2)
  314. return -1;
  315. while (*s1 && *s1 == *s2)
  316. ++s1, ++s2;
  317. if (*s1 != *s2)
  318. return -1;
  319. return 0;
  320. }
  321. /*
  322. * The poor man's implementation of memrchr(3).
  323. * We are only looking for '/' in this program.
  324. * Ideally 0 < n <= strlen(s).
  325. */
  326. static void *
  327. xmemrchr(uchar *s, uchar ch, size_t n)
  328. {
  329. if (!s || !n)
  330. return NULL;
  331. s = s + n - 1;
  332. while (n) {
  333. if (*s == ch)
  334. return s;
  335. --n, --s;
  336. }
  337. return NULL;
  338. }
  339. /*
  340. * The following dirname(3) implementation does not
  341. * modify the input. We use a copy of the original.
  342. *
  343. * Modified from the glibc (GNU LGPL) version.
  344. */
  345. static char *
  346. xdirname(const char *path)
  347. {
  348. static char *buf = g_buf;
  349. static char *last_slash;
  350. xstrlcpy(buf, path, PATH_MAX);
  351. /* Find last '/'. */
  352. last_slash = xmemrchr((uchar *)buf, '/', xstrlen(buf));
  353. if (last_slash != NULL && last_slash != buf && last_slash[1] == '\0') {
  354. /* Determine whether all remaining characters are slashes. */
  355. char *runp;
  356. for (runp = last_slash; runp != buf; --runp)
  357. if (runp[-1] != '/')
  358. break;
  359. /* The '/' is the last character, we have to look further. */
  360. if (runp != buf)
  361. last_slash = xmemrchr((uchar *)buf, '/', runp - buf);
  362. }
  363. if (last_slash != NULL) {
  364. /* Determine whether all remaining characters are slashes. */
  365. char *runp;
  366. for (runp = last_slash; runp != buf; --runp)
  367. if (runp[-1] != '/')
  368. break;
  369. /* Terminate the buffer. */
  370. if (runp == buf) {
  371. /* The last slash is the first character in the string.
  372. * We have to return "/". As a special case we have to
  373. * return "//" if there are exactly two slashes at the
  374. * beginning of the string. See XBD 4.10 Path Name
  375. * Resolution for more information.
  376. */
  377. if (last_slash == buf + 1)
  378. ++last_slash;
  379. else
  380. last_slash = buf + 1;
  381. } else
  382. last_slash = runp;
  383. last_slash[0] = '\0';
  384. } else {
  385. /* This assignment is ill-designed but the XPG specs require to
  386. * return a string containing "." in any case no directory part
  387. * is found and so a static and constant string is required.
  388. */
  389. buf[0] = '.';
  390. buf[1] = '\0';
  391. }
  392. return buf;
  393. }
  394. /*
  395. * Return number of dots if all chars in a string are dots, else 0
  396. */
  397. static int
  398. all_dots(const char *path)
  399. {
  400. if (!path)
  401. return FALSE;
  402. int count = 0;
  403. while (*path == '.')
  404. ++count, ++path;
  405. if (*path)
  406. return 0;
  407. return count;
  408. }
  409. /* Initialize curses mode */
  410. static void
  411. initcurses(void)
  412. {
  413. if (initscr() == NULL) {
  414. char *term = getenv("TERM");
  415. if (term != NULL)
  416. fprintf(stderr, "error opening TERM: %s\n", term);
  417. else
  418. fprintf(stderr, "initscr() failed\n");
  419. exit(1);
  420. }
  421. cbreak();
  422. noecho();
  423. nonl();
  424. intrflush(stdscr, FALSE);
  425. keypad(stdscr, TRUE);
  426. curs_set(FALSE); /* Hide cursor */
  427. start_color();
  428. use_default_colors();
  429. if (cfg.showcolor)
  430. init_pair(1, color, -1);
  431. settimeout(); /* One second */
  432. }
  433. /*
  434. * Spawns a child process. Behaviour can be controlled using flag.
  435. * Limited to 2 arguments to a program, flag works on bit set.
  436. */
  437. static void
  438. spawn(char *file, char *arg1, char *arg2, char *dir, uchar flag)
  439. {
  440. pid_t pid;
  441. int status;
  442. if (flag & F_NORMAL)
  443. exitcurses();
  444. pid = fork();
  445. if (pid == 0) {
  446. if (dir != NULL)
  447. status = chdir(dir);
  448. /* Show a marker (to indicate nnn spawned shell) */
  449. if (flag & F_MARKER) {
  450. printf("\n +-++-++-+\n | n n n |\n +-++-++-+\n\n");
  451. printf("Spawned shell level: %d\n", atoi(getenv("SHLVL")) + 1);
  452. }
  453. /* Suppress stdout and stderr */
  454. if (flag & F_NOTRACE) {
  455. int fd = open("/dev/null", O_WRONLY, 0200);
  456. dup2(fd, 1);
  457. dup2(fd, 2);
  458. close(fd);
  459. }
  460. if (flag & F_SIGINT)
  461. signal(SIGINT, SIG_DFL);
  462. execlp(file, file, arg1, arg2, NULL);
  463. _exit(1);
  464. } else {
  465. if (!(flag & F_NOWAIT))
  466. /* Ignore interruptions */
  467. while (waitpid(pid, &status, 0) == -1)
  468. DPRINTF_D(status);
  469. DPRINTF_D(pid);
  470. if (flag & F_NORMAL)
  471. initcurses();
  472. }
  473. }
  474. /* Get program name from env var, else return fallback program */
  475. static char *
  476. xgetenv(char *name, char *fallback)
  477. {
  478. if (name == NULL)
  479. return fallback;
  480. char *value = getenv(name);
  481. return value && value[0] ? value : fallback;
  482. }
  483. /* Check if a dir exists, IS a dir and is readable */
  484. static bool
  485. xdiraccess(char *path)
  486. {
  487. static DIR *dirp;
  488. dirp = opendir(path);
  489. if (dirp == NULL) {
  490. printwarn();
  491. return FALSE;
  492. }
  493. closedir(dirp);
  494. return TRUE;
  495. }
  496. /*
  497. * We assume none of the strings are NULL.
  498. *
  499. * Let's have the logic to sort numeric names in numeric order.
  500. * E.g., the order '1, 10, 2' doesn't make sense to human eyes.
  501. *
  502. * If the absolute numeric values are same, we fallback to alphasort.
  503. */
  504. static int
  505. xstricmp(char *s1, char *s2)
  506. {
  507. static char *c1, *c2;
  508. c1 = s1;
  509. while (isspace(*c1))
  510. ++c1;
  511. if (*c1 == '-' || *c1 == '+')
  512. ++c1;
  513. while (*c1 >= '0' && *c1 <= '9')
  514. ++c1;
  515. c2 = s2;
  516. while (isspace(*c2))
  517. ++c2;
  518. if (*c2 == '-' || *c2 == '+')
  519. ++c2;
  520. while (*c2 >= '0' && *c2 <= '9')
  521. ++c2;
  522. if (*c1 == '\0' && *c2 == '\0') {
  523. static long long num1, num2;
  524. num1 = strtoll(s1, &c1, 10);
  525. num2 = strtoll(s2, &c2, 10);
  526. if (num1 != num2) {
  527. if (num1 > num2)
  528. return 1;
  529. else
  530. return -1;
  531. }
  532. } else if (*c1 == '\0' && *c2 != '\0')
  533. return -1;
  534. else if (*c1 != '\0' && *c2 == '\0')
  535. return 1;
  536. while (*s2 && *s1 && TOUPPER(*s1) == TOUPPER(*s2))
  537. ++s1, ++s2;
  538. /* In case of alphabetically same names, make sure
  539. * lower case one comes before upper case one
  540. */
  541. if (!*s1 && !*s2)
  542. return 1;
  543. return (int) (TOUPPER(*s1) - TOUPPER(*s2));
  544. }
  545. /* Return the integer value of a char representing HEX */
  546. static char
  547. xchartohex(char c)
  548. {
  549. if (c >= '0' && c <= '9')
  550. return c - '0';
  551. c = TOUPPER(c);
  552. if (c >= 'A' && c <= 'F')
  553. return c - 'A' + 10;
  554. return c;
  555. }
  556. /* Trim all whitespace from both ends, / from end */
  557. static char *
  558. strstrip(char *s)
  559. {
  560. if (!s || !*s)
  561. return s;
  562. size_t len = xstrlen(s) - 1;
  563. while (len != 0 && (isspace(s[len]) || s[len] == '/'))
  564. --len;
  565. s[len + 1] = '\0';
  566. while (*s && isspace(*s))
  567. ++s;
  568. return s;
  569. }
  570. static char *
  571. getmime(char *file)
  572. {
  573. regex_t regex;
  574. uint i;
  575. static uint len = LEN(assocs);
  576. for (i = 0; i < len; ++i) {
  577. if (regcomp(&regex, assocs[i].regex, REG_NOSUB | REG_EXTENDED | REG_ICASE) != 0)
  578. continue;
  579. if (regexec(&regex, file, 0, NULL, 0) == 0)
  580. return assocs[i].mime;
  581. }
  582. return NULL;
  583. }
  584. static int
  585. setfilter(regex_t *regex, char *filter)
  586. {
  587. static size_t len;
  588. static int r;
  589. r = regcomp(regex, filter, REG_NOSUB | REG_EXTENDED | REG_ICASE);
  590. if (r != 0 && filter && filter[0] != '\0') {
  591. len = COLS;
  592. if (len > LINE_MAX)
  593. len = LINE_MAX;
  594. regerror(r, regex, g_buf, len);
  595. printmsg(g_buf);
  596. }
  597. return r;
  598. }
  599. static void
  600. initfilter(int dot, char **ifilter)
  601. {
  602. *ifilter = dot ? "." : "^[^.]";
  603. }
  604. static int
  605. visible(regex_t *regex, char *file)
  606. {
  607. return regexec(regex, file, 0, NULL, 0) == 0;
  608. }
  609. static int
  610. entrycmp(const void *va, const void *vb)
  611. {
  612. static pEntry pa, pb;
  613. pa = (pEntry)va;
  614. pb = (pEntry)vb;
  615. /* Sort directories first */
  616. if (S_ISDIR(pb->mode) && !S_ISDIR(pa->mode))
  617. return 1;
  618. else if (S_ISDIR(pa->mode) && !S_ISDIR(pb->mode))
  619. return -1;
  620. /* Do the actual sorting */
  621. if (cfg.mtimeorder)
  622. return pb->t - pa->t;
  623. if (cfg.sizeorder) {
  624. if (pb->size > pa->size)
  625. return 1;
  626. else if (pb->size < pa->size)
  627. return -1;
  628. }
  629. if (cfg.blkorder) {
  630. if (pb->blocks > pa->blocks)
  631. return 1;
  632. else if (pb->blocks < pa->blocks)
  633. return -1;
  634. }
  635. return xstricmp(pa->name, pb->name);
  636. }
  637. /* Messages show up at the bottom */
  638. static void
  639. printmsg(char *msg)
  640. {
  641. mvprintw(LINES - 1, 0, "%s\n", msg);
  642. }
  643. /* Kill curses and display error before exiting */
  644. static void
  645. printerr(int ret, char *prefix)
  646. {
  647. exitcurses();
  648. fprintf(stderr, "%s: %s\n", prefix, strerror(errno));
  649. exit(ret);
  650. }
  651. /* Print prompt on the last line */
  652. static void
  653. printprompt(char *str)
  654. {
  655. clearprompt();
  656. printw(str);
  657. }
  658. /*
  659. * Returns SEL_* if key is bound and 0 otherwise.
  660. * Also modifies the run and env pointers (used on SEL_{RUN,RUNARG}).
  661. * The next keyboard input can be simulated by presel.
  662. */
  663. static int
  664. nextsel(char **run, char **env, int *presel)
  665. {
  666. static int c;
  667. static uchar i;
  668. static uint len = LEN(bindings);
  669. #ifdef LINUX_INOTIFY
  670. static char inotify_buf[EVENT_BUF_LEN];
  671. #elif defined(BSD_KQUEUE)
  672. static struct kevent event_data[NUM_EVENT_SLOTS];
  673. #endif
  674. c = *presel;
  675. if (c == 0)
  676. c = getch();
  677. else {
  678. *presel = 0;
  679. /* Unwatch dir if we are still in a filtered view */
  680. #ifdef LINUX_INOTIFY
  681. if (inotify_wd >= 0) {
  682. inotify_rm_watch(inotify_fd, inotify_wd);
  683. inotify_wd = -1;
  684. }
  685. #elif defined(BSD_KQUEUE)
  686. if (event_fd >= 0) {
  687. close(event_fd);
  688. event_fd = -1;
  689. }
  690. #endif
  691. }
  692. if (c == -1) {
  693. ++idle;
  694. /* Do not check for directory changes in du
  695. * mode. A redraw forces du calculation.
  696. * Check for changes every odd second.
  697. */
  698. #ifdef LINUX_INOTIFY
  699. if (!cfg.blkorder && inotify_wd >= 0 && idle & 1 && read(inotify_fd, inotify_buf, EVENT_BUF_LEN) > 0)
  700. #elif defined(BSD_KQUEUE)
  701. if (!cfg.blkorder && event_fd >= 0 && idle & 1
  702. && kevent(kq, events_to_monitor, NUM_EVENT_SLOTS, event_data, NUM_EVENT_FDS, &gtimeout) > 0)
  703. #endif
  704. c = CONTROL('L');
  705. } else
  706. idle = 0;
  707. for (i = 0; i < len; ++i)
  708. if (c == bindings[i].sym) {
  709. *run = bindings[i].run;
  710. *env = bindings[i].env;
  711. return bindings[i].act;
  712. }
  713. return 0;
  714. }
  715. /*
  716. * Move non-matching entries to the end
  717. */
  718. static void
  719. fill(struct entry **dents, int (*filter)(regex_t *, char *), regex_t *re)
  720. {
  721. static int count;
  722. for (count = 0; count < ndents; ++count) {
  723. if (filter(re, (*dents)[count].name) == 0) {
  724. if (count != --ndents) {
  725. static struct entry _dent, *dentp1, *dentp2;
  726. dentp1 = &(*dents)[count];
  727. dentp2 = &(*dents)[ndents];
  728. /* Copy count to tmp */
  729. xstrlcpy(_dent.name, dentp1->name, NAME_MAX);
  730. _dent.mode = dentp1->mode;
  731. _dent.t = dentp1->t;
  732. _dent.size = dentp1->size;
  733. _dent.blocks = dentp1->blocks;
  734. /* Copy ndents - 1 to count */
  735. xstrlcpy(dentp1->name, dentp2->name, NAME_MAX);
  736. dentp1->mode = dentp2->mode;
  737. dentp1->t = dentp2->t;
  738. dentp1->size = dentp2->size;
  739. dentp1->blocks = dentp2->blocks;
  740. /* Copy tmp to ndents - 1 */
  741. xstrlcpy(dentp2->name, _dent.name, NAME_MAX);
  742. dentp2->mode = _dent.mode;
  743. dentp2->t = _dent.t;
  744. dentp2->size = _dent.size;
  745. dentp2->blocks = _dent.blocks;
  746. --count;
  747. }
  748. continue;
  749. }
  750. }
  751. }
  752. static int
  753. matches(char *fltr)
  754. {
  755. static regex_t re;
  756. /* Search filter */
  757. if (setfilter(&re, fltr) != 0)
  758. return -1;
  759. fill(&dents, visible, &re);
  760. qsort(dents, ndents, sizeof(*dents), entrycmp);
  761. return 0;
  762. }
  763. static int
  764. filterentries(char *path)
  765. {
  766. static char ln[REGEX_MAX];
  767. static wchar_t wln[REGEX_MAX];
  768. static wint_t ch[2] = {0};
  769. static int maxlen = REGEX_MAX - 1;
  770. int r, total = ndents;
  771. int oldcur = cur;
  772. int len = 1;
  773. char *pln = ln + 1;
  774. ln[0] = wln[0] = FILTER;
  775. ln[1] = wln[1] = '\0';
  776. cur = 0;
  777. cleartimeout();
  778. echo();
  779. curs_set(TRUE);
  780. printprompt(ln);
  781. while ((r = wget_wch(stdscr, ch)) != ERR)
  782. if (r == OK)
  783. switch (*ch) {
  784. case '\r': // with nonl(), this is ENTER key value
  785. if (len == 1) {
  786. cur = oldcur;
  787. goto end;
  788. }
  789. if (matches(pln) == -1)
  790. goto end;
  791. redraw(path);
  792. goto end;
  793. case 127: // handle DEL
  794. if (len == 1) {
  795. cur = oldcur;
  796. *ch = CONTROL('L');
  797. goto end;
  798. }
  799. wln[--len] = '\0';
  800. if (len == 1)
  801. cur = oldcur;
  802. wcstombs(ln, wln, REGEX_MAX);
  803. ndents = total;
  804. if (matches(pln) == -1) {
  805. printprompt(ln);
  806. continue;
  807. }
  808. redraw(path);
  809. printprompt(ln);
  810. break;
  811. case CONTROL('L'):
  812. if (len == 1)
  813. cur = oldcur; // fallthrough
  814. case CONTROL('Q'):
  815. goto end;
  816. default:
  817. /* Reset cur in case it's a repeat search */
  818. if (len == 1)
  819. cur = 0;
  820. if (len == maxlen || !isprint(*ch))
  821. break;
  822. wln[len] = (wchar_t)*ch;
  823. wln[++len] = '\0';
  824. wcstombs(ln, wln, REGEX_MAX);
  825. ndents = total;
  826. if (matches(pln) == -1)
  827. continue;
  828. redraw(path);
  829. printprompt(ln);
  830. }
  831. else
  832. switch (*ch) {
  833. case KEY_DC: // fallthrough
  834. case KEY_BACKSPACE:
  835. if (len == 1) {
  836. cur = oldcur;
  837. *ch = CONTROL('L');
  838. goto end;
  839. }
  840. wln[--len] = '\0';
  841. if (len == 1)
  842. cur = oldcur;
  843. wcstombs(ln, wln, REGEX_MAX);
  844. ndents = total;
  845. if (matches(pln) == -1)
  846. continue;
  847. redraw(path);
  848. printprompt(ln);
  849. break;
  850. default:
  851. if (len == 1)
  852. cur = oldcur;
  853. goto end;
  854. }
  855. end:
  856. noecho();
  857. curs_set(FALSE);
  858. settimeout();
  859. /* Return keys for navigation etc. */
  860. return *ch;
  861. }
  862. /* Show a prompt with input string and return the changes */
  863. static char *
  864. xreadline(char *fname)
  865. {
  866. int old_curs = curs_set(1);
  867. size_t len, pos;
  868. int c, x, y;
  869. wchar_t *buf = (wchar_t *)g_buf;
  870. size_t buflen = NAME_MAX - 1;
  871. DPRINTF_S(fname)
  872. mbstowcs(buf, fname, NAME_MAX);
  873. len = pos = wcslen(buf);
  874. /* For future: handle NULL, say for a new name */
  875. if (len <= 0) {
  876. buf[0] = '\0';
  877. len = pos = 0;
  878. }
  879. getyx(stdscr, y, x);
  880. cleartimeout();
  881. while (1) {
  882. buf[len] = ' ';
  883. mvaddnwstr(y, x, buf, len + 1);
  884. move(y, x + pos);
  885. c = getch();
  886. if (c == KEY_ENTER || c == '\n' || c == '\r')
  887. break;
  888. if (isprint(c) && pos < buflen) {
  889. memmove(buf + pos + 1, buf + pos, (len - pos) << 2);
  890. buf[pos] = c;
  891. ++len, ++pos;
  892. continue;
  893. }
  894. switch (c) {
  895. case KEY_LEFT:
  896. if (pos > 0)
  897. --pos;
  898. break;
  899. case KEY_RIGHT:
  900. if (pos < len)
  901. ++pos;
  902. break;
  903. case KEY_BACKSPACE:
  904. if (pos > 0) {
  905. memmove(buf + pos - 1, buf + pos, (len - pos) << 2);
  906. --len, --pos;
  907. }
  908. break;
  909. case KEY_DC:
  910. if (pos < len) {
  911. memmove(buf + pos, buf + pos + 1, (len - pos - 1) << 2);
  912. --len;
  913. }
  914. break;
  915. default:
  916. break;
  917. }
  918. }
  919. buf[len] = '\0';
  920. if (old_curs != ERR) curs_set(old_curs);
  921. settimeout();
  922. DPRINTF_S(buf)
  923. wcstombs(g_buf, buf, NAME_MAX);
  924. return g_buf;
  925. }
  926. /*
  927. * Returns "dir/name or "/name"
  928. */
  929. static char *
  930. mkpath(char *dir, char *name, char *out, size_t n)
  931. {
  932. /* Handle absolute path */
  933. if (name[0] == '/')
  934. xstrlcpy(out, name, n);
  935. else {
  936. /* Handle root case */
  937. if (istopdir(dir))
  938. snprintf(out, n, "/%s", name);
  939. else
  940. snprintf(out, n, "%s/%s", dir, name);
  941. }
  942. return out;
  943. }
  944. static void
  945. parsebmstr(char *bms)
  946. {
  947. int i = 0;
  948. while (*bms && i < MAX_BM) {
  949. bookmark[i].key = bms;
  950. ++bms;
  951. while (*bms && *bms != ':')
  952. ++bms;
  953. if (!*bms) {
  954. bookmark[i].key = NULL;
  955. break;
  956. }
  957. *bms = '\0';
  958. bookmark[i].loc = ++bms;
  959. if (bookmark[i].loc[0] == '\0' || bookmark[i].loc[0] == ';') {
  960. bookmark[i].key = NULL;
  961. break;
  962. }
  963. while (*bms && *bms != ';')
  964. ++bms;
  965. if (*bms)
  966. *bms = '\0';
  967. else
  968. break;
  969. ++bms;
  970. ++i;
  971. }
  972. }
  973. static char *
  974. readinput(void)
  975. {
  976. cleartimeout();
  977. echo();
  978. curs_set(TRUE);
  979. memset(g_buf, 0, LINE_MAX);
  980. wgetnstr(stdscr, g_buf, LINE_MAX - 1);
  981. noecho();
  982. curs_set(FALSE);
  983. settimeout();
  984. return g_buf[0] ? g_buf : NULL;
  985. }
  986. /*
  987. * Replace escape characters in a string with '?'
  988. */
  989. static char *
  990. unescape(const char *str)
  991. {
  992. static char buffer[PATH_MAX];
  993. static wchar_t wbuf[PATH_MAX];
  994. static wchar_t *buf;
  995. buffer[0] = '\0';
  996. buf = wbuf;
  997. /* Convert multi-byte to wide char */
  998. mbstowcs(wbuf, str, PATH_MAX);
  999. while (*buf) {
  1000. if (*buf <= '\x1f' || *buf == '\x7f')
  1001. *buf = '\?';
  1002. ++buf;
  1003. }
  1004. /* Convert wide char to multi-byte */
  1005. wcstombs(buffer, wbuf, PATH_MAX);
  1006. return buffer;
  1007. }
  1008. static void
  1009. printent(struct entry *ent, int sel)
  1010. {
  1011. static int ncols;
  1012. if (PATH_MAX + 16 < COLS)
  1013. ncols = PATH_MAX + 16;
  1014. else
  1015. ncols = COLS;
  1016. if (S_ISDIR(ent->mode))
  1017. snprintf(g_buf, ncols, "%s%s/", CURSYM(sel), unescape(ent->name));
  1018. else if (S_ISLNK(ent->mode))
  1019. snprintf(g_buf, ncols, "%s%s@", CURSYM(sel), unescape(ent->name));
  1020. else if (S_ISSOCK(ent->mode))
  1021. snprintf(g_buf, ncols, "%s%s=", CURSYM(sel), unescape(ent->name));
  1022. else if (S_ISFIFO(ent->mode))
  1023. snprintf(g_buf, ncols, "%s%s|", CURSYM(sel), unescape(ent->name));
  1024. else if (ent->mode & 0100)
  1025. snprintf(g_buf, ncols, "%s%s*", CURSYM(sel), unescape(ent->name));
  1026. else
  1027. snprintf(g_buf, ncols, "%s%s", CURSYM(sel), unescape(ent->name));
  1028. /* Dirs are always shown on top */
  1029. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  1030. attroff(COLOR_PAIR(1) | A_BOLD);
  1031. cfg.dircolor = 0;
  1032. }
  1033. printw("%s\n", g_buf);
  1034. }
  1035. static char *
  1036. coolsize(off_t size)
  1037. {
  1038. static const char * const U = "BKMGTPEZY";
  1039. static char size_buf[12]; /* Buffer to hold human readable size */
  1040. static int i;
  1041. static off_t tmp;
  1042. static long double rem;
  1043. i = 0;
  1044. rem = 0;
  1045. while (size > 1024) {
  1046. tmp = size;
  1047. size >>= 10;
  1048. rem = tmp - (size << 10);
  1049. ++i;
  1050. }
  1051. snprintf(size_buf, 12, "%.*Lf%c", i, size + rem * div_2_pow_10, U[i]);
  1052. return size_buf;
  1053. }
  1054. static void
  1055. printent_long(struct entry *ent, int sel)
  1056. {
  1057. static int ncols;
  1058. static char buf[18];
  1059. if (PATH_MAX + 32 < COLS)
  1060. ncols = PATH_MAX + 32;
  1061. else
  1062. ncols = COLS;
  1063. strftime(buf, 18, "%d-%m-%Y %H:%M", localtime(&ent->t));
  1064. if (sel)
  1065. attron(A_REVERSE);
  1066. if (!cfg.blkorder) {
  1067. if (S_ISDIR(ent->mode))
  1068. snprintf(g_buf, ncols, "%s%-16.16s / %s/", CURSYM(sel), buf, unescape(ent->name));
  1069. else if (S_ISLNK(ent->mode))
  1070. snprintf(g_buf, ncols, "%s%-16.16s @ %s@", CURSYM(sel), buf, unescape(ent->name));
  1071. else if (S_ISSOCK(ent->mode))
  1072. snprintf(g_buf, ncols, "%s%-16.16s = %s=", CURSYM(sel), buf, unescape(ent->name));
  1073. else if (S_ISFIFO(ent->mode))
  1074. snprintf(g_buf, ncols, "%s%-16.16s | %s|", CURSYM(sel), buf, unescape(ent->name));
  1075. else if (S_ISBLK(ent->mode))
  1076. snprintf(g_buf, ncols, "%s%-16.16s b %s", CURSYM(sel), buf, unescape(ent->name));
  1077. else if (S_ISCHR(ent->mode))
  1078. snprintf(g_buf, ncols, "%s%-16.16s c %s", CURSYM(sel), buf, unescape(ent->name));
  1079. else if (ent->mode & 0100)
  1080. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*", CURSYM(sel), buf, coolsize(ent->size), unescape(ent->name));
  1081. else
  1082. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s", CURSYM(sel), buf, coolsize(ent->size), unescape(ent->name));
  1083. } else {
  1084. if (S_ISDIR(ent->mode))
  1085. snprintf(g_buf, ncols, "%s%-16.16s %8.8s/ %s/", CURSYM(sel), buf, coolsize(ent->blocks << 9), unescape(ent->name));
  1086. else if (S_ISLNK(ent->mode))
  1087. snprintf(g_buf, ncols, "%s%-16.16s @ %s@", CURSYM(sel), buf, unescape(ent->name));
  1088. else if (S_ISSOCK(ent->mode))
  1089. snprintf(g_buf, ncols, "%s%-16.16s = %s=", CURSYM(sel), buf, unescape(ent->name));
  1090. else if (S_ISFIFO(ent->mode))
  1091. snprintf(g_buf, ncols, "%s%-16.16s | %s|", CURSYM(sel), buf, unescape(ent->name));
  1092. else if (S_ISBLK(ent->mode))
  1093. snprintf(g_buf, ncols, "%s%-16.16s b %s", CURSYM(sel), buf, unescape(ent->name));
  1094. else if (S_ISCHR(ent->mode))
  1095. snprintf(g_buf, ncols, "%s%-16.16s c %s", CURSYM(sel), buf, unescape(ent->name));
  1096. else if (ent->mode & 0100)
  1097. snprintf(g_buf, ncols, "%s%-16.16s %8.8s* %s*", CURSYM(sel), buf, coolsize(ent->blocks << 9), unescape(ent->name));
  1098. else
  1099. snprintf(g_buf, ncols, "%s%-16.16s %8.8s %s", CURSYM(sel), buf, coolsize(ent->blocks << 9), unescape(ent->name));
  1100. }
  1101. /* Dirs are always shown on top */
  1102. if (cfg.dircolor && !S_ISDIR(ent->mode)) {
  1103. attroff(COLOR_PAIR(1) | A_BOLD);
  1104. cfg.dircolor = 0;
  1105. }
  1106. printw("%s\n", g_buf);
  1107. if (sel)
  1108. attroff(A_REVERSE);
  1109. }
  1110. static void (*printptr)(struct entry *ent, int sel) = &printent_long;
  1111. static char
  1112. get_fileind(mode_t mode, char *desc)
  1113. {
  1114. static char c;
  1115. if (S_ISREG(mode)) {
  1116. c = '-';
  1117. sprintf(desc, "%s", "regular file");
  1118. if (mode & 0100)
  1119. strcat(desc, ", executable");
  1120. } else if (S_ISDIR(mode)) {
  1121. c = 'd';
  1122. sprintf(desc, "%s", "directory");
  1123. } else if (S_ISBLK(mode)) {
  1124. c = 'b';
  1125. sprintf(desc, "%s", "block special device");
  1126. } else if (S_ISCHR(mode)) {
  1127. c = 'c';
  1128. sprintf(desc, "%s", "character special device");
  1129. #ifdef S_ISFIFO
  1130. } else if (S_ISFIFO(mode)) {
  1131. c = 'p';
  1132. sprintf(desc, "%s", "FIFO");
  1133. #endif /* S_ISFIFO */
  1134. #ifdef S_ISLNK
  1135. } else if (S_ISLNK(mode)) {
  1136. c = 'l';
  1137. sprintf(desc, "%s", "symbolic link");
  1138. #endif /* S_ISLNK */
  1139. #ifdef S_ISSOCK
  1140. } else if (S_ISSOCK(mode)) {
  1141. c = 's';
  1142. sprintf(desc, "%s", "socket");
  1143. #endif /* S_ISSOCK */
  1144. #ifdef S_ISDOOR
  1145. /* Solaris 2.6, etc. */
  1146. } else if (S_ISDOOR(mode)) {
  1147. c = 'D';
  1148. desc[0] = '\0';
  1149. #endif /* S_ISDOOR */
  1150. } else {
  1151. /* Unknown type -- possibly a regular file? */
  1152. c = '?';
  1153. desc[0] = '\0';
  1154. }
  1155. return c;
  1156. }
  1157. /* Convert a mode field into "ls -l" type perms field. */
  1158. static char *
  1159. get_lsperms(mode_t mode, char *desc)
  1160. {
  1161. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1162. static char bits[11];
  1163. bits[0] = get_fileind(mode, desc);
  1164. strcpy(&bits[1], rwx[(mode >> 6) & 7]);
  1165. strcpy(&bits[4], rwx[(mode >> 3) & 7]);
  1166. strcpy(&bits[7], rwx[(mode & 7)]);
  1167. if (mode & S_ISUID)
  1168. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1169. if (mode & S_ISGID)
  1170. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1171. if (mode & S_ISVTX)
  1172. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1173. bits[10] = '\0';
  1174. return bits;
  1175. }
  1176. /*
  1177. * Gets only a single line (that's what we need
  1178. * for now) or shows full command output in pager.
  1179. *
  1180. * If pager is valid, returns NULL
  1181. */
  1182. static char *
  1183. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2,
  1184. int pager)
  1185. {
  1186. pid_t pid;
  1187. int pipefd[2];
  1188. FILE *pf;
  1189. int tmp, flags;
  1190. char *ret = NULL;
  1191. if (pipe(pipefd) == -1)
  1192. printerr(1, "pipe(2)");
  1193. for (tmp = 0; tmp < 2; ++tmp) {
  1194. /* Get previous flags */
  1195. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1196. /* Set bit for non-blocking flag */
  1197. flags |= O_NONBLOCK;
  1198. /* Change flags on fd */
  1199. fcntl(pipefd[tmp], F_SETFL, flags);
  1200. }
  1201. pid = fork();
  1202. if (pid == 0) {
  1203. /* In child */
  1204. close(pipefd[0]);
  1205. dup2(pipefd[1], STDOUT_FILENO);
  1206. dup2(pipefd[1], STDERR_FILENO);
  1207. close(pipefd[1]);
  1208. execlp(file, file, arg1, arg2, NULL);
  1209. _exit(1);
  1210. }
  1211. /* In parent */
  1212. waitpid(pid, &tmp, 0);
  1213. close(pipefd[1]);
  1214. if (!pager) {
  1215. pf = fdopen(pipefd[0], "r");
  1216. if (pf) {
  1217. ret = fgets(buf, bytes, pf);
  1218. close(pipefd[0]);
  1219. }
  1220. return ret;
  1221. }
  1222. pid = fork();
  1223. if (pid == 0) {
  1224. /* Show in pager in child */
  1225. dup2(pipefd[0], STDIN_FILENO);
  1226. close(pipefd[0]);
  1227. execlp("less", "less", NULL);
  1228. _exit(1);
  1229. }
  1230. /* In parent */
  1231. waitpid(pid, &tmp, 0);
  1232. close(pipefd[0]);
  1233. return NULL;
  1234. }
  1235. /*
  1236. * Follows the stat(1) output closely
  1237. */
  1238. static int
  1239. show_stats(char *fpath, char *fname, struct stat *sb)
  1240. {
  1241. char *perms = get_lsperms(sb->st_mode, g_buf);
  1242. char *p, *begin = g_buf;
  1243. char tmp[] = "/tmp/nnnXXXXXX";
  1244. int fd = mkstemp(tmp);
  1245. if (fd == -1)
  1246. return -1;
  1247. /* Show file name or 'symlink' -> 'target' */
  1248. if (perms[0] == 'l') {
  1249. /* Note that MAX_CMD_LEN > PATH_MAX */
  1250. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1251. if (len != -1) {
  1252. g_buf[len] = '\0';
  1253. dprintf(fd, " File: '%s' -> ", unescape(fname));
  1254. dprintf(fd, "'%s'", unescape(g_buf));
  1255. xstrlcpy(g_buf, "symbolic link", MAX_CMD_LEN);
  1256. }
  1257. } else
  1258. dprintf(fd, " File: '%s'", unescape(fname));
  1259. /* Show size, blocks, file type */
  1260. #ifdef __APPLE__
  1261. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1262. #else
  1263. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1264. #endif
  1265. sb->st_size, sb->st_blocks, sb->st_blksize, g_buf);
  1266. /* Show containing device, inode, hardlink count */
  1267. #ifdef __APPLE__
  1268. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1269. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1270. #else
  1271. sprintf(g_buf, "%lxh/%lud", sb->st_dev, sb->st_dev);
  1272. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1273. #endif
  1274. g_buf, sb->st_ino, sb->st_nlink);
  1275. /* Show major, minor number for block or char device */
  1276. if (perms[0] == 'b' || perms[0] == 'c')
  1277. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1278. /* Show permissions, owner, group */
  1279. dprintf(fd, "\n Access: 0%d%d%d/%s Uid: (%u/%s) Gid: (%u/%s)", (sb->st_mode >> 6) & 7, (sb->st_mode >> 3) & 7,
  1280. sb->st_mode & 7, perms, sb->st_uid, (getpwuid(sb->st_uid))->pw_name, sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1281. /* Show last access time */
  1282. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_atime));
  1283. dprintf(fd, "\n\n Access: %s", g_buf);
  1284. /* Show last modification time */
  1285. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_mtime));
  1286. dprintf(fd, "\n Modify: %s", g_buf);
  1287. /* Show last status change time */
  1288. strftime(g_buf, 40, "%a %d-%b-%Y %T %z,%Z", localtime(&sb->st_ctime));
  1289. dprintf(fd, "\n Change: %s", g_buf);
  1290. if (S_ISREG(sb->st_mode)) {
  1291. /* Show file(1) output */
  1292. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1293. if (p) {
  1294. dprintf(fd, "\n\n ");
  1295. while (*p) {
  1296. if (*p == ',') {
  1297. *p = '\0';
  1298. dprintf(fd, " %s\n", begin);
  1299. begin = p + 1;
  1300. }
  1301. ++p;
  1302. }
  1303. dprintf(fd, " %s", begin);
  1304. }
  1305. dprintf(fd, "\n\n");
  1306. } else
  1307. dprintf(fd, "\n\n\n");
  1308. close(fd);
  1309. exitcurses();
  1310. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1311. unlink(tmp);
  1312. initcurses();
  1313. return 0;
  1314. }
  1315. static int
  1316. getorder(size_t size)
  1317. {
  1318. switch (size) {
  1319. case 4096:
  1320. return 12;
  1321. case 512:
  1322. return 9;
  1323. case 8192:
  1324. return 13;
  1325. case 16384:
  1326. return 14;
  1327. case 32768:
  1328. return 15;
  1329. case 65536:
  1330. return 16;
  1331. case 131072:
  1332. return 17;
  1333. case 262144:
  1334. return 18;
  1335. case 524288:
  1336. return 19;
  1337. case 1048576:
  1338. return 20;
  1339. case 2048:
  1340. return 11;
  1341. case 1024:
  1342. return 10;
  1343. default:
  1344. return 0;
  1345. }
  1346. }
  1347. static void
  1348. update_fs_free(char *path)
  1349. {
  1350. static struct statvfs svb;
  1351. if (statvfs(path, &svb) == -1)
  1352. fs_free = 0;
  1353. else
  1354. fs_free = svb.f_bavail << getorder(svb.f_bsize);
  1355. }
  1356. static int
  1357. show_mediainfo(char *fpath, char *arg)
  1358. {
  1359. if (!get_output(g_buf, MAX_CMD_LEN, "which", metaviewer, NULL, 0))
  1360. return -1;
  1361. exitcurses();
  1362. get_output(NULL, 0, metaviewer, fpath, arg, 1);
  1363. initcurses();
  1364. return 0;
  1365. }
  1366. /*
  1367. * The help string tokens (each line) start with a HEX value
  1368. * which indicates the number of spaces to print before the
  1369. * particular token. This method was chosen instead of a flat
  1370. * string because the number of bytes in help was increasing
  1371. * the binary size by around a hundred bytes. This would only
  1372. * have increased as we keep adding new options.
  1373. */
  1374. static int
  1375. show_help(char *path)
  1376. {
  1377. char tmp[] = "/tmp/nnnXXXXXX";
  1378. int i = 0, fd = mkstemp(tmp);
  1379. char *start, *end;
  1380. static char helpstr[] = (
  1381. "cKey | Function\n"
  1382. "e- + -\n"
  1383. "7↑, k, ^P | Previous entry\n"
  1384. "7↓, j, ^N | Next entry\n"
  1385. "7PgUp, ^U | Scroll half page up\n"
  1386. "7PgDn, ^D | Scroll half page down\n"
  1387. "1Home, g, ^, ^A | Jump to first entry\n"
  1388. "2End, G, $, ^E | Jump to last entry\n"
  1389. "4→, ↵, l, ^M | Open file or enter dir\n"
  1390. "1←, Bksp, h, ^H | Go to parent dir\n"
  1391. "9Insert | Toggle navigate-as-you-type\n"
  1392. "e~ | Jump to HOME dir\n"
  1393. "e& | Jump to initial dir\n"
  1394. "e- | Jump to last visited dir\n"
  1395. "e/ | Filter dir contents\n"
  1396. "d^/ | Open desktop search tool\n"
  1397. "e. | Toggle hide .dot files\n"
  1398. "eb | Show bookmark key prompt\n"
  1399. "d^B | Mark current dir\n"
  1400. "d^V | Visit marked dir\n"
  1401. "ec | Show change dir prompt\n"
  1402. "ed | Toggle detail view\n"
  1403. "eD | Show current file details\n"
  1404. "em | Show concise media info\n"
  1405. "eM | Show full media info\n"
  1406. "d^R | Rename selected entry\n"
  1407. "es | Toggle sort by file size\n"
  1408. "eS | Toggle disk usage mode\n"
  1409. "et | Toggle sort by mtime\n"
  1410. "e! | Spawn SHELL in current dir\n"
  1411. "ee | Edit entry in EDITOR\n"
  1412. "eo | Open dir in file manager\n"
  1413. "ep | Open entry in PAGER\n"
  1414. "d^K | Invoke file path copier\n"
  1415. "d^L | Force a redraw, unfilter\n"
  1416. "e? | Show help, settings\n"
  1417. "eQ | Quit and change dir\n"
  1418. "aq, ^Q | Quit\n\n");
  1419. if (fd == -1)
  1420. return -1;
  1421. start = end = helpstr;
  1422. while (*end) {
  1423. while (*end != '\n')
  1424. ++end;
  1425. if (start == end) {
  1426. ++end;
  1427. continue;
  1428. }
  1429. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1430. start = ++end;
  1431. }
  1432. dprintf(fd, "\n");
  1433. if (getenv("NNN_BMS")) {
  1434. dprintf(fd, "BOOKMARKS\n");
  1435. for (; i < MAX_BM; ++i)
  1436. if (bookmark[i].key)
  1437. dprintf(fd, " %s: %s\n",
  1438. bookmark[i].key, bookmark[i].loc);
  1439. else
  1440. break;
  1441. dprintf(fd, "\n");
  1442. }
  1443. if (editor)
  1444. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1445. if (desktop_manager)
  1446. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1447. if (idletimeout)
  1448. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1449. if (copier)
  1450. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1451. update_fs_free(path);
  1452. dprintf(fd, "\nVolume: %s free\n", coolsize(fs_free));
  1453. dprintf(fd, "\n");
  1454. close(fd);
  1455. exitcurses();
  1456. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1457. unlink(tmp);
  1458. initcurses();
  1459. return 0;
  1460. }
  1461. static int
  1462. sum_bsizes(const char *fpath, const struct stat *sb,
  1463. int typeflag, struct FTW *ftwbuf)
  1464. {
  1465. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1466. ent_blocks += sb->st_blocks;
  1467. ++num_files;
  1468. return 0;
  1469. }
  1470. static int
  1471. dentfill(char *path, struct entry **dents,
  1472. int (*filter)(regex_t *, char *), regex_t *re)
  1473. {
  1474. static DIR *dirp;
  1475. static struct dirent *dp;
  1476. static struct stat sb_path, sb;
  1477. static int fd, n;
  1478. static char *namep;
  1479. static ulong num_saved;
  1480. static struct entry *dentp;
  1481. dirp = opendir(path);
  1482. if (dirp == NULL)
  1483. return 0;
  1484. fd = dirfd(dirp);
  1485. n = 0;
  1486. if (cfg.blkorder) {
  1487. num_files = 0;
  1488. dir_blocks = 0;
  1489. update_fs_free(path);
  1490. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1491. printwarn();
  1492. return 0;
  1493. }
  1494. }
  1495. while ((dp = readdir(dirp)) != NULL) {
  1496. namep = dp->d_name;
  1497. if (filter(re, namep) == 0) {
  1498. if (!cfg.blkorder)
  1499. continue;
  1500. /* Skip self and parent */
  1501. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1502. continue;
  1503. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW)
  1504. == -1)
  1505. continue;
  1506. if (S_ISDIR(sb.st_mode)) {
  1507. if (sb_path.st_dev == sb.st_dev) {
  1508. ent_blocks = 0;
  1509. mkpath(path, namep, g_buf, PATH_MAX);
  1510. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1511. printmsg(STR_NFTWFAIL);
  1512. dir_blocks += sb.st_blocks;
  1513. } else
  1514. dir_blocks += ent_blocks;
  1515. }
  1516. } else {
  1517. if (sb.st_blocks)
  1518. dir_blocks += sb.st_blocks;
  1519. ++num_files;
  1520. }
  1521. continue;
  1522. }
  1523. /* Skip self and parent */
  1524. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1525. (namep[1] == '.' && namep[2] == '\0'))))
  1526. continue;
  1527. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1528. if (*dents)
  1529. free(*dents);
  1530. printerr(1, "fstatat");
  1531. }
  1532. if (n == total_dents) {
  1533. total_dents += 64;
  1534. *dents = realloc(*dents, total_dents * sizeof(**dents));
  1535. if (*dents == NULL)
  1536. printerr(1, "realloc");
  1537. }
  1538. dentp = &(*dents)[n];
  1539. xstrlcpy(dentp->name, namep, NAME_MAX);
  1540. dentp->mode = sb.st_mode;
  1541. dentp->t = sb.st_mtime;
  1542. dentp->size = sb.st_size;
  1543. if (cfg.blkorder) {
  1544. if (S_ISDIR(sb.st_mode)) {
  1545. ent_blocks = 0;
  1546. num_saved = num_files + 1;
  1547. mkpath(path, namep, g_buf, PATH_MAX);
  1548. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1549. printmsg(STR_NFTWFAIL);
  1550. dentp->blocks = sb.st_blocks;
  1551. } else
  1552. dentp->blocks = ent_blocks;
  1553. if (sb_path.st_dev == sb.st_dev)
  1554. dir_blocks += dentp->blocks;
  1555. else
  1556. num_files = num_saved;
  1557. } else {
  1558. dentp->blocks = sb.st_blocks;
  1559. dir_blocks += dentp->blocks;
  1560. ++num_files;
  1561. }
  1562. }
  1563. ++n;
  1564. }
  1565. /* Should never be null */
  1566. if (closedir(dirp) == -1) {
  1567. if (*dents)
  1568. free(*dents);
  1569. printerr(1, "closedir");
  1570. }
  1571. return n;
  1572. }
  1573. static void
  1574. dentfree(struct entry *dents)
  1575. {
  1576. free(dents);
  1577. }
  1578. /* Return the position of the matching entry or 0 otherwise */
  1579. static int
  1580. dentfind(struct entry *dents, int n, char *path)
  1581. {
  1582. if (!path)
  1583. return 0;
  1584. static int i;
  1585. static char *p;
  1586. p = basename(path);
  1587. DPRINTF_S(p);
  1588. for (i = 0; i < n; ++i)
  1589. if (xstrcmp(p, dents[i].name) == 0)
  1590. return i;
  1591. return 0;
  1592. }
  1593. static int
  1594. populate(char *path, char *oldpath, char *fltr)
  1595. {
  1596. static regex_t re;
  1597. /* Can fail when permissions change while browsing.
  1598. * It's assumed that path IS a directory when we are here.
  1599. */
  1600. if (access(path, R_OK) == -1)
  1601. return -1;
  1602. /* Search filter */
  1603. if (setfilter(&re, fltr) != 0)
  1604. return -1;
  1605. if (cfg.blkorder) {
  1606. printmsg("Calculating...");
  1607. refresh();
  1608. }
  1609. ndents = dentfill(path, &dents, visible, &re);
  1610. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1611. /* Find cur from history */
  1612. cur = dentfind(dents, ndents, oldpath);
  1613. return 0;
  1614. }
  1615. static void
  1616. redraw(char *path)
  1617. {
  1618. static int nlines, i;
  1619. static size_t ncols;
  1620. nlines = MIN(LINES - 4, ndents);
  1621. /* Clean screen */
  1622. erase();
  1623. /* Strip trailing slashes */
  1624. for (i = xstrlen(path) - 1; i > 0; --i)
  1625. if (path[i] == '/')
  1626. path[i] = '\0';
  1627. else
  1628. break;
  1629. DPRINTF_D(cur);
  1630. DPRINTF_S(path);
  1631. /* No text wrapping in cwd line */
  1632. if (!realpath(path, g_buf)) {
  1633. printwarn();
  1634. return;
  1635. }
  1636. ncols = COLS;
  1637. if (ncols > PATH_MAX)
  1638. ncols = PATH_MAX;
  1639. /* - xstrlen(CWD) - 1 = 6 */
  1640. g_buf[ncols - 6] = '\0';
  1641. printw(CWD "%s\n\n", g_buf);
  1642. if (cfg.showcolor) {
  1643. attron(COLOR_PAIR(1) | A_BOLD);
  1644. cfg.dircolor = 1;
  1645. }
  1646. /* Print listing */
  1647. if (cur < (nlines >> 1)) {
  1648. for (i = 0; i < nlines; ++i)
  1649. printptr(&dents[i], i == cur);
  1650. } else if (cur >= ndents - (nlines >> 1)) {
  1651. for (i = ndents - nlines; i < ndents; ++i)
  1652. printptr(&dents[i], i == cur);
  1653. } else {
  1654. static int odd;
  1655. odd = ISODD(nlines);
  1656. nlines >>= 1;
  1657. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1658. printptr(&dents[i], i == cur);
  1659. }
  1660. /* Must reset e.g. no files in dir */
  1661. if (cfg.dircolor) {
  1662. attroff(COLOR_PAIR(1) | A_BOLD);
  1663. cfg.dircolor = 0;
  1664. }
  1665. if (cfg.showdetail) {
  1666. if (ndents) {
  1667. static char ind[2] = "\0\0";
  1668. static char sort[9];
  1669. if (cfg.mtimeorder)
  1670. sprintf(sort, "by time ");
  1671. else if (cfg.sizeorder)
  1672. sprintf(sort, "by size ");
  1673. else
  1674. sort[0] = '\0';
  1675. if (S_ISDIR(dents[cur].mode))
  1676. ind[0] = '/';
  1677. else if (S_ISLNK(dents[cur].mode))
  1678. ind[0] = '@';
  1679. else if (S_ISSOCK(dents[cur].mode))
  1680. ind[0] = '=';
  1681. else if (S_ISFIFO(dents[cur].mode))
  1682. ind[0] = '|';
  1683. else if (dents[cur].mode & 0100)
  1684. ind[0] = '*';
  1685. else
  1686. ind[0] = '\0';
  1687. /* We need to show filename as it may
  1688. * be truncated in directory listing
  1689. */
  1690. if (!cfg.blkorder)
  1691. sprintf(g_buf, "total %d %s[%s%s]", ndents, sort, unescape(dents[cur].name), ind);
  1692. else {
  1693. i = sprintf(g_buf, "du: %s (%lu files) ", coolsize(dir_blocks << 9), num_files);
  1694. sprintf(g_buf + i, "vol: %s free [%s%s]", coolsize(fs_free), unescape(dents[cur].name), ind);
  1695. }
  1696. printmsg(g_buf);
  1697. } else
  1698. printmsg("0 items");
  1699. }
  1700. }
  1701. static void
  1702. browse(char *ipath, char *ifilter)
  1703. {
  1704. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX], lastdir[PATH_MAX], mark[PATH_MAX];
  1705. static char fltr[LINE_MAX];
  1706. char *dir, *tmp, *run, *env, *dstdir = NULL;
  1707. struct stat sb;
  1708. int r, fd, presel;
  1709. enum action sel = SEL_RUNARG + 1;
  1710. xstrlcpy(path, ipath, PATH_MAX);
  1711. xstrlcpy(fltr, ifilter, LINE_MAX);
  1712. oldpath[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  1713. if (cfg.filtermode)
  1714. presel = FILTER;
  1715. else
  1716. presel = 0;
  1717. begin:
  1718. #ifdef LINUX_INOTIFY
  1719. if (inotify_wd >= 0)
  1720. inotify_rm_watch(inotify_fd, inotify_wd);
  1721. #elif defined(BSD_KQUEUE)
  1722. if (event_fd >= 0)
  1723. close(event_fd);
  1724. #endif
  1725. if (populate(path, oldpath, fltr) == -1) {
  1726. printwarn();
  1727. goto nochange;
  1728. }
  1729. #ifdef LINUX_INOTIFY
  1730. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  1731. #elif defined(BSD_KQUEUE)
  1732. event_fd = open(path, O_EVTONLY);
  1733. if (event_fd >= 0)
  1734. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  1735. #endif
  1736. for (;;) {
  1737. redraw(path);
  1738. nochange:
  1739. /* Exit if parent has exited */
  1740. if (getppid() == 1)
  1741. _exit(0);
  1742. sel = nextsel(&run, &env, &presel);
  1743. switch (sel) {
  1744. case SEL_CDQUIT:
  1745. {
  1746. char *tmpfile = "/tmp/nnn";
  1747. tmp = getenv("NNN_TMPFILE");
  1748. if (tmp)
  1749. tmpfile = tmp;
  1750. FILE *fp = fopen(tmpfile, "w");
  1751. if (fp) {
  1752. fprintf(fp, "cd \"%s\"", path);
  1753. fclose(fp);
  1754. }
  1755. /* Fall through to exit */
  1756. } // fallthrough
  1757. case SEL_QUIT:
  1758. dentfree(dents);
  1759. return;
  1760. case SEL_BACK:
  1761. /* There is no going back */
  1762. if (istopdir(path)) {
  1763. printmsg(STR_ATROOT);
  1764. goto nochange;
  1765. }
  1766. dir = xdirname(path);
  1767. if (access(dir, R_OK) == -1) {
  1768. printwarn();
  1769. goto nochange;
  1770. }
  1771. /* Save history */
  1772. xstrlcpy(oldpath, path, PATH_MAX);
  1773. /* Save last working directory */
  1774. xstrlcpy(lastdir, path, PATH_MAX);
  1775. xstrlcpy(path, dir, PATH_MAX);
  1776. /* Reset filter */
  1777. xstrlcpy(fltr, ifilter, LINE_MAX);
  1778. if (cfg.filtermode)
  1779. presel = FILTER;
  1780. goto begin;
  1781. case SEL_GOIN:
  1782. /* Cannot descend in empty directories */
  1783. if (ndents == 0)
  1784. goto begin;
  1785. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1786. DPRINTF_S(newpath);
  1787. /* Get path info */
  1788. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1789. if (fd == -1) {
  1790. printwarn();
  1791. goto nochange;
  1792. }
  1793. r = fstat(fd, &sb);
  1794. if (r == -1) {
  1795. printwarn();
  1796. close(fd);
  1797. goto nochange;
  1798. }
  1799. close(fd);
  1800. DPRINTF_U(sb.st_mode);
  1801. switch (sb.st_mode & S_IFMT) {
  1802. case S_IFDIR:
  1803. if (access(newpath, R_OK) == -1) {
  1804. printwarn();
  1805. goto nochange;
  1806. }
  1807. /* Save last working directory */
  1808. xstrlcpy(lastdir, path, PATH_MAX);
  1809. xstrlcpy(path, newpath, PATH_MAX);
  1810. oldpath[0] = '\0';
  1811. /* Reset filter */
  1812. xstrlcpy(fltr, ifilter, LINE_MAX);
  1813. if (cfg.filtermode)
  1814. presel = FILTER;
  1815. goto begin;
  1816. case S_IFREG:
  1817. {
  1818. /* If NNN_USE_EDITOR is set,
  1819. * open text in EDITOR
  1820. */
  1821. if (editor) {
  1822. if (getmime(dents[cur].name)) {
  1823. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1824. continue;
  1825. }
  1826. /* Recognize and open plain
  1827. * text files with vi
  1828. */
  1829. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  1830. continue;
  1831. if (strstr(g_buf, "text/") == g_buf) {
  1832. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1833. continue;
  1834. }
  1835. }
  1836. /* Invoke desktop opener as last resort */
  1837. spawn(utils[0], newpath, NULL, NULL, F_NOTRACE);
  1838. continue;
  1839. }
  1840. default:
  1841. printmsg("Unsupported file");
  1842. goto nochange;
  1843. }
  1844. case SEL_FLTR:
  1845. presel = filterentries(path);
  1846. xstrlcpy(fltr, ifilter, LINE_MAX);
  1847. DPRINTF_S(fltr);
  1848. /* Save current */
  1849. if (ndents > 0)
  1850. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  1851. goto nochange;
  1852. case SEL_MFLTR:
  1853. cfg.filtermode ^= 1;
  1854. if (cfg.filtermode)
  1855. presel = FILTER;
  1856. else
  1857. printmsg("navigate-as-you-type off");
  1858. goto nochange;
  1859. case SEL_SEARCH:
  1860. spawn(player, path, "search", NULL, F_NORMAL);
  1861. break;
  1862. case SEL_NEXT:
  1863. if (cur < ndents - 1)
  1864. ++cur;
  1865. else if (ndents)
  1866. /* Roll over, set cursor to first entry */
  1867. cur = 0;
  1868. break;
  1869. case SEL_PREV:
  1870. if (cur > 0)
  1871. --cur;
  1872. else if (ndents)
  1873. /* Roll over, set cursor to last entry */
  1874. cur = ndents - 1;
  1875. break;
  1876. case SEL_PGDN:
  1877. if (cur < ndents - 1)
  1878. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1879. break;
  1880. case SEL_PGUP:
  1881. if (cur > 0)
  1882. cur -= MIN((LINES - 4) / 2, cur);
  1883. break;
  1884. case SEL_HOME:
  1885. cur = 0;
  1886. break;
  1887. case SEL_END:
  1888. cur = ndents - 1;
  1889. break;
  1890. case SEL_CD:
  1891. {
  1892. char *input;
  1893. int truecd;
  1894. /* Save the program start dir */
  1895. tmp = getcwd(newpath, PATH_MAX);
  1896. if (tmp == NULL) {
  1897. printwarn();
  1898. goto nochange;
  1899. }
  1900. /* Switch to current path for readline(3) */
  1901. if (chdir(path) == -1) {
  1902. printwarn();
  1903. goto nochange;
  1904. }
  1905. exitcurses();
  1906. tmp = readline("chdir: ");
  1907. initcurses();
  1908. /* Change back to program start dir */
  1909. if (chdir(newpath) == -1)
  1910. printwarn();
  1911. if (tmp[0] == '\0')
  1912. break;
  1913. /* Add to readline(3) history */
  1914. add_history(tmp);
  1915. input = tmp;
  1916. tmp = strstrip(tmp);
  1917. if (tmp[0] == '\0') {
  1918. free(input);
  1919. break;
  1920. }
  1921. truecd = 0;
  1922. if (tmp[0] == '~') {
  1923. /* Expand ~ to HOME absolute path */
  1924. char *home = getenv("HOME");
  1925. if (home)
  1926. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  1927. else {
  1928. free(input);
  1929. printmsg(STR_NOHOME);
  1930. goto nochange;
  1931. }
  1932. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1933. if (lastdir[0] == '\0') {
  1934. free(input);
  1935. break;
  1936. }
  1937. /* Switch to last visited dir */
  1938. xstrlcpy(newpath, lastdir, PATH_MAX);
  1939. truecd = 1;
  1940. } else if ((r = all_dots(tmp))) {
  1941. if (r == 1) {
  1942. /* Always in the current dir */
  1943. free(input);
  1944. break;
  1945. }
  1946. /* Show a message if already at / */
  1947. if (istopdir(path)) {
  1948. printmsg(STR_ATROOT);
  1949. free(input);
  1950. goto nochange;
  1951. }
  1952. --r; /* One . for the current dir */
  1953. dir = path;
  1954. /* Note: fd is used as a tmp variable here */
  1955. for (fd = 0; fd < r; ++fd) {
  1956. /* Reached / ? */
  1957. if (istopdir(path)) {
  1958. /* Can't cd beyond / */
  1959. break;
  1960. }
  1961. dir = xdirname(dir);
  1962. if (access(dir, R_OK) == -1) {
  1963. printwarn();
  1964. free(input);
  1965. goto nochange;
  1966. }
  1967. }
  1968. truecd = 1;
  1969. /* Save the path in case of cd ..
  1970. * We mark the current dir in parent dir
  1971. */
  1972. if (r == 1) {
  1973. xstrlcpy(oldpath, path, PATH_MAX);
  1974. truecd = 2;
  1975. }
  1976. xstrlcpy(newpath, dir, PATH_MAX);
  1977. } else
  1978. mkpath(path, tmp, newpath, PATH_MAX);
  1979. free(input);
  1980. if (!xdiraccess(newpath))
  1981. goto nochange;
  1982. if (truecd == 0) {
  1983. /* Probable change in dir */
  1984. /* No-op if it's the same directory */
  1985. if (xstrcmp(path, newpath) == 0)
  1986. break;
  1987. oldpath[0] = '\0';
  1988. } else if (truecd == 1)
  1989. /* Sure change in dir */
  1990. oldpath[0] = '\0';
  1991. /* Save last working directory */
  1992. xstrlcpy(lastdir, path, PATH_MAX);
  1993. /* Save the newly opted dir in path */
  1994. xstrlcpy(path, newpath, PATH_MAX);
  1995. /* Reset filter */
  1996. xstrlcpy(fltr, ifilter, LINE_MAX);
  1997. DPRINTF_S(path);
  1998. if (cfg.filtermode)
  1999. presel = FILTER;
  2000. goto begin;
  2001. }
  2002. case SEL_CDHOME:
  2003. dstdir = getenv("HOME");
  2004. if (dstdir == NULL) {
  2005. clearprompt();
  2006. goto nochange;
  2007. } // fallthrough
  2008. case SEL_CDBEGIN:
  2009. if (!dstdir)
  2010. dstdir = ipath;
  2011. if (!xdiraccess(dstdir)) {
  2012. dstdir = NULL;
  2013. goto nochange;
  2014. }
  2015. if (xstrcmp(path, dstdir) == 0) {
  2016. dstdir = NULL;
  2017. break;
  2018. }
  2019. /* Save last working directory */
  2020. xstrlcpy(lastdir, path, PATH_MAX);
  2021. xstrlcpy(path, dstdir, PATH_MAX);
  2022. oldpath[0] = '\0';
  2023. /* Reset filter */
  2024. xstrlcpy(fltr, ifilter, LINE_MAX);
  2025. DPRINTF_S(path);
  2026. if (cfg.filtermode)
  2027. presel = FILTER;
  2028. dstdir = NULL;
  2029. goto begin;
  2030. case SEL_CDLAST: // fallthrough
  2031. case SEL_VISIT:
  2032. if (sel == SEL_VISIT) {
  2033. if (xstrcmp(mark, path) == 0)
  2034. break;
  2035. tmp = mark;
  2036. } else
  2037. tmp = lastdir;
  2038. if (tmp[0] == '\0') {
  2039. printmsg("Not set...");
  2040. goto nochange;
  2041. }
  2042. if (!xdiraccess(tmp))
  2043. goto nochange;
  2044. xstrlcpy(newpath, tmp, PATH_MAX);
  2045. xstrlcpy(lastdir, path, PATH_MAX);
  2046. xstrlcpy(path, newpath, PATH_MAX);
  2047. oldpath[0] = '\0';
  2048. /* Reset filter */
  2049. xstrlcpy(fltr, ifilter, LINE_MAX);
  2050. DPRINTF_S(path);
  2051. if (cfg.filtermode)
  2052. presel = FILTER;
  2053. goto begin;
  2054. case SEL_CDBM:
  2055. printprompt("key: ");
  2056. tmp = readinput();
  2057. clearprompt();
  2058. if (tmp == NULL)
  2059. break;
  2060. for (r = 0; bookmark[r].key && r < MAX_BM; ++r) {
  2061. if (xstrcmp(bookmark[r].key, tmp) == -1)
  2062. continue;
  2063. if (bookmark[r].loc[0] == '~') {
  2064. /* Expand ~ to HOME */
  2065. char *home = getenv("HOME");
  2066. if (home)
  2067. snprintf(newpath, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  2068. else {
  2069. printmsg(STR_NOHOME);
  2070. goto nochange;
  2071. }
  2072. } else
  2073. mkpath(path, bookmark[r].loc,
  2074. newpath, PATH_MAX);
  2075. if (!xdiraccess(newpath))
  2076. goto nochange;
  2077. if (xstrcmp(path, newpath) == 0)
  2078. break;
  2079. oldpath[0] = '\0';
  2080. break;
  2081. }
  2082. if (!bookmark[r].key) {
  2083. printmsg("No matching bookmark");
  2084. goto nochange;
  2085. }
  2086. /* Save last working directory */
  2087. xstrlcpy(lastdir, path, PATH_MAX);
  2088. /* Save the newly opted dir in path */
  2089. xstrlcpy(path, newpath, PATH_MAX);
  2090. /* Reset filter */
  2091. xstrlcpy(fltr, ifilter, LINE_MAX);
  2092. DPRINTF_S(path);
  2093. if (cfg.filtermode)
  2094. presel = FILTER;
  2095. goto begin;
  2096. case SEL_MARK:
  2097. xstrlcpy(mark, path, PATH_MAX);
  2098. printmsg(mark);
  2099. goto nochange;
  2100. case SEL_TOGGLEDOT:
  2101. cfg.showhidden ^= 1;
  2102. initfilter(cfg.showhidden, &ifilter);
  2103. xstrlcpy(fltr, ifilter, LINE_MAX);
  2104. goto begin;
  2105. case SEL_DETAIL:
  2106. cfg.showdetail ^= 1;
  2107. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2108. /* Save current */
  2109. if (ndents > 0)
  2110. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2111. goto begin;
  2112. case SEL_STATS:
  2113. if (ndents > 0) {
  2114. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2115. r = lstat(oldpath, &sb);
  2116. if (r == -1) {
  2117. if (dents)
  2118. dentfree(dents);
  2119. printerr(1, "lstat");
  2120. } else {
  2121. r = show_stats(oldpath, dents[cur].name, &sb);
  2122. if (r < 0) {
  2123. printwarn();
  2124. goto nochange;
  2125. }
  2126. }
  2127. }
  2128. break;
  2129. case SEL_MEDIA: // fallthrough
  2130. case SEL_FMEDIA:
  2131. if (ndents > 0) {
  2132. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2133. if (show_mediainfo(oldpath, run) == -1) {
  2134. sprintf(g_buf, "%s missing", metaviewer);
  2135. printmsg(g_buf);
  2136. goto nochange;
  2137. }
  2138. }
  2139. break;
  2140. case SEL_DFB:
  2141. if (!desktop_manager) {
  2142. printmsg("NNN_DE_FILE_MANAGER not set");
  2143. goto nochange;
  2144. }
  2145. spawn(desktop_manager, path, NULL, path, F_NOTRACE | F_NOWAIT);
  2146. break;
  2147. case SEL_FSIZE:
  2148. cfg.sizeorder ^= 1;
  2149. cfg.mtimeorder = 0;
  2150. cfg.blkorder = 0;
  2151. /* Save current */
  2152. if (ndents > 0)
  2153. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2154. goto begin;
  2155. case SEL_BSIZE:
  2156. cfg.blkorder ^= 1;
  2157. if (cfg.blkorder) {
  2158. cfg.showdetail = 1;
  2159. printptr = &printent_long;
  2160. }
  2161. cfg.mtimeorder = 0;
  2162. cfg.sizeorder = 0;
  2163. /* Save current */
  2164. if (ndents > 0)
  2165. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2166. goto begin;
  2167. case SEL_MTIME:
  2168. cfg.mtimeorder ^= 1;
  2169. cfg.sizeorder = 0;
  2170. cfg.blkorder = 0;
  2171. /* Save current */
  2172. if (ndents > 0)
  2173. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2174. goto begin;
  2175. case SEL_REDRAW:
  2176. /* Save current */
  2177. if (ndents > 0)
  2178. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2179. goto begin;
  2180. case SEL_COPY:
  2181. if (copier && ndents) {
  2182. if (istopdir(path))
  2183. snprintf(newpath, PATH_MAX, "/%s", dents[cur].name);
  2184. else
  2185. snprintf(newpath, PATH_MAX, "%s/%s", path, dents[cur].name);
  2186. spawn(copier, newpath, NULL, NULL, F_NONE);
  2187. printmsg(newpath);
  2188. } else if (!copier)
  2189. printmsg("NNN_COPIER is not set");
  2190. goto nochange;
  2191. case SEL_RENAME:
  2192. if (ndents <= 0)
  2193. break;
  2194. printprompt("> ");
  2195. tmp = xreadline(dents[cur].name);
  2196. clearprompt();
  2197. if (tmp == NULL || tmp[0] == '\0')
  2198. break;
  2199. /* Allow only relative paths */
  2200. if (tmp[0] == '/' || basename(tmp) != tmp) {
  2201. printmsg("relative paths only");
  2202. goto nochange;
  2203. }
  2204. /* Skip renaming to same name */
  2205. if (xstrcmp(tmp, dents[cur].name) == 0)
  2206. break;
  2207. /* Open the descriptor to currently open directory */
  2208. fd = open(path, O_RDONLY | O_DIRECTORY);
  2209. if (fd == -1) {
  2210. printwarn();
  2211. goto nochange;
  2212. }
  2213. /* Check if another file with same name exists */
  2214. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2215. /* File with the same name exists */
  2216. printprompt("Press 'y' to overwrite: ");
  2217. cleartimeout();
  2218. r = getch();
  2219. settimeout();
  2220. if (r != 'y') {
  2221. close(fd);
  2222. break;
  2223. }
  2224. }
  2225. /* Rename the file */
  2226. r = renameat(fd, dents[cur].name, fd, tmp);
  2227. if (r != 0) {
  2228. printwarn();
  2229. close(fd);
  2230. goto nochange;
  2231. }
  2232. close(fd);
  2233. mkpath(path, tmp, oldpath, PATH_MAX);
  2234. goto begin;
  2235. case SEL_HELP:
  2236. show_help(path);
  2237. break;
  2238. case SEL_RUN:
  2239. run = xgetenv(env, run);
  2240. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2241. /* Repopulate as directory content may have changed */
  2242. goto begin;
  2243. case SEL_RUNARG:
  2244. run = xgetenv(env, run);
  2245. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2246. break;
  2247. }
  2248. /* Screensaver */
  2249. if (idletimeout != 0 && idle == idletimeout) {
  2250. idle = 0;
  2251. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2252. }
  2253. }
  2254. }
  2255. static void
  2256. usage(void)
  2257. {
  2258. printf("usage: nnn [-c N] [-e] [-i] [-l] [-p nlay] [-S]\n\
  2259. [-v] [-h] [PATH]\n\n\
  2260. The missing terminal file browser for X.\n\n\
  2261. positional arguments:\n\
  2262. PATH directory to open [default: current dir]\n\n\
  2263. optional arguments:\n\
  2264. -c N specify dir color, disables if N>7\n\
  2265. -e use exiftool instead of mediainfo\n\
  2266. -i start in navigate-as-you-type mode\n\
  2267. -l start in light mode (fewer details)\n\
  2268. -p nlay path to custom nlay\n\
  2269. -S start in disk usage analyzer mode\n\
  2270. -v show program version and exit\n\
  2271. -h show this help and exit\n\n\
  2272. Version: %s\n\
  2273. License: BSD 2-Clause\n\
  2274. Webpage: https://github.com/jarun/nnn\n", VERSION);
  2275. exit(0);
  2276. }
  2277. int
  2278. main(int argc, char *argv[])
  2279. {
  2280. static char cwd[PATH_MAX];
  2281. char *ipath, *ifilter, *bmstr;
  2282. int opt;
  2283. /* Confirm we are in a terminal */
  2284. if (!isatty(0) || !isatty(1)) {
  2285. fprintf(stderr, "stdin or stdout is not a tty\n");
  2286. exit(1);
  2287. }
  2288. while ((opt = getopt(argc, argv, "Slic:ep:vh")) != -1) {
  2289. switch (opt) {
  2290. case 'S':
  2291. cfg.blkorder = 1;
  2292. break;
  2293. case 'l':
  2294. cfg.showdetail = 0;
  2295. printptr = &printent;
  2296. break;
  2297. case 'i':
  2298. cfg.filtermode = 1;
  2299. break;
  2300. case 'c':
  2301. color = (uchar)atoi(optarg);
  2302. if (color > 7)
  2303. cfg.showcolor = 0;
  2304. break;
  2305. case 'e':
  2306. metaviewer = utils[3];
  2307. break;
  2308. case 'p':
  2309. player = optarg;
  2310. break;
  2311. case 'v':
  2312. printf("%s\n", VERSION);
  2313. return 0;
  2314. case 'h': // fallthrough
  2315. default:
  2316. usage();
  2317. }
  2318. }
  2319. if (argc == optind) {
  2320. /* Start in the current directory */
  2321. ipath = getcwd(cwd, PATH_MAX);
  2322. if (ipath == NULL)
  2323. ipath = "/";
  2324. } else {
  2325. ipath = realpath(argv[optind], cwd);
  2326. if (!ipath) {
  2327. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2328. exit(1);
  2329. }
  2330. }
  2331. /* Increase current open file descriptor limit */
  2332. open_max = max_openfds();
  2333. if (getuid() == 0)
  2334. cfg.showhidden = 1;
  2335. initfilter(cfg.showhidden, &ifilter);
  2336. #ifdef LINUX_INOTIFY
  2337. /* Initialize inotify */
  2338. inotify_fd = inotify_init1(IN_NONBLOCK);
  2339. if (inotify_fd < 0) {
  2340. fprintf(stderr, "Cannot initialize inotify: %s\n", strerror(errno));
  2341. exit(1);
  2342. }
  2343. #elif defined(BSD_KQUEUE)
  2344. kq = kqueue();
  2345. if (kq < 0) {
  2346. fprintf(stderr, "Cannot initialize kqueue: %s\n", strerror(errno));
  2347. exit(1);
  2348. }
  2349. gtimeout.tv_sec = 0;
  2350. gtimeout.tv_nsec = 50; /* 50 ns delay */
  2351. #endif
  2352. /* Parse bookmarks string, if available */
  2353. bmstr = getenv("NNN_BMS");
  2354. if (bmstr)
  2355. parsebmstr(bmstr);
  2356. /* Edit text in EDITOR, if opted */
  2357. if (getenv("NNN_USE_EDITOR"))
  2358. editor = xgetenv("EDITOR", "vi");
  2359. /* Set metadata viewer if not set */
  2360. if (!metaviewer)
  2361. metaviewer = utils[2];
  2362. /* Set player if not set already */
  2363. if (!player)
  2364. player = utils[1];
  2365. /* Get the desktop file browser, if set */
  2366. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2367. /* Get screensaver wait time, if set; copier used as tmp var */
  2368. copier = getenv("NNN_IDLE_TIMEOUT");
  2369. if (copier)
  2370. idletimeout = abs(atoi(copier));
  2371. /* Get the default copier, if set */
  2372. copier = getenv("NNN_COPIER");
  2373. signal(SIGINT, SIG_IGN);
  2374. /* Test initial path */
  2375. if (!xdiraccess(ipath)) {
  2376. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2377. exit(1);
  2378. }
  2379. /* Set locale */
  2380. setlocale(LC_ALL, "");
  2381. #ifdef DEBUGMODE
  2382. enabledbg();
  2383. #endif
  2384. initcurses();
  2385. browse(ipath, ifilter);
  2386. exitcurses();
  2387. #ifdef LINUX_INOTIFY
  2388. /* Shutdown inotify */
  2389. if (inotify_wd >= 0)
  2390. inotify_rm_watch(inotify_fd, inotify_wd);
  2391. close(inotify_fd);
  2392. #elif defined(BSD_KQUEUE)
  2393. if (event_fd >= 0)
  2394. close(event_fd);
  2395. close(kq);
  2396. #endif
  2397. #ifdef DEBUGMODE
  2398. disabledbg();
  2399. #endif
  2400. exit(0);
  2401. }