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

2987 рядки
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. mode_t mode;
  178. uchar nlen; /* Length of file name */
  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. dentp = *dents;
  1570. dentp->name = pnamebuf;
  1571. for (count = 1; count < n; ++dentp, ++count)
  1572. /* Current filename starts at last filename start + length */
  1573. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1574. }
  1575. }
  1576. dentp = *dents + n;
  1577. /* Copy file name */
  1578. dentp->name = (char *)((size_t)pnamebuf + off);
  1579. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1580. off += dentp->nlen;
  1581. /* Copy other fields */
  1582. dentp->mode = sb.st_mode;
  1583. dentp->t = sb.st_mtime;
  1584. dentp->size = sb.st_size;
  1585. if (cfg.blkorder) {
  1586. if (S_ISDIR(sb.st_mode)) {
  1587. ent_blocks = 0;
  1588. num_saved = num_files + 1;
  1589. mkpath(path, namep, g_buf, PATH_MAX);
  1590. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1591. printmsg(STR_NFTWFAIL);
  1592. dentp->blocks = sb.st_blocks;
  1593. } else
  1594. dentp->blocks = ent_blocks;
  1595. if (sb_path.st_dev == sb.st_dev)
  1596. dir_blocks += dentp->blocks;
  1597. else
  1598. num_files = num_saved;
  1599. } else {
  1600. dentp->blocks = sb.st_blocks;
  1601. dir_blocks += dentp->blocks;
  1602. ++num_files;
  1603. }
  1604. }
  1605. ++n;
  1606. }
  1607. /* Should never be null */
  1608. if (closedir(dirp) == -1) {
  1609. if (*dents) {
  1610. free(pnamebuf);
  1611. free(*dents);
  1612. }
  1613. errexit();
  1614. }
  1615. return n;
  1616. }
  1617. static void
  1618. dentfree(struct entry *dents)
  1619. {
  1620. free(pnamebuf);
  1621. free(dents);
  1622. }
  1623. /* Return the position of the matching entry or 0 otherwise */
  1624. static int
  1625. dentfind(struct entry *dents, int n, char *path)
  1626. {
  1627. if (!path)
  1628. return 0;
  1629. static int i;
  1630. static char *p;
  1631. p = basename(path);
  1632. DPRINTF_S(p);
  1633. for (i = 0; i < n; ++i)
  1634. if (xstrcmp(p, dents[i].name) == 0)
  1635. return i;
  1636. return 0;
  1637. }
  1638. static int
  1639. populate(char *path, char *oldpath, char *fltr)
  1640. {
  1641. static regex_t re;
  1642. /* Can fail when permissions change while browsing.
  1643. * It's assumed that path IS a directory when we are here.
  1644. */
  1645. if (access(path, R_OK) == -1)
  1646. return -1;
  1647. /* Search filter */
  1648. if (setfilter(&re, fltr) != 0)
  1649. return -1;
  1650. if (cfg.blkorder) {
  1651. printmsg("Calculating...");
  1652. refresh();
  1653. }
  1654. #ifdef DEBUGMODE
  1655. struct timespec ts1, ts2;
  1656. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1657. #endif
  1658. ndents = dentfill(path, &dents, visible, &re);
  1659. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1660. #ifdef DEBUGMODE
  1661. clock_gettime(CLOCK_REALTIME, &ts2);
  1662. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1663. #endif
  1664. /* Find cur from history */
  1665. cur = dentfind(dents, ndents, oldpath);
  1666. return 0;
  1667. }
  1668. static void
  1669. redraw(char *path)
  1670. {
  1671. static char buf[(NAME_MAX + 1) << 1];
  1672. static size_t ncols;
  1673. static int nlines, i;
  1674. static bool mode_changed;
  1675. mode_changed = FALSE;
  1676. nlines = MIN(LINES - 4, ndents);
  1677. /* Clean screen */
  1678. erase();
  1679. /* Fail redraw if < than 10 columns */
  1680. if (COLS < 10) {
  1681. printmsg("Too few columns!");
  1682. return;
  1683. }
  1684. /* Strip trailing slashes */
  1685. for (i = xstrlen(path) - 1; i > 0; --i)
  1686. if (path[i] == '/')
  1687. path[i] = '\0';
  1688. else
  1689. break;
  1690. DPRINTF_D(cur);
  1691. DPRINTF_S(path);
  1692. if (!realpath(path, g_buf)) {
  1693. printwarn();
  1694. return;
  1695. }
  1696. ncols = COLS;
  1697. if (ncols > PATH_MAX)
  1698. ncols = PATH_MAX;
  1699. /* No text wrapping in cwd line */
  1700. /* Show CWD: - xstrlen(CWD) - 1 = 6 */
  1701. g_buf[ncols - 6] = '\0';
  1702. printw(CWD "%s\n\n", g_buf);
  1703. /* Fallback to light mode if less than 35 columns */
  1704. if (ncols < 35 && cfg.showdetail) {
  1705. cfg.showdetail ^= 1;
  1706. printptr = &printent;
  1707. mode_changed = TRUE;
  1708. }
  1709. /* Calculate the number of cols available to print entry name */
  1710. if (cfg.showdetail)
  1711. ncols -= 32;
  1712. else
  1713. ncols -= 5;
  1714. if (cfg.showcolor) {
  1715. attron(COLOR_PAIR(1) | A_BOLD);
  1716. cfg.dircolor = 1;
  1717. }
  1718. /* Print listing */
  1719. if (cur < (nlines >> 1)) {
  1720. for (i = 0; i < nlines; ++i)
  1721. printptr(&dents[i], i == cur, ncols);
  1722. } else if (cur >= ndents - (nlines >> 1)) {
  1723. for (i = ndents - nlines; i < ndents; ++i)
  1724. printptr(&dents[i], i == cur, ncols);
  1725. } else {
  1726. static int odd;
  1727. odd = ISODD(nlines);
  1728. nlines >>= 1;
  1729. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1730. printptr(&dents[i], i == cur, ncols);
  1731. }
  1732. /* Must reset e.g. no files in dir */
  1733. if (cfg.dircolor) {
  1734. attroff(COLOR_PAIR(1) | A_BOLD);
  1735. cfg.dircolor = 0;
  1736. }
  1737. if (cfg.showdetail) {
  1738. if (ndents) {
  1739. static char ind[2] = "\0\0";
  1740. static char sort[9];
  1741. if (cfg.mtimeorder)
  1742. sprintf(sort, "by time ");
  1743. else if (cfg.sizeorder)
  1744. sprintf(sort, "by size ");
  1745. else
  1746. sort[0] = '\0';
  1747. if (S_ISDIR(dents[cur].mode))
  1748. ind[0] = '/';
  1749. else if (S_ISLNK(dents[cur].mode))
  1750. ind[0] = '@';
  1751. else if (S_ISSOCK(dents[cur].mode))
  1752. ind[0] = '=';
  1753. else if (S_ISFIFO(dents[cur].mode))
  1754. ind[0] = '|';
  1755. else if (dents[cur].mode & 0100)
  1756. ind[0] = '*';
  1757. else
  1758. ind[0] = '\0';
  1759. /* We need to show filename as it may be truncated in directory listing */
  1760. if (!cfg.blkorder)
  1761. sprintf(buf, "%d/%d %s[%s%s]", cur + 1, ndents, sort, unescape(dents[cur].name, 0), ind);
  1762. else {
  1763. i = sprintf(buf, "%d/%d du: %s (%lu files) ", cur + 1, ndents, coolsize(dir_blocks << 9), num_files);
  1764. sprintf(buf + i, "vol: %s free [%s%s]", coolsize(get_fs_free(path)), unescape(dents[cur].name, 0), ind);
  1765. }
  1766. printmsg(buf);
  1767. } else
  1768. printmsg("0 items");
  1769. }
  1770. if (mode_changed) {
  1771. cfg.showdetail ^= 1;
  1772. printptr = &printent_long;
  1773. }
  1774. }
  1775. static void
  1776. browse(char *ipath, char *ifilter)
  1777. {
  1778. static char path[PATH_MAX], oldpath[PATH_MAX], newpath[PATH_MAX], lastdir[PATH_MAX], mark[PATH_MAX];
  1779. static char fltr[LINE_MAX];
  1780. char *dir, *tmp, *run = NULL, *env = NULL, *dstdir = NULL;
  1781. struct stat sb;
  1782. int r, fd, presel;
  1783. enum action sel = SEL_RUNARG + 1;
  1784. bool dir_changed = FALSE;
  1785. xstrlcpy(path, ipath, PATH_MAX);
  1786. xstrlcpy(fltr, ifilter, LINE_MAX);
  1787. oldpath[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  1788. if (cfg.filtermode)
  1789. presel = FILTER;
  1790. else
  1791. presel = 0;
  1792. /* Allocate buffer to hold names */
  1793. pnamebuf = (char *)malloc(NAMEBUF_INCR);
  1794. if (pnamebuf == NULL)
  1795. errexit();
  1796. begin:
  1797. #ifdef LINUX_INOTIFY
  1798. if (dir_changed && inotify_wd >= 0) {
  1799. inotify_rm_watch(inotify_fd, inotify_wd);
  1800. inotify_wd = -1;
  1801. dir_changed = FALSE;
  1802. }
  1803. #elif defined(BSD_KQUEUE)
  1804. if (dir_changed && event_fd >= 0) {
  1805. close(event_fd);
  1806. event_fd = -1;
  1807. dir_changed = FALSE;
  1808. }
  1809. #endif
  1810. if (populate(path, oldpath, fltr) == -1) {
  1811. printwarn();
  1812. goto nochange;
  1813. }
  1814. #ifdef LINUX_INOTIFY
  1815. if (inotify_wd == -1)
  1816. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  1817. #elif defined(BSD_KQUEUE)
  1818. if (event_fd == -1) {
  1819. #if defined(O_EVTONLY)
  1820. event_fd = open(path, O_EVTONLY);
  1821. #else
  1822. event_fd = open(path, O_RDONLY);
  1823. #endif
  1824. if (event_fd >= 0)
  1825. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  1826. }
  1827. #endif
  1828. for (;;) {
  1829. redraw(path);
  1830. nochange:
  1831. /* Exit if parent has exited */
  1832. if (getppid() == 1)
  1833. _exit(0);
  1834. sel = nextsel(&run, &env, &presel);
  1835. switch (sel) {
  1836. case SEL_BACK:
  1837. /* There is no going back */
  1838. if (istopdir(path)) {
  1839. printmsg(STR_ATROOT);
  1840. goto nochange;
  1841. }
  1842. dir = xdirname(path);
  1843. if (access(dir, R_OK) == -1) {
  1844. printwarn();
  1845. goto nochange;
  1846. }
  1847. /* Save history */
  1848. xstrlcpy(oldpath, path, PATH_MAX);
  1849. /* Save last working directory */
  1850. xstrlcpy(lastdir, path, PATH_MAX);
  1851. dir_changed = TRUE;
  1852. xstrlcpy(path, dir, PATH_MAX);
  1853. /* Reset filter */
  1854. xstrlcpy(fltr, ifilter, LINE_MAX);
  1855. if (cfg.filtermode)
  1856. presel = FILTER;
  1857. goto begin;
  1858. case SEL_GOIN:
  1859. /* Cannot descend in empty directories */
  1860. if (ndents == 0)
  1861. goto begin;
  1862. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1863. DPRINTF_S(newpath);
  1864. /* Get path info */
  1865. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1866. if (fd == -1) {
  1867. printwarn();
  1868. goto nochange;
  1869. }
  1870. if (fstat(fd, &sb) == -1) {
  1871. printwarn();
  1872. close(fd);
  1873. goto nochange;
  1874. }
  1875. close(fd);
  1876. DPRINTF_U(sb.st_mode);
  1877. switch (sb.st_mode & S_IFMT) {
  1878. case S_IFDIR:
  1879. if (access(newpath, R_OK) == -1) {
  1880. printwarn();
  1881. goto nochange;
  1882. }
  1883. /* Save last working directory */
  1884. xstrlcpy(lastdir, path, PATH_MAX);
  1885. dir_changed = TRUE;
  1886. xstrlcpy(path, newpath, PATH_MAX);
  1887. oldpath[0] = '\0';
  1888. /* Reset filter */
  1889. xstrlcpy(fltr, ifilter, LINE_MAX);
  1890. if (cfg.filtermode)
  1891. presel = FILTER;
  1892. goto begin;
  1893. case S_IFREG:
  1894. {
  1895. /* If NNN_USE_EDITOR is set,
  1896. * open text in EDITOR
  1897. */
  1898. if (editor) {
  1899. if (getmime(dents[cur].name)) {
  1900. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1901. continue;
  1902. }
  1903. /* Recognize and open plain
  1904. * text files with vi
  1905. */
  1906. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  1907. continue;
  1908. if (strstr(g_buf, "text/") == g_buf) {
  1909. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1910. continue;
  1911. }
  1912. }
  1913. /* Invoke desktop opener as last resort */
  1914. spawn(utils[2], newpath, NULL, NULL, nowait);
  1915. continue;
  1916. }
  1917. default:
  1918. printmsg("Unsupported file");
  1919. goto nochange;
  1920. }
  1921. case SEL_NEXT:
  1922. if (cur < ndents - 1)
  1923. ++cur;
  1924. else if (ndents)
  1925. /* Roll over, set cursor to first entry */
  1926. cur = 0;
  1927. break;
  1928. case SEL_PREV:
  1929. if (cur > 0)
  1930. --cur;
  1931. else if (ndents)
  1932. /* Roll over, set cursor to last entry */
  1933. cur = ndents - 1;
  1934. break;
  1935. case SEL_PGDN:
  1936. if (cur < ndents - 1)
  1937. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1938. break;
  1939. case SEL_PGUP:
  1940. if (cur > 0)
  1941. cur -= MIN((LINES - 4) / 2, cur);
  1942. break;
  1943. case SEL_HOME:
  1944. cur = 0;
  1945. break;
  1946. case SEL_END:
  1947. cur = ndents - 1;
  1948. break;
  1949. case SEL_CD:
  1950. {
  1951. char *input;
  1952. int truecd;
  1953. /* Save the program start dir */
  1954. tmp = getcwd(newpath, PATH_MAX);
  1955. if (tmp == NULL) {
  1956. printwarn();
  1957. goto nochange;
  1958. }
  1959. /* Switch to current path for readline(3) */
  1960. if (chdir(path) == -1) {
  1961. printwarn();
  1962. goto nochange;
  1963. }
  1964. exitcurses();
  1965. tmp = readline("chdir: ");
  1966. initcurses();
  1967. /* Change back to program start dir */
  1968. if (chdir(newpath) == -1)
  1969. printwarn();
  1970. if (tmp[0] == '\0')
  1971. break;
  1972. /* Add to readline(3) history */
  1973. add_history(tmp);
  1974. input = tmp;
  1975. tmp = strstrip(tmp);
  1976. if (tmp[0] == '\0') {
  1977. free(input);
  1978. break;
  1979. }
  1980. truecd = 0;
  1981. if (tmp[0] == '~') {
  1982. /* Expand ~ to HOME absolute path */
  1983. char *home = getenv("HOME");
  1984. if (home)
  1985. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  1986. else {
  1987. free(input);
  1988. printmsg(STR_NOHOME);
  1989. goto nochange;
  1990. }
  1991. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  1992. if (lastdir[0] == '\0') {
  1993. free(input);
  1994. break;
  1995. }
  1996. /* Switch to last visited dir */
  1997. xstrlcpy(newpath, lastdir, PATH_MAX);
  1998. truecd = 1;
  1999. } else if ((r = all_dots(tmp))) {
  2000. if (r == 1) {
  2001. /* Always in the current dir */
  2002. free(input);
  2003. break;
  2004. }
  2005. /* Show a message if already at / */
  2006. if (istopdir(path)) {
  2007. printmsg(STR_ATROOT);
  2008. free(input);
  2009. goto nochange;
  2010. }
  2011. --r; /* One . for the current dir */
  2012. dir = path;
  2013. /* Note: fd is used as a tmp variable here */
  2014. for (fd = 0; fd < r; ++fd) {
  2015. /* Reached / ? */
  2016. if (istopdir(path)) {
  2017. /* Can't cd beyond / */
  2018. break;
  2019. }
  2020. dir = xdirname(dir);
  2021. if (access(dir, R_OK) == -1) {
  2022. printwarn();
  2023. free(input);
  2024. goto nochange;
  2025. }
  2026. }
  2027. truecd = 1;
  2028. /* Save the path in case of cd ..
  2029. * We mark the current dir in parent dir
  2030. */
  2031. if (r == 1) {
  2032. xstrlcpy(oldpath, path, PATH_MAX);
  2033. truecd = 2;
  2034. }
  2035. xstrlcpy(newpath, dir, PATH_MAX);
  2036. } else
  2037. mkpath(path, tmp, newpath, PATH_MAX);
  2038. free(input);
  2039. if (!xdiraccess(newpath))
  2040. goto nochange;
  2041. if (truecd == 0) {
  2042. /* Probable change in dir */
  2043. /* No-op if it's the same directory */
  2044. if (xstrcmp(path, newpath) == 0)
  2045. break;
  2046. oldpath[0] = '\0';
  2047. } else if (truecd == 1)
  2048. /* Sure change in dir */
  2049. oldpath[0] = '\0';
  2050. /* Save last working directory */
  2051. xstrlcpy(lastdir, path, PATH_MAX);
  2052. dir_changed = TRUE;
  2053. /* Save the newly opted dir in path */
  2054. xstrlcpy(path, newpath, PATH_MAX);
  2055. /* Reset filter */
  2056. xstrlcpy(fltr, ifilter, LINE_MAX);
  2057. DPRINTF_S(path);
  2058. if (cfg.filtermode)
  2059. presel = FILTER;
  2060. goto begin;
  2061. }
  2062. case SEL_CDHOME:
  2063. dstdir = getenv("HOME");
  2064. if (dstdir == NULL) {
  2065. clearprompt();
  2066. goto nochange;
  2067. } // fallthrough
  2068. case SEL_CDBEGIN:
  2069. if (!dstdir)
  2070. dstdir = ipath;
  2071. if (!xdiraccess(dstdir)) {
  2072. dstdir = NULL;
  2073. goto nochange;
  2074. }
  2075. if (xstrcmp(path, dstdir) == 0) {
  2076. dstdir = NULL;
  2077. break;
  2078. }
  2079. /* Save last working directory */
  2080. xstrlcpy(lastdir, path, PATH_MAX);
  2081. dir_changed = TRUE;
  2082. xstrlcpy(path, dstdir, PATH_MAX);
  2083. oldpath[0] = '\0';
  2084. /* Reset filter */
  2085. xstrlcpy(fltr, ifilter, LINE_MAX);
  2086. DPRINTF_S(path);
  2087. if (cfg.filtermode)
  2088. presel = FILTER;
  2089. dstdir = NULL;
  2090. goto begin;
  2091. case SEL_CDLAST: // fallthrough
  2092. case SEL_VISIT:
  2093. if (sel == SEL_VISIT) {
  2094. if (xstrcmp(mark, path) == 0)
  2095. break;
  2096. tmp = mark;
  2097. } else
  2098. tmp = lastdir;
  2099. if (tmp[0] == '\0') {
  2100. printmsg("Not set...");
  2101. goto nochange;
  2102. }
  2103. if (!xdiraccess(tmp))
  2104. goto nochange;
  2105. xstrlcpy(newpath, tmp, PATH_MAX);
  2106. xstrlcpy(lastdir, path, PATH_MAX);
  2107. dir_changed = TRUE;
  2108. xstrlcpy(path, newpath, PATH_MAX);
  2109. oldpath[0] = '\0';
  2110. /* Reset filter */
  2111. xstrlcpy(fltr, ifilter, LINE_MAX);
  2112. DPRINTF_S(path);
  2113. if (cfg.filtermode)
  2114. presel = FILTER;
  2115. goto begin;
  2116. case SEL_CDBM:
  2117. printprompt("key: ");
  2118. tmp = readinput();
  2119. clearprompt();
  2120. if (tmp == NULL)
  2121. break;
  2122. for (r = 0; bookmark[r].key && r < BM_MAX; ++r) {
  2123. if (xstrcmp(bookmark[r].key, tmp) == -1)
  2124. continue;
  2125. if (bookmark[r].loc[0] == '~') {
  2126. /* Expand ~ to HOME */
  2127. char *home = getenv("HOME");
  2128. if (home)
  2129. snprintf(newpath, PATH_MAX, "%s%s", home, bookmark[r].loc + 1);
  2130. else {
  2131. printmsg(STR_NOHOME);
  2132. goto nochange;
  2133. }
  2134. } else
  2135. mkpath(path, bookmark[r].loc, newpath, PATH_MAX);
  2136. if (!xdiraccess(newpath))
  2137. goto nochange;
  2138. if (xstrcmp(path, newpath) == 0)
  2139. break;
  2140. oldpath[0] = '\0';
  2141. break;
  2142. }
  2143. if (!bookmark[r].key) {
  2144. printmsg("No matching bookmark");
  2145. goto nochange;
  2146. }
  2147. /* Save last working directory */
  2148. xstrlcpy(lastdir, path, PATH_MAX);
  2149. dir_changed = TRUE;
  2150. /* Save the newly opted dir in path */
  2151. xstrlcpy(path, newpath, PATH_MAX);
  2152. /* Reset filter */
  2153. xstrlcpy(fltr, ifilter, LINE_MAX);
  2154. DPRINTF_S(path);
  2155. if (cfg.filtermode)
  2156. presel = FILTER;
  2157. goto begin;
  2158. case SEL_PIN:
  2159. xstrlcpy(mark, path, PATH_MAX);
  2160. printmsg(mark);
  2161. goto nochange;
  2162. case SEL_FLTR:
  2163. presel = filterentries(path);
  2164. xstrlcpy(fltr, ifilter, LINE_MAX);
  2165. DPRINTF_S(fltr);
  2166. /* Save current */
  2167. if (ndents > 0)
  2168. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2169. goto nochange;
  2170. case SEL_MFLTR:
  2171. cfg.filtermode ^= 1;
  2172. if (cfg.filtermode)
  2173. presel = FILTER;
  2174. else
  2175. printmsg("navigate-as-you-type off");
  2176. goto nochange;
  2177. case SEL_SEARCH:
  2178. spawn(player, path, "search", NULL, F_NORMAL);
  2179. break;
  2180. case SEL_TOGGLEDOT:
  2181. cfg.showhidden ^= 1;
  2182. initfilter(cfg.showhidden, &ifilter);
  2183. xstrlcpy(fltr, ifilter, LINE_MAX);
  2184. goto begin;
  2185. case SEL_DETAIL:
  2186. cfg.showdetail ^= 1;
  2187. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2188. /* Save current */
  2189. if (ndents > 0)
  2190. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2191. goto begin;
  2192. case SEL_STATS:
  2193. if (ndents > 0) {
  2194. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2195. if (lstat(oldpath, &sb) == -1) {
  2196. if (dents)
  2197. dentfree(dents);
  2198. errexit();
  2199. } else {
  2200. if (show_stats(oldpath, dents[cur].name, &sb) < 0) {
  2201. printwarn();
  2202. goto nochange;
  2203. }
  2204. }
  2205. }
  2206. break;
  2207. case SEL_LIST: // fallthrough
  2208. case SEL_EXTRACT: // fallthrough
  2209. case SEL_MEDIA: // fallthrough
  2210. case SEL_FMEDIA:
  2211. if (ndents > 0) {
  2212. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2213. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2214. r = show_mediainfo(oldpath, run);
  2215. else
  2216. r = handle_archive(oldpath, run, path);
  2217. if (r == -1) {
  2218. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2219. sprintf(g_buf, "%s missing", utils[cfg.metaviewer]);
  2220. else
  2221. sprintf(g_buf, "%s missing", utils[4]);
  2222. printmsg(g_buf);
  2223. goto nochange;
  2224. }
  2225. }
  2226. break;
  2227. case SEL_DFB:
  2228. if (!desktop_manager) {
  2229. printmsg("NNN_DE_FILE_MANAGER not set");
  2230. goto nochange;
  2231. }
  2232. spawn(desktop_manager, path, NULL, path, F_NOTRACE | F_NOWAIT);
  2233. break;
  2234. case SEL_FSIZE:
  2235. cfg.sizeorder ^= 1;
  2236. cfg.mtimeorder = 0;
  2237. cfg.blkorder = 0;
  2238. /* Save current */
  2239. if (ndents > 0)
  2240. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2241. goto begin;
  2242. case SEL_BSIZE:
  2243. cfg.blkorder ^= 1;
  2244. if (cfg.blkorder) {
  2245. cfg.showdetail = 1;
  2246. printptr = &printent_long;
  2247. }
  2248. cfg.mtimeorder = 0;
  2249. cfg.sizeorder = 0;
  2250. /* Save current */
  2251. if (ndents > 0)
  2252. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2253. goto begin;
  2254. case SEL_MTIME:
  2255. cfg.mtimeorder ^= 1;
  2256. cfg.sizeorder = 0;
  2257. cfg.blkorder = 0;
  2258. /* Save current */
  2259. if (ndents > 0)
  2260. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2261. goto begin;
  2262. case SEL_REDRAW:
  2263. /* Save current */
  2264. if (ndents > 0)
  2265. mkpath(path, dents[cur].name, oldpath, PATH_MAX);
  2266. goto begin;
  2267. case SEL_COPY:
  2268. if (copier && ndents) {
  2269. if (istopdir(path))
  2270. snprintf(newpath, PATH_MAX, "/%s", dents[cur].name);
  2271. else
  2272. snprintf(newpath, PATH_MAX, "%s/%s", path, dents[cur].name);
  2273. spawn(copier, newpath, NULL, NULL, F_NONE);
  2274. printmsg(newpath);
  2275. } else if (!copier)
  2276. printmsg("NNN_COPIER is not set");
  2277. goto nochange;
  2278. case SEL_NEW:
  2279. printprompt("name: ");
  2280. tmp = xreadline(NULL);
  2281. clearprompt();
  2282. if (tmp == NULL || tmp[0] == '\0')
  2283. break;
  2284. /* Allow only relative, same dir paths */
  2285. if (tmp[0] == '/' || xstrcmp(basename(tmp), tmp) != 0) {
  2286. printmsg(STR_INPUT);
  2287. goto nochange;
  2288. }
  2289. /* Open the descriptor to currently open directory */
  2290. fd = open(path, O_RDONLY | O_DIRECTORY);
  2291. if (fd == -1) {
  2292. printwarn();
  2293. goto nochange;
  2294. }
  2295. /* Check if another file with same name exists */
  2296. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2297. printmsg("Entry exists");
  2298. goto nochange;
  2299. }
  2300. /* Check if it's a dir or file */
  2301. printprompt("Press 'f' for file or 'd' for dir");
  2302. cleartimeout();
  2303. r = getch();
  2304. settimeout();
  2305. if (r == 'f') {
  2306. r = openat(fd, tmp, O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
  2307. close(r);
  2308. } else if (r == 'd')
  2309. r = mkdirat(fd, tmp, S_IRWXU | S_IRWXG | S_IRWXO);
  2310. else {
  2311. close(fd);
  2312. break;
  2313. }
  2314. if (r == -1) {
  2315. printwarn();
  2316. close(fd);
  2317. goto nochange;
  2318. }
  2319. close(fd);
  2320. mkpath(path, tmp, oldpath, PATH_MAX);
  2321. goto begin;
  2322. case SEL_RENAME:
  2323. if (ndents <= 0)
  2324. break;
  2325. printprompt("");
  2326. tmp = xreadline(dents[cur].name);
  2327. clearprompt();
  2328. if (tmp == NULL || tmp[0] == '\0')
  2329. break;
  2330. /* Allow only relative, same dir paths */
  2331. if (tmp[0] == '/' || xstrcmp(basename(tmp), tmp) != 0) {
  2332. printmsg(STR_INPUT);
  2333. goto nochange;
  2334. }
  2335. /* Skip renaming to same name */
  2336. if (xstrcmp(tmp, dents[cur].name) == 0)
  2337. break;
  2338. /* Open the descriptor to currently open directory */
  2339. fd = open(path, O_RDONLY | O_DIRECTORY);
  2340. if (fd == -1) {
  2341. printwarn();
  2342. goto nochange;
  2343. }
  2344. /* Check if another file with same name exists */
  2345. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2346. /* File with the same name exists */
  2347. printprompt("Press 'y' to overwrite");
  2348. cleartimeout();
  2349. r = getch();
  2350. settimeout();
  2351. if (r != 'y') {
  2352. close(fd);
  2353. break;
  2354. }
  2355. }
  2356. /* Rename the file */
  2357. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2358. printwarn();
  2359. close(fd);
  2360. goto nochange;
  2361. }
  2362. close(fd);
  2363. mkpath(path, tmp, oldpath, PATH_MAX);
  2364. goto begin;
  2365. case SEL_HELP:
  2366. show_help(path);
  2367. break;
  2368. case SEL_RUN:
  2369. run = xgetenv(env, run);
  2370. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2371. /* Repopulate as directory content may have changed */
  2372. goto begin;
  2373. case SEL_RUNARG:
  2374. run = xgetenv(env, run);
  2375. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2376. break;
  2377. case SEL_CDQUIT:
  2378. {
  2379. char *tmpfile = "/tmp/nnn";
  2380. tmp = getenv("NNN_TMPFILE");
  2381. if (tmp)
  2382. tmpfile = tmp;
  2383. FILE *fp = fopen(tmpfile, "w");
  2384. if (fp) {
  2385. fprintf(fp, "cd \"%s\"", path);
  2386. fclose(fp);
  2387. }
  2388. /* Fall through to exit */
  2389. } // fallthrough
  2390. case SEL_QUIT:
  2391. dentfree(dents);
  2392. return;
  2393. }
  2394. /* Screensaver */
  2395. if (idletimeout != 0 && idle == idletimeout) {
  2396. idle = 0;
  2397. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2398. }
  2399. }
  2400. }
  2401. static void
  2402. usage(void)
  2403. {
  2404. printf("usage: nnn [-c N] [-e] [-i] [-l] [-p nlay] [-S]\n\
  2405. [-v] [-h] [PATH]\n\n\
  2406. The missing terminal file browser for X.\n\n\
  2407. positional arguments:\n\
  2408. PATH directory to open [default: current dir]\n\n\
  2409. optional arguments:\n\
  2410. -c N specify dir color, disables if N>7\n\
  2411. -e use exiftool instead of mediainfo\n\
  2412. -i start in navigate-as-you-type mode\n\
  2413. -l start in light mode (fewer details)\n\
  2414. -p nlay path to custom nlay\n\
  2415. -S start in disk usage analyzer mode\n\
  2416. -v show program version and exit\n\
  2417. -h show this help and exit\n\n\
  2418. Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2419. exit(0);
  2420. }
  2421. int
  2422. main(int argc, char *argv[])
  2423. {
  2424. static char cwd[PATH_MAX];
  2425. char *ipath, *ifilter, *bmstr;
  2426. int opt;
  2427. /* Confirm we are in a terminal */
  2428. if (!isatty(0) || !isatty(1)) {
  2429. fprintf(stderr, "stdin or stdout is not a tty\n");
  2430. exit(1);
  2431. }
  2432. while ((opt = getopt(argc, argv, "Slic:ep:vh")) != -1) {
  2433. switch (opt) {
  2434. case 'S':
  2435. cfg.blkorder = 1;
  2436. break;
  2437. case 'l':
  2438. cfg.showdetail = 0;
  2439. printptr = &printent;
  2440. break;
  2441. case 'i':
  2442. cfg.filtermode = 1;
  2443. break;
  2444. case 'c':
  2445. if (atoi(optarg) > 7)
  2446. cfg.showcolor = 0;
  2447. else
  2448. cfg.color = (uchar)atoi(optarg);
  2449. break;
  2450. case 'e':
  2451. cfg.metaviewer = 1;
  2452. break;
  2453. case 'p':
  2454. player = optarg;
  2455. break;
  2456. case 'v':
  2457. printf("%s\n", VERSION);
  2458. return 0;
  2459. case 'h': // fallthrough
  2460. default:
  2461. usage();
  2462. }
  2463. }
  2464. if (argc == optind) {
  2465. /* Start in the current directory */
  2466. ipath = getcwd(cwd, PATH_MAX);
  2467. if (ipath == NULL)
  2468. ipath = "/";
  2469. } else {
  2470. ipath = realpath(argv[optind], cwd);
  2471. if (!ipath) {
  2472. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2473. exit(1);
  2474. }
  2475. }
  2476. /* Increase current open file descriptor limit */
  2477. open_max = max_openfds();
  2478. if (getuid() == 0)
  2479. cfg.showhidden = 1;
  2480. initfilter(cfg.showhidden, &ifilter);
  2481. #ifdef LINUX_INOTIFY
  2482. /* Initialize inotify */
  2483. inotify_fd = inotify_init1(IN_NONBLOCK);
  2484. if (inotify_fd < 0) {
  2485. fprintf(stderr, "Cannot initialize inotify: %s\n", strerror(errno));
  2486. exit(1);
  2487. }
  2488. #elif defined(BSD_KQUEUE)
  2489. kq = kqueue();
  2490. if (kq < 0) {
  2491. fprintf(stderr, "Cannot initialize kqueue: %s\n", strerror(errno));
  2492. exit(1);
  2493. }
  2494. gtimeout.tv_sec = 0;
  2495. gtimeout.tv_nsec = 0;
  2496. #endif
  2497. /* Parse bookmarks string, if available */
  2498. bmstr = getenv("NNN_BMS");
  2499. if (bmstr)
  2500. parsebmstr(bmstr);
  2501. /* Edit text in EDITOR, if opted */
  2502. if (getenv("NNN_USE_EDITOR"))
  2503. editor = xgetenv("EDITOR", "vi");
  2504. /* Set player if not set already */
  2505. if (!player)
  2506. player = utils[3];
  2507. /* Get the desktop file browser, if set */
  2508. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2509. /* Get screensaver wait time, if set; copier used as tmp var */
  2510. copier = getenv("NNN_IDLE_TIMEOUT");
  2511. if (copier)
  2512. idletimeout = abs(atoi(copier));
  2513. /* Get the default copier, if set */
  2514. copier = getenv("NNN_COPIER");
  2515. /* Get nowait flag */
  2516. nowait |= getenv("NNN_NOWAIT") ? F_NOWAIT : 0;
  2517. signal(SIGINT, SIG_IGN);
  2518. /* Test initial path */
  2519. if (!xdiraccess(ipath)) {
  2520. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2521. exit(1);
  2522. }
  2523. /* Set locale */
  2524. setlocale(LC_ALL, "");
  2525. #ifdef DEBUGMODE
  2526. enabledbg();
  2527. #endif
  2528. initcurses();
  2529. browse(ipath, ifilter);
  2530. exitcurses();
  2531. #ifdef LINUX_INOTIFY
  2532. /* Shutdown inotify */
  2533. if (inotify_wd >= 0)
  2534. inotify_rm_watch(inotify_fd, inotify_wd);
  2535. close(inotify_fd);
  2536. #elif defined(BSD_KQUEUE)
  2537. if (event_fd >= 0)
  2538. close(event_fd);
  2539. close(kq);
  2540. #endif
  2541. #ifdef DEBUGMODE
  2542. disabledbg();
  2543. #endif
  2544. exit(0);
  2545. }