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

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