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.
 
 
 
 
 
 

2959 lines
61 KiB

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