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.
 
 
 
 
 
 

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