My build of nnn with minor changes
 
 
 
 
 
 

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