My build of nnn with minor changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

3008 lines
63 KiB

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