My build of nnn with minor changes
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

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