My build of nnn with minor changes
 
 
 
 
 
 

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