My build of nnn with minor changes
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 
 

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