My build of nnn with minor changes
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 
 

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