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.
 
 
 
 
 
 

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