My build of nnn with minor changes
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

2982 рядки
63 KiB

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