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

3061 lines
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 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 -= (blocks << _WSHIFT);
  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 off_t tmp;
  1084. static long double rem;
  1085. static const double div_2_pow_10 = 1.0 / 1024.0;
  1086. i = 0;
  1087. rem = 0;
  1088. while (size > 1024) {
  1089. tmp = size;
  1090. size >>= 10;
  1091. rem = tmp - (size << 10);
  1092. ++i;
  1093. }
  1094. snprintf(size_buf, 12, "%.*Lf%c", i, size + rem * div_2_pow_10, U[i]);
  1095. return size_buf;
  1096. }
  1097. static char *
  1098. get_file_sym(mode_t mode)
  1099. {
  1100. static char ind[2] = "\0\0";
  1101. if (S_ISDIR(mode))
  1102. ind[0] = '/';
  1103. else if (S_ISLNK(mode))
  1104. ind[0] = '@';
  1105. else if (S_ISSOCK(mode))
  1106. ind[0] = '=';
  1107. else if (S_ISFIFO(mode))
  1108. ind[0] = '|';
  1109. else if (mode & 0100)
  1110. ind[0] = '*';
  1111. else
  1112. ind[0] = '\0';
  1113. return ind;
  1114. }
  1115. static void
  1116. printent(struct entry *ent, int sel, uint namecols)
  1117. {
  1118. static char *pname;
  1119. pname = unescape(ent->name, namecols);
  1120. /* Directories are always shown on top */
  1121. resetdircolor(ent->mode);
  1122. printw("%s%s%s\n", CURSYM(sel), pname, get_file_sym(ent->mode));
  1123. }
  1124. static void
  1125. printent_long(struct entry *ent, int sel, uint namecols)
  1126. {
  1127. static char buf[18], *pname;
  1128. strftime(buf, 18, "%Y-%m-%d %H:%M", localtime(&ent->t));
  1129. pname = unescape(ent->name, namecols);
  1130. /* Directories are always shown on top */
  1131. resetdircolor(ent->mode);
  1132. if (sel)
  1133. attron(A_REVERSE);
  1134. if (S_ISDIR(ent->mode)) {
  1135. if (cfg.blkorder)
  1136. printw("%s%-16.16s %8.8s/ %s/\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1137. else
  1138. printw("%s%-16.16s / %s/\n", CURSYM(sel), buf, pname);
  1139. } else if (S_ISLNK(ent->mode))
  1140. printw("%s%-16.16s @ %s@\n", CURSYM(sel), buf, pname);
  1141. else if (S_ISSOCK(ent->mode))
  1142. printw("%s%-16.16s = %s=\n", CURSYM(sel), buf, pname);
  1143. else if (S_ISFIFO(ent->mode))
  1144. printw("%s%-16.16s | %s|\n", CURSYM(sel), buf, pname);
  1145. else if (S_ISBLK(ent->mode))
  1146. printw("%s%-16.16s b %s\n", CURSYM(sel), buf, pname);
  1147. else if (S_ISCHR(ent->mode))
  1148. printw("%s%-16.16s c %s\n", CURSYM(sel), buf, pname);
  1149. else if (ent->mode & 0100) {
  1150. if (cfg.blkorder)
  1151. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1152. else
  1153. printw("%s%-16.16s %8.8s* %s*\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1154. } else {
  1155. if (cfg.blkorder)
  1156. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->blocks << 9), pname);
  1157. else
  1158. printw("%s%-16.16s %8.8s %s\n", CURSYM(sel), buf, coolsize(ent->size), pname);
  1159. }
  1160. if (sel)
  1161. attroff(A_REVERSE);
  1162. }
  1163. static void (*printptr)(struct entry *ent, int sel, uint namecols) = &printent_long;
  1164. static char
  1165. get_fileind(mode_t mode, char *desc)
  1166. {
  1167. static char c;
  1168. if (S_ISREG(mode)) {
  1169. c = '-';
  1170. xstrlcpy(desc, "regular file", DESCRIPTOR_LEN);
  1171. if (mode & 0100)
  1172. xstrlcpy(desc + 12, ", executable", DESCRIPTOR_LEN - 12); /* Length of string "regular file" is 12 */
  1173. } else if (S_ISDIR(mode)) {
  1174. c = 'd';
  1175. xstrlcpy(desc, "directory", DESCRIPTOR_LEN);
  1176. } else if (S_ISBLK(mode)) {
  1177. c = 'b';
  1178. xstrlcpy(desc, "block special device", DESCRIPTOR_LEN);
  1179. } else if (S_ISCHR(mode)) {
  1180. c = 'c';
  1181. xstrlcpy(desc, "character special device", DESCRIPTOR_LEN);
  1182. #ifdef S_ISFIFO
  1183. } else if (S_ISFIFO(mode)) {
  1184. c = 'p';
  1185. xstrlcpy(desc, "FIFO", DESCRIPTOR_LEN);
  1186. #endif /* S_ISFIFO */
  1187. #ifdef S_ISLNK
  1188. } else if (S_ISLNK(mode)) {
  1189. c = 'l';
  1190. xstrlcpy(desc, "symbolic link", DESCRIPTOR_LEN);
  1191. #endif /* S_ISLNK */
  1192. #ifdef S_ISSOCK
  1193. } else if (S_ISSOCK(mode)) {
  1194. c = 's';
  1195. xstrlcpy(desc, "socket", DESCRIPTOR_LEN);
  1196. #endif /* S_ISSOCK */
  1197. #ifdef S_ISDOOR
  1198. /* Solaris 2.6, etc. */
  1199. } else if (S_ISDOOR(mode)) {
  1200. c = 'D';
  1201. desc[0] = '\0';
  1202. #endif /* S_ISDOOR */
  1203. } else {
  1204. /* Unknown type -- possibly a regular file? */
  1205. c = '?';
  1206. desc[0] = '\0';
  1207. }
  1208. return c;
  1209. }
  1210. /* Convert a mode field into "ls -l" type perms field. */
  1211. static char *
  1212. get_lsperms(mode_t mode, char *desc)
  1213. {
  1214. static const char * const rwx[] = {"---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"};
  1215. static char bits[11] = {'\0'};
  1216. bits[0] = get_fileind(mode, desc);
  1217. xstrlcpy(&bits[1], rwx[(mode >> 6) & 7], 4);
  1218. xstrlcpy(&bits[4], rwx[(mode >> 3) & 7], 4);
  1219. xstrlcpy(&bits[7], rwx[(mode & 7)], 4);
  1220. if (mode & S_ISUID)
  1221. bits[3] = (mode & 0100) ? 's' : 'S'; /* user executable */
  1222. if (mode & S_ISGID)
  1223. bits[6] = (mode & 0010) ? 's' : 'l'; /* group executable */
  1224. if (mode & S_ISVTX)
  1225. bits[9] = (mode & 0001) ? 't' : 'T'; /* others executable */
  1226. return bits;
  1227. }
  1228. /*
  1229. * Gets only a single line (that's what we need
  1230. * for now) or shows full command output in pager.
  1231. *
  1232. * If pager is valid, returns NULL
  1233. */
  1234. static char *
  1235. get_output(char *buf, size_t bytes, char *file, char *arg1, char *arg2, int pager)
  1236. {
  1237. pid_t pid;
  1238. int pipefd[2];
  1239. FILE *pf;
  1240. int tmp, flags;
  1241. char *ret = NULL;
  1242. if (pipe(pipefd) == -1)
  1243. errexit();
  1244. for (tmp = 0; tmp < 2; ++tmp) {
  1245. /* Get previous flags */
  1246. flags = fcntl(pipefd[tmp], F_GETFL, 0);
  1247. /* Set bit for non-blocking flag */
  1248. flags |= O_NONBLOCK;
  1249. /* Change flags on fd */
  1250. fcntl(pipefd[tmp], F_SETFL, flags);
  1251. }
  1252. pid = fork();
  1253. if (pid == 0) {
  1254. /* In child */
  1255. close(pipefd[0]);
  1256. dup2(pipefd[1], STDOUT_FILENO);
  1257. dup2(pipefd[1], STDERR_FILENO);
  1258. close(pipefd[1]);
  1259. execlp(file, file, arg1, arg2, NULL);
  1260. _exit(1);
  1261. }
  1262. /* In parent */
  1263. waitpid(pid, &tmp, 0);
  1264. close(pipefd[1]);
  1265. if (!pager) {
  1266. pf = fdopen(pipefd[0], "r");
  1267. if (pf) {
  1268. ret = fgets(buf, bytes, pf);
  1269. close(pipefd[0]);
  1270. }
  1271. return ret;
  1272. }
  1273. pid = fork();
  1274. if (pid == 0) {
  1275. /* Show in pager in child */
  1276. dup2(pipefd[0], STDIN_FILENO);
  1277. close(pipefd[0]);
  1278. execlp("less", "less", NULL);
  1279. _exit(1);
  1280. }
  1281. /* In parent */
  1282. waitpid(pid, &tmp, 0);
  1283. close(pipefd[0]);
  1284. return NULL;
  1285. }
  1286. /*
  1287. * Follows the stat(1) output closely
  1288. */
  1289. static int
  1290. show_stats(char *fpath, char *fname, struct stat *sb)
  1291. {
  1292. char desc[DESCRIPTOR_LEN];
  1293. char *perms = get_lsperms(sb->st_mode, desc);
  1294. char *p, *begin = g_buf;
  1295. char tmp[] = "/tmp/nnnXXXXXX";
  1296. int fd = mkstemp(tmp);
  1297. if (fd == -1)
  1298. return -1;
  1299. dprintf(fd, " File: '%s'", unescape(fname, 0));
  1300. /* Show file name or 'symlink' -> 'target' */
  1301. if (perms[0] == 'l') {
  1302. /* Note that MAX_CMD_LEN > PATH_MAX */
  1303. ssize_t len = readlink(fpath, g_buf, MAX_CMD_LEN);
  1304. if (len != -1) {
  1305. g_buf[len] = '\0';
  1306. /*
  1307. * We pass g_buf but unescape() operates on g_buf too!
  1308. * Read the API notes for information on how this works.
  1309. */
  1310. dprintf(fd, " -> '%s'", unescape(g_buf, 0));
  1311. }
  1312. }
  1313. /* Show size, blocks, file type */
  1314. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1315. dprintf(fd, "\n Size: %-15lld Blocks: %-10lld IO Block: %-6d %s",
  1316. (long long)sb->st_size, (long long)sb->st_blocks, sb->st_blksize, desc);
  1317. #else
  1318. dprintf(fd, "\n Size: %-15ld Blocks: %-10ld IO Block: %-6ld %s",
  1319. sb->st_size, sb->st_blocks, (long)sb->st_blksize, desc);
  1320. #endif
  1321. /* Show containing device, inode, hardlink count */
  1322. #if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
  1323. sprintf(g_buf, "%xh/%ud", sb->st_dev, sb->st_dev);
  1324. dprintf(fd, "\n Device: %-15s Inode: %-11llu Links: %-9hu",
  1325. g_buf, (unsigned long long)sb->st_ino, sb->st_nlink);
  1326. #else
  1327. sprintf(g_buf, "%lxh/%lud", (ulong)sb->st_dev, (ulong)sb->st_dev);
  1328. dprintf(fd, "\n Device: %-15s Inode: %-11lu Links: %-9lu",
  1329. g_buf, sb->st_ino, (ulong)sb->st_nlink);
  1330. #endif
  1331. /* Show major, minor number for block or char device */
  1332. if (perms[0] == 'b' || perms[0] == 'c')
  1333. dprintf(fd, " Device type: %x,%x", major(sb->st_rdev), minor(sb->st_rdev));
  1334. /* Show permissions, owner, group */
  1335. 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,
  1336. sb->st_mode & 7, perms, sb->st_uid, (getpwuid(sb->st_uid))->pw_name, sb->st_gid, (getgrgid(sb->st_gid))->gr_name);
  1337. /* Show last access time */
  1338. strftime(g_buf, 40, STR_DATE, localtime(&sb->st_atime));
  1339. dprintf(fd, "\n\n Access: %s", g_buf);
  1340. /* Show last modification time */
  1341. strftime(g_buf, 40, STR_DATE, localtime(&sb->st_mtime));
  1342. dprintf(fd, "\n Modify: %s", g_buf);
  1343. /* Show last status change time */
  1344. strftime(g_buf, 40, STR_DATE, localtime(&sb->st_ctime));
  1345. dprintf(fd, "\n Change: %s", g_buf);
  1346. if (S_ISREG(sb->st_mode)) {
  1347. /* Show file(1) output */
  1348. p = get_output(g_buf, MAX_CMD_LEN, "file", "-b", fpath, 0);
  1349. if (p) {
  1350. dprintf(fd, "\n\n ");
  1351. while (*p) {
  1352. if (*p == ',') {
  1353. *p = '\0';
  1354. dprintf(fd, " %s\n", begin);
  1355. begin = p + 1;
  1356. }
  1357. ++p;
  1358. }
  1359. dprintf(fd, " %s", begin);
  1360. }
  1361. dprintf(fd, "\n\n");
  1362. } else
  1363. dprintf(fd, "\n\n\n");
  1364. close(fd);
  1365. exitcurses();
  1366. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1367. unlink(tmp);
  1368. initcurses();
  1369. return 0;
  1370. }
  1371. static size_t
  1372. get_fs_free(const char *path)
  1373. {
  1374. static struct statvfs svb;
  1375. if (statvfs(path, &svb) == -1)
  1376. return 0;
  1377. else
  1378. return svb.f_bavail << ffs(svb.f_frsize >> 1);
  1379. }
  1380. static size_t
  1381. get_fs_capacity(const char *path)
  1382. {
  1383. struct statvfs svb;
  1384. if (statvfs(path, &svb) == -1)
  1385. return 0;
  1386. else
  1387. return svb.f_blocks << ffs(svb.f_bsize >> 1);
  1388. }
  1389. static int
  1390. show_mediainfo(char *fpath, char *arg)
  1391. {
  1392. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[cfg.metaviewer], NULL, 0))
  1393. return -1;
  1394. exitcurses();
  1395. get_output(NULL, 0, utils[cfg.metaviewer], fpath, arg, 1);
  1396. initcurses();
  1397. return 0;
  1398. }
  1399. static int
  1400. handle_archive(char *fpath, char *arg, char *dir)
  1401. {
  1402. if (!get_output(g_buf, MAX_CMD_LEN, "which", utils[4], NULL, 0))
  1403. return -1;
  1404. if (arg[1] == 'x')
  1405. spawn(utils[4], arg, fpath, dir, F_NORMAL);
  1406. else {
  1407. exitcurses();
  1408. get_output(NULL, 0, utils[4], arg, fpath, 1);
  1409. initcurses();
  1410. }
  1411. return 0;
  1412. }
  1413. /*
  1414. * The help string tokens (each line) start with a HEX value
  1415. * which indicates the number of spaces to print before the
  1416. * particular token. This method was chosen instead of a flat
  1417. * string because the number of bytes in help was increasing
  1418. * the binary size by around a hundred bytes. This would only
  1419. * have increased as we keep adding new options.
  1420. */
  1421. static int
  1422. show_help(char *path)
  1423. {
  1424. char tmp[] = "/tmp/nnnXXXXXX";
  1425. int i = 0, fd = mkstemp(tmp);
  1426. char *start, *end;
  1427. static char helpstr[] = (
  1428. "cKey | Function\n"
  1429. "e- + -\n"
  1430. "7↑, k, ^P | Previous entry\n"
  1431. "7↓, j, ^N | Next entry\n"
  1432. "7PgUp, ^U | Scroll half page up\n"
  1433. "7PgDn, ^D | Scroll half page down\n"
  1434. "1Home, g, ^, ^A | First entry\n"
  1435. "2End, G, $, ^E | Last entry\n"
  1436. "4→, ↵, l, ^M | Open file or enter dir\n"
  1437. "1←, Bksp, h, ^H | Go to parent dir\n"
  1438. "d^O | Open with...\n"
  1439. "9Insert | Toggle navigate-as-you-type\n"
  1440. "e~ | Go HOME\n"
  1441. "e& | Go to initial dir\n"
  1442. "e- | Go to last visited dir\n"
  1443. "e/ | Filter dir contents\n"
  1444. "d^/ | Open desktop search tool\n"
  1445. "e. | Toggle hide . files\n"
  1446. "d^B | Bookmark prompt\n"
  1447. "eB | Pin current dir\n"
  1448. "d^V | Go to pinned dir\n"
  1449. "ec | Change dir prompt\n"
  1450. "ed | Toggle detail view\n"
  1451. "eD | File details\n"
  1452. "em | Brief media info\n"
  1453. "eM | Full media info\n"
  1454. "en | Create new\n"
  1455. "d^R | Rename entry\n"
  1456. "es | Toggle sort by size\n"
  1457. "eS | Toggle du mode\n"
  1458. "et | Toggle sort by mtime\n"
  1459. "e! | Spawn SHELL in dir\n"
  1460. "ee | Edit entry in EDITOR\n"
  1461. "eo | Open dir in file manager\n"
  1462. "ep | Open entry in PAGER\n"
  1463. "eF | List archive\n"
  1464. "d^X | Extract archive\n"
  1465. "d^K | Invoke file path copier\n"
  1466. "d^L | Redraw, clear prompt\n"
  1467. "e? | Help, settings\n"
  1468. "eQ | Quit and cd\n"
  1469. "aq, ^Q | Quit\n\n");
  1470. if (fd == -1)
  1471. return -1;
  1472. start = end = helpstr;
  1473. while (*end) {
  1474. while (*end != '\n')
  1475. ++end;
  1476. if (start == end) {
  1477. ++end;
  1478. continue;
  1479. }
  1480. dprintf(fd, "%*c%.*s", xchartohex(*start), ' ', (int)(end - start), start + 1);
  1481. start = ++end;
  1482. }
  1483. dprintf(fd, "\n");
  1484. if (getenv("NNN_BMS")) {
  1485. dprintf(fd, "BOOKMARKS\n");
  1486. for (; i < BM_MAX; ++i)
  1487. if (bookmark[i].key)
  1488. dprintf(fd, " %s: %s\n", bookmark[i].key, bookmark[i].loc);
  1489. else
  1490. break;
  1491. dprintf(fd, "\n");
  1492. }
  1493. if (editor)
  1494. dprintf(fd, "NNN_USE_EDITOR: %s\n", editor);
  1495. if (desktop_manager)
  1496. dprintf(fd, "NNN_DE_FILE_MANAGER: %s\n", desktop_manager);
  1497. if (idletimeout)
  1498. dprintf(fd, "NNN_IDLE_TIMEOUT: %d secs\n", idletimeout);
  1499. if (copier)
  1500. dprintf(fd, "NNN_COPIER: %s\n", copier);
  1501. dprintf(fd, "\nVolume: %s of ", coolsize(get_fs_free(path)));
  1502. dprintf(fd, "%s free\n", coolsize(get_fs_capacity(path)));
  1503. dprintf(fd, "\nVersion: %s\n%s\n", VERSION, GENERAL_INFO);
  1504. close(fd);
  1505. exitcurses();
  1506. get_output(NULL, 0, "cat", tmp, NULL, 1);
  1507. unlink(tmp);
  1508. initcurses();
  1509. return 0;
  1510. }
  1511. static int
  1512. sum_bsizes(const char *fpath, const struct stat *sb,
  1513. int typeflag, struct FTW *ftwbuf)
  1514. {
  1515. if (sb->st_blocks && (typeflag == FTW_F || typeflag == FTW_D))
  1516. ent_blocks += sb->st_blocks;
  1517. ++num_files;
  1518. return 0;
  1519. }
  1520. /*
  1521. * Wrapper to realloc()
  1522. * Frees current memory if realloc() fails and returns NULL.
  1523. *
  1524. * As per the docs, the *alloc() family is supposed to be memory aligned:
  1525. * Ubuntu: http://manpages.ubuntu.com/manpages/xenial/man3/malloc.3.html
  1526. * OS X: https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/malloc.3.html
  1527. */
  1528. static void *
  1529. xrealloc(void *pcur, size_t len)
  1530. {
  1531. static void *pmem;
  1532. pmem = realloc(pcur, len);
  1533. if (!pmem && pcur)
  1534. free(pcur);
  1535. return pmem;
  1536. }
  1537. static int
  1538. dentfill(char *path, struct entry **dents,
  1539. int (*filter)(regex_t *, char *), regex_t *re)
  1540. {
  1541. static DIR *dirp;
  1542. static struct dirent *dp;
  1543. static char *namep, *pnb;
  1544. static struct entry *dentp;
  1545. static size_t off, namebuflen = NAMEBUF_INCR;
  1546. static ulong num_saved;
  1547. static int fd, n, count;
  1548. static struct stat sb_path, sb;
  1549. off = 0;
  1550. dirp = opendir(path);
  1551. if (dirp == NULL)
  1552. return 0;
  1553. fd = dirfd(dirp);
  1554. n = 0;
  1555. if (cfg.blkorder) {
  1556. num_files = 0;
  1557. dir_blocks = 0;
  1558. if (fstatat(fd, ".", &sb_path, 0) == -1) {
  1559. printwarn();
  1560. return 0;
  1561. }
  1562. }
  1563. while ((dp = readdir(dirp)) != NULL) {
  1564. namep = dp->d_name;
  1565. if (filter(re, namep) == 0) {
  1566. if (!cfg.blkorder)
  1567. continue;
  1568. /* Skip self and parent */
  1569. if ((namep[0] == '.' && (namep[1] == '\0' || (namep[1] == '.' && namep[2] == '\0'))))
  1570. continue;
  1571. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1)
  1572. continue;
  1573. if (S_ISDIR(sb.st_mode)) {
  1574. if (sb_path.st_dev == sb.st_dev) {
  1575. ent_blocks = 0;
  1576. mkpath(path, namep, g_buf, PATH_MAX);
  1577. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1578. printmsg(STR_NFTWFAIL);
  1579. dir_blocks += sb.st_blocks;
  1580. } else
  1581. dir_blocks += ent_blocks;
  1582. }
  1583. } else {
  1584. if (sb.st_blocks)
  1585. dir_blocks += sb.st_blocks;
  1586. ++num_files;
  1587. }
  1588. continue;
  1589. }
  1590. /* Skip self and parent */
  1591. if ((namep[0] == '.' && (namep[1] == '\0' ||
  1592. (namep[1] == '.' && namep[2] == '\0'))))
  1593. continue;
  1594. if (fstatat(fd, namep, &sb, AT_SYMLINK_NOFOLLOW) == -1) {
  1595. DPRINTF_S(namep);
  1596. continue;
  1597. }
  1598. if (n == total_dents) {
  1599. total_dents += ENTRY_INCR;
  1600. *dents = xrealloc(*dents, total_dents * sizeof(**dents));
  1601. if (*dents == NULL) {
  1602. if (pnamebuf)
  1603. free(pnamebuf);
  1604. errexit();
  1605. }
  1606. DPRINTF_P(*dents);
  1607. }
  1608. /* If there's not enough bytes left to copy a file name of length NAME_MAX, re-allocate */
  1609. if (namebuflen - off < NAME_MAX + 1) {
  1610. namebuflen += NAMEBUF_INCR;
  1611. pnb = pnamebuf;
  1612. pnamebuf = (char *)xrealloc(pnamebuf, namebuflen);
  1613. if (pnamebuf == NULL) {
  1614. free(*dents);
  1615. errexit();
  1616. }
  1617. DPRINTF_P(pnamebuf);
  1618. /* realloc() may result in memory move, we must re-adjust if that happens */
  1619. if (pnb != pnamebuf) {
  1620. dentp = *dents;
  1621. dentp->name = pnamebuf;
  1622. for (count = 1; count < n; ++dentp, ++count)
  1623. /* Current filename starts at last filename start + length */
  1624. (dentp + 1)->name = (char *)((size_t)dentp->name + dentp->nlen);
  1625. }
  1626. }
  1627. dentp = *dents + n;
  1628. /* Copy file name */
  1629. dentp->name = (char *)((size_t)pnamebuf + off);
  1630. dentp->nlen = xstrlcpy(dentp->name, namep, NAME_MAX + 1);
  1631. off += dentp->nlen;
  1632. /* Copy other fields */
  1633. dentp->mode = sb.st_mode;
  1634. dentp->t = sb.st_mtime;
  1635. dentp->size = sb.st_size;
  1636. if (cfg.blkorder) {
  1637. if (S_ISDIR(sb.st_mode)) {
  1638. ent_blocks = 0;
  1639. num_saved = num_files + 1;
  1640. mkpath(path, namep, g_buf, PATH_MAX);
  1641. if (nftw(g_buf, sum_bsizes, open_max, FTW_MOUNT | FTW_PHYS) == -1) {
  1642. printmsg(STR_NFTWFAIL);
  1643. dentp->blocks = sb.st_blocks;
  1644. } else
  1645. dentp->blocks = ent_blocks;
  1646. if (sb_path.st_dev == sb.st_dev)
  1647. dir_blocks += dentp->blocks;
  1648. else
  1649. num_files = num_saved;
  1650. } else {
  1651. dentp->blocks = sb.st_blocks;
  1652. dir_blocks += dentp->blocks;
  1653. ++num_files;
  1654. }
  1655. }
  1656. ++n;
  1657. }
  1658. /* Should never be null */
  1659. if (closedir(dirp) == -1) {
  1660. if (*dents) {
  1661. free(pnamebuf);
  1662. free(*dents);
  1663. }
  1664. errexit();
  1665. }
  1666. return n;
  1667. }
  1668. static void
  1669. dentfree(struct entry *dents)
  1670. {
  1671. free(pnamebuf);
  1672. free(dents);
  1673. }
  1674. /* Return the position of the matching entry or 0 otherwise */
  1675. static int
  1676. dentfind(struct entry *dents, const char *fname, int n)
  1677. {
  1678. static int i;
  1679. if (!fname)
  1680. return 0;
  1681. DPRINTF_S(fname);
  1682. for (i = 0; i < n; ++i)
  1683. if (xstrcmp(fname, dents[i].name) == 0)
  1684. return i;
  1685. return 0;
  1686. }
  1687. static int
  1688. populate(char *path, char *oldname, char *fltr)
  1689. {
  1690. static regex_t re;
  1691. /* Can fail when permissions change while browsing.
  1692. * It's assumed that path IS a directory when we are here.
  1693. */
  1694. if (access(path, R_OK) == -1)
  1695. return -1;
  1696. /* Search filter */
  1697. if (setfilter(&re, fltr) != 0)
  1698. return -1;
  1699. if (cfg.blkorder) {
  1700. printmsg("Calculating...");
  1701. refresh();
  1702. }
  1703. #ifdef DEBUGMODE
  1704. struct timespec ts1, ts2;
  1705. clock_gettime(CLOCK_REALTIME, &ts1); /* Use CLOCK_MONOTONIC on FreeBSD */
  1706. #endif
  1707. ndents = dentfill(path, &dents, visible, &re);
  1708. qsort(dents, ndents, sizeof(*dents), entrycmp);
  1709. #ifdef DEBUGMODE
  1710. clock_gettime(CLOCK_REALTIME, &ts2);
  1711. DPRINTF_U(ts2.tv_nsec - ts1.tv_nsec);
  1712. #endif
  1713. /* Find cur from history */
  1714. cur = dentfind(dents, oldname, ndents);
  1715. regfree(&re);
  1716. return 0;
  1717. }
  1718. static void
  1719. redraw(char *path)
  1720. {
  1721. static char buf[(NAME_MAX + 1) << 1] __attribute__ ((aligned));
  1722. static size_t ncols;
  1723. static int nlines, i;
  1724. static bool mode_changed;
  1725. mode_changed = FALSE;
  1726. nlines = MIN(LINES - 4, ndents);
  1727. /* Clean screen */
  1728. erase();
  1729. /* Fail redraw if < than 10 columns */
  1730. if (COLS < 10) {
  1731. printmsg("Too few columns!");
  1732. return;
  1733. }
  1734. /* Strip trailing slashes */
  1735. for (i = xstrlen(path) - 1; i > 0; --i)
  1736. if (path[i] == '/')
  1737. path[i] = '\0';
  1738. else
  1739. break;
  1740. DPRINTF_D(cur);
  1741. DPRINTF_S(path);
  1742. if (!realpath(path, g_buf)) {
  1743. printwarn();
  1744. return;
  1745. }
  1746. ncols = COLS;
  1747. if (ncols > PATH_MAX)
  1748. ncols = PATH_MAX;
  1749. /* No text wrapping in cwd line */
  1750. /* Show CWD: - xstrlen(CWD) - 1 = 6 */
  1751. g_buf[ncols - 6] = '\0';
  1752. printw(CWD "%s\n\n", g_buf);
  1753. /* Fallback to light mode if less than 35 columns */
  1754. if (ncols < 35 && cfg.showdetail) {
  1755. cfg.showdetail ^= 1;
  1756. printptr = &printent;
  1757. mode_changed = TRUE;
  1758. }
  1759. /* Calculate the number of cols available to print entry name */
  1760. if (cfg.showdetail)
  1761. ncols -= 32;
  1762. else
  1763. ncols -= 5;
  1764. if (cfg.showcolor) {
  1765. attron(COLOR_PAIR(1) | A_BOLD);
  1766. cfg.dircolor = 1;
  1767. }
  1768. /* Print listing */
  1769. if (cur < (nlines >> 1)) {
  1770. for (i = 0; i < nlines; ++i)
  1771. printptr(&dents[i], i == cur, ncols);
  1772. } else if (cur >= ndents - (nlines >> 1)) {
  1773. for (i = ndents - nlines; i < ndents; ++i)
  1774. printptr(&dents[i], i == cur, ncols);
  1775. } else {
  1776. static int odd;
  1777. odd = ISODD(nlines);
  1778. nlines >>= 1;
  1779. for (i = cur - nlines; i < cur + nlines + odd; ++i)
  1780. printptr(&dents[i], i == cur, ncols);
  1781. }
  1782. /* Must reset e.g. no files in dir */
  1783. if (cfg.dircolor) {
  1784. attroff(COLOR_PAIR(1) | A_BOLD);
  1785. cfg.dircolor = 0;
  1786. }
  1787. if (cfg.showdetail) {
  1788. if (ndents) {
  1789. static char sort[9];
  1790. if (cfg.mtimeorder)
  1791. xstrlcpy(sort, "by time ", 9);
  1792. else if (cfg.sizeorder)
  1793. xstrlcpy(sort, "by size ", 9);
  1794. else
  1795. sort[0] = '\0';
  1796. /* We need to show filename as it may be truncated in directory listing */
  1797. if (!cfg.blkorder)
  1798. sprintf(buf, "%d/%d %s[%s%s]", cur + 1, ndents, sort, unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  1799. else {
  1800. i = sprintf(buf, "%d/%d du: %s (%lu files) ", cur + 1, ndents, coolsize(dir_blocks << 9), num_files);
  1801. sprintf(buf + i, "vol: %s free [%s%s]",
  1802. coolsize(get_fs_free(path)), unescape(dents[cur].name, 0), get_file_sym(dents[cur].mode));
  1803. }
  1804. printmsg(buf);
  1805. } else
  1806. printmsg("0 items");
  1807. }
  1808. if (mode_changed) {
  1809. cfg.showdetail ^= 1;
  1810. printptr = &printent_long;
  1811. }
  1812. }
  1813. static void
  1814. browse(char *ipath, char *ifilter)
  1815. {
  1816. static char path[PATH_MAX] __attribute__ ((aligned));
  1817. static char newpath[PATH_MAX] __attribute__ ((aligned));
  1818. static char lastdir[PATH_MAX] __attribute__ ((aligned));
  1819. static char mark[PATH_MAX] __attribute__ ((aligned));
  1820. static char fltr[NAME_MAX + 1] __attribute__ ((aligned));
  1821. static char oldname[NAME_MAX + 1] __attribute__ ((aligned));
  1822. char *dir, *tmp, *run = NULL, *env = NULL;
  1823. struct stat sb;
  1824. int r, fd, presel;
  1825. enum action sel = SEL_RUNARG + 1;
  1826. bool dir_changed = FALSE;
  1827. xstrlcpy(path, ipath, PATH_MAX);
  1828. copyfilter();
  1829. oldname[0] = newpath[0] = lastdir[0] = mark[0] = '\0';
  1830. if (cfg.filtermode)
  1831. presel = FILTER;
  1832. else
  1833. presel = 0;
  1834. dents = xrealloc(dents, total_dents * sizeof(struct entry));
  1835. if (dents == NULL)
  1836. errexit();
  1837. DPRINTF_P(dents);
  1838. /* Allocate buffer to hold names */
  1839. pnamebuf = (char *)xrealloc(pnamebuf, NAMEBUF_INCR);
  1840. if (pnamebuf == NULL) {
  1841. free(dents);
  1842. errexit();
  1843. }
  1844. DPRINTF_P(pnamebuf);
  1845. begin:
  1846. #ifdef LINUX_INOTIFY
  1847. if (dir_changed && inotify_wd >= 0) {
  1848. inotify_rm_watch(inotify_fd, inotify_wd);
  1849. inotify_wd = -1;
  1850. dir_changed = FALSE;
  1851. }
  1852. #elif defined(BSD_KQUEUE)
  1853. if (dir_changed && event_fd >= 0) {
  1854. close(event_fd);
  1855. event_fd = -1;
  1856. dir_changed = FALSE;
  1857. }
  1858. #endif
  1859. if (populate(path, oldname, fltr) == -1) {
  1860. printwarn();
  1861. goto nochange;
  1862. }
  1863. #ifdef LINUX_INOTIFY
  1864. if (inotify_wd == -1)
  1865. inotify_wd = inotify_add_watch(inotify_fd, path, INOTIFY_MASK);
  1866. #elif defined(BSD_KQUEUE)
  1867. if (event_fd == -1) {
  1868. #if defined(O_EVTONLY)
  1869. event_fd = open(path, O_EVTONLY);
  1870. #else
  1871. event_fd = open(path, O_RDONLY);
  1872. #endif
  1873. if (event_fd >= 0)
  1874. EV_SET(&events_to_monitor[0], event_fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, KQUEUE_FFLAGS, 0, path);
  1875. }
  1876. #endif
  1877. for (;;) {
  1878. redraw(path);
  1879. nochange:
  1880. /* Exit if parent has exited */
  1881. if (getppid() == 1)
  1882. _exit(0);
  1883. sel = nextsel(&run, &env, &presel);
  1884. switch (sel) {
  1885. case SEL_BACK:
  1886. /* There is no going back */
  1887. if (istopdir(path)) {
  1888. printmsg(STR_ATROOT);
  1889. goto nochange;
  1890. }
  1891. dir = xdirname(path);
  1892. if (access(dir, R_OK) == -1) {
  1893. printwarn();
  1894. goto nochange;
  1895. }
  1896. /* Save history */
  1897. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  1898. /* Save last working directory */
  1899. xstrlcpy(lastdir, path, PATH_MAX);
  1900. dir_changed = TRUE;
  1901. xstrlcpy(path, dir, PATH_MAX);
  1902. /* Reset filter */
  1903. copyfilter();
  1904. if (cfg.filtermode)
  1905. presel = FILTER;
  1906. goto begin;
  1907. case SEL_GOIN:
  1908. /* Cannot descend in empty directories */
  1909. if (ndents == 0)
  1910. goto begin;
  1911. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  1912. DPRINTF_S(newpath);
  1913. /* Get path info */
  1914. fd = open(newpath, O_RDONLY | O_NONBLOCK);
  1915. if (fd == -1) {
  1916. printwarn();
  1917. goto nochange;
  1918. }
  1919. if (fstat(fd, &sb) == -1) {
  1920. printwarn();
  1921. close(fd);
  1922. goto nochange;
  1923. }
  1924. close(fd);
  1925. DPRINTF_U(sb.st_mode);
  1926. switch (sb.st_mode & S_IFMT) {
  1927. case S_IFDIR:
  1928. if (access(newpath, R_OK) == -1) {
  1929. printwarn();
  1930. goto nochange;
  1931. }
  1932. /* Save last working directory */
  1933. xstrlcpy(lastdir, path, PATH_MAX);
  1934. dir_changed = TRUE;
  1935. xstrlcpy(path, newpath, PATH_MAX);
  1936. oldname[0] = '\0';
  1937. /* Reset filter */
  1938. copyfilter();
  1939. if (cfg.filtermode)
  1940. presel = FILTER;
  1941. goto begin;
  1942. case S_IFREG:
  1943. {
  1944. /* If NNN_USE_EDITOR is set,
  1945. * open text in EDITOR
  1946. */
  1947. if (editor) {
  1948. if (getmime(dents[cur].name)) {
  1949. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1950. continue;
  1951. }
  1952. /* Recognize and open plain
  1953. * text files with vi
  1954. */
  1955. if (get_output(g_buf, MAX_CMD_LEN, "file", "-bi", newpath, 0) == NULL)
  1956. continue;
  1957. if (strstr(g_buf, "text/") == g_buf) {
  1958. spawn(editor, newpath, NULL, NULL, F_NORMAL);
  1959. continue;
  1960. }
  1961. }
  1962. /* Invoke desktop opener as last resort */
  1963. spawn(utils[2], newpath, NULL, NULL, nowait);
  1964. continue;
  1965. }
  1966. default:
  1967. printmsg("Unsupported file");
  1968. goto nochange;
  1969. }
  1970. case SEL_NEXT:
  1971. if (cur < ndents - 1)
  1972. ++cur;
  1973. else if (ndents)
  1974. /* Roll over, set cursor to first entry */
  1975. cur = 0;
  1976. break;
  1977. case SEL_PREV:
  1978. if (cur > 0)
  1979. --cur;
  1980. else if (ndents)
  1981. /* Roll over, set cursor to last entry */
  1982. cur = ndents - 1;
  1983. break;
  1984. case SEL_PGDN:
  1985. if (cur < ndents - 1)
  1986. cur += MIN((LINES - 4) / 2, ndents - 1 - cur);
  1987. break;
  1988. case SEL_PGUP:
  1989. if (cur > 0)
  1990. cur -= MIN((LINES - 4) / 2, cur);
  1991. break;
  1992. case SEL_HOME:
  1993. cur = 0;
  1994. break;
  1995. case SEL_END:
  1996. cur = ndents - 1;
  1997. break;
  1998. case SEL_CD:
  1999. {
  2000. char *input;
  2001. int truecd;
  2002. /* Save the program start dir */
  2003. tmp = getcwd(newpath, PATH_MAX);
  2004. if (tmp == NULL) {
  2005. printwarn();
  2006. goto nochange;
  2007. }
  2008. /* Switch to current path for readline(3) */
  2009. if (chdir(path) == -1) {
  2010. printwarn();
  2011. goto nochange;
  2012. }
  2013. exitcurses();
  2014. tmp = readline("chdir: ");
  2015. initcurses();
  2016. /* Change back to program start dir */
  2017. if (chdir(newpath) == -1)
  2018. printwarn();
  2019. if (tmp[0] == '\0')
  2020. break;
  2021. /* Add to readline(3) history */
  2022. add_history(tmp);
  2023. input = tmp;
  2024. tmp = strstrip(tmp);
  2025. if (tmp[0] == '\0') {
  2026. free(input);
  2027. break;
  2028. }
  2029. truecd = 0;
  2030. if (tmp[0] == '~') {
  2031. /* Expand ~ to HOME absolute path */
  2032. char *home = getenv("HOME");
  2033. if (home)
  2034. snprintf(newpath, PATH_MAX, "%s%s", home, tmp + 1);
  2035. else {
  2036. free(input);
  2037. printmsg(STR_NOHOME);
  2038. goto nochange;
  2039. }
  2040. } else if (tmp[0] == '-' && tmp[1] == '\0') {
  2041. if (lastdir[0] == '\0') {
  2042. free(input);
  2043. break;
  2044. }
  2045. /* Switch to last visited dir */
  2046. xstrlcpy(newpath, lastdir, PATH_MAX);
  2047. truecd = 1;
  2048. } else if ((r = all_dots(tmp))) {
  2049. if (r == 1) {
  2050. /* Always in the current dir */
  2051. free(input);
  2052. break;
  2053. }
  2054. /* Show a message if already at / */
  2055. if (istopdir(path)) {
  2056. printmsg(STR_ATROOT);
  2057. free(input);
  2058. goto nochange;
  2059. }
  2060. --r; /* One . for the current dir */
  2061. dir = path;
  2062. /* Note: fd is used as a tmp variable here */
  2063. for (fd = 0; fd < r; ++fd) {
  2064. /* Reached / ? */
  2065. if (istopdir(path)) {
  2066. /* Can't cd beyond / */
  2067. break;
  2068. }
  2069. dir = xdirname(dir);
  2070. if (access(dir, R_OK) == -1) {
  2071. printwarn();
  2072. free(input);
  2073. goto nochange;
  2074. }
  2075. }
  2076. truecd = 1;
  2077. /* Save the path in case of cd ..
  2078. * We mark the current dir in parent dir
  2079. */
  2080. if (r == 1) {
  2081. xstrlcpy(oldname, xbasename(path), NAME_MAX + 1);
  2082. truecd = 2;
  2083. }
  2084. xstrlcpy(newpath, dir, PATH_MAX);
  2085. } else
  2086. mkpath(path, tmp, newpath, PATH_MAX);
  2087. free(input);
  2088. if (!xdiraccess(newpath))
  2089. goto nochange;
  2090. if (truecd == 0) {
  2091. /* Probable change in dir */
  2092. /* No-op if it's the same directory */
  2093. if (xstrcmp(path, newpath) == 0)
  2094. break;
  2095. oldname[0] = '\0';
  2096. } else if (truecd == 1)
  2097. /* Sure change in dir */
  2098. oldname[0] = '\0';
  2099. /* Save last working directory */
  2100. xstrlcpy(lastdir, path, PATH_MAX);
  2101. dir_changed = TRUE;
  2102. /* Save the newly opted dir in path */
  2103. xstrlcpy(path, newpath, PATH_MAX);
  2104. /* Reset filter */
  2105. copyfilter();
  2106. DPRINTF_S(path);
  2107. if (cfg.filtermode)
  2108. presel = FILTER;
  2109. goto begin;
  2110. }
  2111. case SEL_CDHOME:
  2112. dir = getenv("HOME");
  2113. if (dir == NULL) {
  2114. clearprompt();
  2115. goto nochange;
  2116. } // fallthrough
  2117. case SEL_CDBEGIN:
  2118. if (sel == SEL_CDBEGIN)
  2119. dir = ipath;
  2120. if (!xdiraccess(dir)) {
  2121. goto nochange;
  2122. }
  2123. if (xstrcmp(path, dir) == 0) {
  2124. break;
  2125. }
  2126. /* Save last working directory */
  2127. xstrlcpy(lastdir, path, PATH_MAX);
  2128. dir_changed = TRUE;
  2129. xstrlcpy(path, dir, PATH_MAX);
  2130. oldname[0] = '\0';
  2131. /* Reset filter */
  2132. copyfilter();
  2133. DPRINTF_S(path);
  2134. if (cfg.filtermode)
  2135. presel = FILTER;
  2136. goto begin;
  2137. case SEL_CDLAST: // fallthrough
  2138. case SEL_VISIT:
  2139. if (sel == SEL_VISIT) {
  2140. if (xstrcmp(mark, path) == 0)
  2141. break;
  2142. tmp = mark;
  2143. } else
  2144. tmp = lastdir;
  2145. if (tmp[0] == '\0') {
  2146. printmsg("Not set...");
  2147. goto nochange;
  2148. }
  2149. if (!xdiraccess(tmp))
  2150. goto nochange;
  2151. xstrlcpy(newpath, tmp, PATH_MAX);
  2152. xstrlcpy(lastdir, path, PATH_MAX);
  2153. dir_changed = TRUE;
  2154. xstrlcpy(path, newpath, PATH_MAX);
  2155. oldname[0] = '\0';
  2156. /* Reset filter */
  2157. copyfilter();
  2158. DPRINTF_S(path);
  2159. if (cfg.filtermode)
  2160. presel = FILTER;
  2161. goto begin;
  2162. case SEL_CDBM:
  2163. printprompt("key: ");
  2164. tmp = readinput();
  2165. clearprompt();
  2166. if (tmp == NULL)
  2167. break;
  2168. if (get_bm_loc(tmp, newpath) == NULL) {
  2169. printmsg(STR_INVBM);
  2170. goto nochange;
  2171. }
  2172. if (!xdiraccess(newpath))
  2173. goto nochange;
  2174. if (xstrcmp(path, newpath) == 0)
  2175. break;
  2176. oldname[0] = '\0';
  2177. /* Save last working directory */
  2178. xstrlcpy(lastdir, path, PATH_MAX);
  2179. dir_changed = TRUE;
  2180. /* Save the newly opted dir in path */
  2181. xstrlcpy(path, newpath, PATH_MAX);
  2182. /* Reset filter */
  2183. copyfilter();
  2184. DPRINTF_S(path);
  2185. if (cfg.filtermode)
  2186. presel = FILTER;
  2187. goto begin;
  2188. case SEL_PIN:
  2189. xstrlcpy(mark, path, PATH_MAX);
  2190. printmsg(mark);
  2191. goto nochange;
  2192. case SEL_FLTR:
  2193. presel = filterentries(path);
  2194. copyfilter();
  2195. DPRINTF_S(fltr);
  2196. /* Save current */
  2197. if (ndents > 0)
  2198. copycurname();
  2199. goto nochange;
  2200. case SEL_MFLTR:
  2201. cfg.filtermode ^= 1;
  2202. if (cfg.filtermode)
  2203. presel = FILTER;
  2204. else
  2205. printmsg("navigate-as-you-type off");
  2206. goto nochange;
  2207. case SEL_SEARCH:
  2208. spawn(player, path, "search", NULL, F_NORMAL);
  2209. break;
  2210. case SEL_TOGGLEDOT:
  2211. cfg.showhidden ^= 1;
  2212. initfilter(cfg.showhidden, &ifilter);
  2213. copyfilter();
  2214. goto begin;
  2215. case SEL_DETAIL:
  2216. cfg.showdetail ^= 1;
  2217. cfg.showdetail ? (printptr = &printent_long) : (printptr = &printent);
  2218. /* Save current */
  2219. if (ndents > 0)
  2220. copycurname();
  2221. goto begin;
  2222. case SEL_STATS:
  2223. if (ndents > 0) {
  2224. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2225. if (lstat(newpath, &sb) == -1) {
  2226. if (dents)
  2227. dentfree(dents);
  2228. errexit();
  2229. } else {
  2230. if (show_stats(newpath, dents[cur].name, &sb) < 0) {
  2231. printwarn();
  2232. goto nochange;
  2233. }
  2234. }
  2235. }
  2236. break;
  2237. case SEL_LIST: // fallthrough
  2238. case SEL_EXTRACT: // fallthrough
  2239. case SEL_MEDIA: // fallthrough
  2240. case SEL_FMEDIA:
  2241. if (ndents > 0) {
  2242. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2243. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2244. r = show_mediainfo(newpath, run);
  2245. else
  2246. r = handle_archive(newpath, run, path);
  2247. if (r == -1) {
  2248. xstrlcpy(newpath, "missing ", PATH_MAX);
  2249. if (sel == SEL_MEDIA || sel == SEL_FMEDIA)
  2250. xstrlcpy(newpath + 8, utils[cfg.metaviewer], 32);
  2251. else
  2252. xstrlcpy(newpath + 8, utils[4], 32);
  2253. printmsg(newpath);
  2254. goto nochange;
  2255. }
  2256. }
  2257. break;
  2258. case SEL_DFB:
  2259. if (!desktop_manager) {
  2260. printmsg("NNN_DE_FILE_MANAGER not set");
  2261. goto nochange;
  2262. }
  2263. spawn(desktop_manager, path, NULL, path, F_NOTRACE | F_NOWAIT);
  2264. break;
  2265. case SEL_FSIZE:
  2266. cfg.sizeorder ^= 1;
  2267. cfg.mtimeorder = 0;
  2268. cfg.blkorder = 0;
  2269. /* Save current */
  2270. if (ndents > 0)
  2271. copycurname();
  2272. goto begin;
  2273. case SEL_BSIZE:
  2274. cfg.blkorder ^= 1;
  2275. if (cfg.blkorder) {
  2276. cfg.showdetail = 1;
  2277. printptr = &printent_long;
  2278. }
  2279. cfg.mtimeorder = 0;
  2280. cfg.sizeorder = 0;
  2281. /* Save current */
  2282. if (ndents > 0)
  2283. copycurname();
  2284. goto begin;
  2285. case SEL_MTIME:
  2286. cfg.mtimeorder ^= 1;
  2287. cfg.sizeorder = 0;
  2288. cfg.blkorder = 0;
  2289. /* Save current */
  2290. if (ndents > 0)
  2291. copycurname();
  2292. goto begin;
  2293. case SEL_REDRAW:
  2294. /* Save current */
  2295. if (ndents > 0)
  2296. copycurname();
  2297. goto begin;
  2298. case SEL_COPY:
  2299. if (copier && ndents) {
  2300. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2301. spawn(copier, newpath, NULL, NULL, F_NONE);
  2302. printmsg(newpath);
  2303. } else if (!copier)
  2304. printmsg("NNN_COPIER is not set");
  2305. goto nochange;
  2306. case SEL_OPEN:
  2307. printprompt("open with: "); // fallthrough
  2308. case SEL_NEW:
  2309. if (sel == SEL_NEW)
  2310. printprompt("name: ");
  2311. tmp = xreadline(NULL);
  2312. clearprompt();
  2313. if (tmp == NULL || tmp[0] == '\0')
  2314. break;
  2315. /* Allow only relative, same dir paths */
  2316. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2317. printmsg(STR_INPUT);
  2318. goto nochange;
  2319. }
  2320. if (sel == SEL_OPEN) {
  2321. printprompt("Press 'c' for cli mode");
  2322. cleartimeout();
  2323. r = getch();
  2324. settimeout();
  2325. if (r == 'c')
  2326. r = F_NORMAL;
  2327. else
  2328. r = F_NOWAIT;
  2329. mkpath(path, dents[cur].name, newpath, PATH_MAX);
  2330. spawn(tmp, newpath, NULL, path, r);
  2331. continue;
  2332. }
  2333. /* Open the descriptor to currently open directory */
  2334. fd = open(path, O_RDONLY | O_DIRECTORY);
  2335. if (fd == -1) {
  2336. printwarn();
  2337. goto nochange;
  2338. }
  2339. /* Check if another file with same name exists */
  2340. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2341. printmsg("Entry exists");
  2342. goto nochange;
  2343. }
  2344. /* Check if it's a dir or file */
  2345. printprompt("Press 'f' for file or 'd' for dir");
  2346. cleartimeout();
  2347. r = getch();
  2348. settimeout();
  2349. if (r == 'f') {
  2350. r = openat(fd, tmp, O_CREAT, 0666);
  2351. close(r);
  2352. } else if (r == 'd')
  2353. r = mkdirat(fd, tmp, 0777);
  2354. else {
  2355. close(fd);
  2356. break;
  2357. }
  2358. if (r == -1) {
  2359. printwarn();
  2360. close(fd);
  2361. goto nochange;
  2362. }
  2363. close(fd);
  2364. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2365. goto begin;
  2366. case SEL_RENAME:
  2367. if (ndents <= 0)
  2368. break;
  2369. printprompt("");
  2370. tmp = xreadline(dents[cur].name);
  2371. clearprompt();
  2372. if (tmp == NULL || tmp[0] == '\0')
  2373. break;
  2374. /* Allow only relative, same dir paths */
  2375. if (tmp[0] == '/' || xstrcmp(xbasename(tmp), tmp) != 0) {
  2376. printmsg(STR_INPUT);
  2377. goto nochange;
  2378. }
  2379. /* Skip renaming to same name */
  2380. if (xstrcmp(tmp, dents[cur].name) == 0)
  2381. break;
  2382. /* Open the descriptor to currently open directory */
  2383. fd = open(path, O_RDONLY | O_DIRECTORY);
  2384. if (fd == -1) {
  2385. printwarn();
  2386. goto nochange;
  2387. }
  2388. /* Check if another file with same name exists */
  2389. if (faccessat(fd, tmp, F_OK, AT_SYMLINK_NOFOLLOW) != -1) {
  2390. /* File with the same name exists */
  2391. printprompt("Press 'y' to overwrite");
  2392. cleartimeout();
  2393. r = getch();
  2394. settimeout();
  2395. if (r != 'y') {
  2396. close(fd);
  2397. break;
  2398. }
  2399. }
  2400. /* Rename the file */
  2401. if (renameat(fd, dents[cur].name, fd, tmp) != 0) {
  2402. printwarn();
  2403. close(fd);
  2404. goto nochange;
  2405. }
  2406. close(fd);
  2407. xstrlcpy(oldname, tmp, NAME_MAX + 1);
  2408. goto begin;
  2409. case SEL_HELP:
  2410. show_help(path);
  2411. break;
  2412. case SEL_RUN:
  2413. run = xgetenv(env, run);
  2414. spawn(run, NULL, NULL, path, F_NORMAL | F_MARKER);
  2415. /* Repopulate as directory content may have changed */
  2416. goto begin;
  2417. case SEL_RUNARG:
  2418. run = xgetenv(env, run);
  2419. spawn(run, dents[cur].name, NULL, path, F_NORMAL);
  2420. break;
  2421. case SEL_CDQUIT:
  2422. {
  2423. char *tmpfile = "/tmp/nnn";
  2424. tmp = getenv("NNN_TMPFILE");
  2425. if (tmp)
  2426. tmpfile = tmp;
  2427. FILE *fp = fopen(tmpfile, "w");
  2428. if (fp) {
  2429. fprintf(fp, "cd \"%s\"", path);
  2430. fclose(fp);
  2431. }
  2432. /* Fall through to exit */
  2433. } // fallthrough
  2434. case SEL_QUIT:
  2435. dentfree(dents);
  2436. return;
  2437. }
  2438. /* Screensaver */
  2439. if (idletimeout != 0 && idle == idletimeout) {
  2440. idle = 0;
  2441. spawn(player, "", "screensaver", NULL, F_NORMAL | F_SIGINT);
  2442. }
  2443. }
  2444. }
  2445. static void
  2446. usage(void)
  2447. {
  2448. printf("usage: nnn [-b key] [-c N] [-e] [-i] [-l]\n\
  2449. [-p nlay] [-S] [-v] [-h] [PATH]\n\n\
  2450. The missing terminal file browser for X.\n\n\
  2451. positional arguments:\n\
  2452. PATH start dir [default: current dir]\n\n\
  2453. optional arguments:\n\
  2454. -b key specify bookmark key to open\n\
  2455. -c N specify dir color, disables if N>7\n\
  2456. -e use exiftool instead of mediainfo\n\
  2457. -i start in navigate-as-you-type mode\n\
  2458. -l start in light mode (fewer details)\n\
  2459. -p nlay path to custom nlay\n\
  2460. -S start in disk usage analyzer mode\n\
  2461. -v show program version and exit\n\
  2462. -h show this help and exit\n\n\
  2463. Version: %s\n%s\n", VERSION, GENERAL_INFO);
  2464. exit(0);
  2465. }
  2466. int
  2467. main(int argc, char *argv[])
  2468. {
  2469. static char cwd[PATH_MAX] __attribute__ ((aligned));
  2470. char *ipath = NULL, *ifilter, *bmstr;
  2471. int opt;
  2472. /* Confirm we are in a terminal */
  2473. if (!isatty(0) || !isatty(1)) {
  2474. fprintf(stderr, "stdin or stdout is not a tty\n");
  2475. exit(1);
  2476. }
  2477. while ((opt = getopt(argc, argv, "Slib:c:ep:vh")) != -1) {
  2478. switch (opt) {
  2479. case 'S':
  2480. cfg.blkorder = 1;
  2481. break;
  2482. case 'l':
  2483. cfg.showdetail = 0;
  2484. printptr = &printent;
  2485. break;
  2486. case 'i':
  2487. cfg.filtermode = 1;
  2488. break;
  2489. case 'b':
  2490. ipath = optarg;
  2491. break;
  2492. case 'c':
  2493. if (atoi(optarg) > 7)
  2494. cfg.showcolor = 0;
  2495. else
  2496. cfg.color = (uchar)atoi(optarg);
  2497. break;
  2498. case 'e':
  2499. cfg.metaviewer = 1;
  2500. break;
  2501. case 'p':
  2502. player = optarg;
  2503. break;
  2504. case 'v':
  2505. printf("%s\n", VERSION);
  2506. return 0;
  2507. case 'h': // fallthrough
  2508. default:
  2509. usage();
  2510. }
  2511. }
  2512. /* Parse bookmarks string, if available */
  2513. bmstr = getenv("NNN_BMS");
  2514. if (bmstr)
  2515. parsebmstr(bmstr);
  2516. if (ipath) { /* Open a bookmark directly */
  2517. if (get_bm_loc(ipath, cwd) == NULL) {
  2518. fprintf(stderr, "%s\n", STR_INVBM);
  2519. exit(1);
  2520. }
  2521. ipath = cwd;
  2522. } else if (argc == optind) {
  2523. /* Start in the current directory */
  2524. ipath = getcwd(cwd, PATH_MAX);
  2525. if (ipath == NULL)
  2526. ipath = "/";
  2527. } else {
  2528. ipath = realpath(argv[optind], cwd);
  2529. if (!ipath) {
  2530. fprintf(stderr, "%s: no such dir\n", argv[optind]);
  2531. exit(1);
  2532. }
  2533. }
  2534. /* Increase current open file descriptor limit */
  2535. open_max = max_openfds();
  2536. if (getuid() == 0)
  2537. cfg.showhidden = 1;
  2538. initfilter(cfg.showhidden, &ifilter);
  2539. #ifdef LINUX_INOTIFY
  2540. /* Initialize inotify */
  2541. inotify_fd = inotify_init1(IN_NONBLOCK);
  2542. if (inotify_fd < 0) {
  2543. fprintf(stderr, "inotify init! %s\n", strerror(errno));
  2544. exit(1);
  2545. }
  2546. #elif defined(BSD_KQUEUE)
  2547. kq = kqueue();
  2548. if (kq < 0) {
  2549. fprintf(stderr, "kqueue init! %s\n", strerror(errno));
  2550. exit(1);
  2551. }
  2552. gtimeout.tv_sec = 0;
  2553. gtimeout.tv_nsec = 0;
  2554. #endif
  2555. /* Edit text in EDITOR, if opted */
  2556. if (getenv("NNN_USE_EDITOR"))
  2557. editor = xgetenv("EDITOR", "vi");
  2558. /* Set player if not set already */
  2559. if (!player)
  2560. player = utils[3];
  2561. /* Get the desktop file browser, if set */
  2562. desktop_manager = getenv("NNN_DE_FILE_MANAGER");
  2563. /* Get screensaver wait time, if set; copier used as tmp var */
  2564. copier = getenv("NNN_IDLE_TIMEOUT");
  2565. if (copier)
  2566. idletimeout = abs(atoi(copier));
  2567. /* Get the default copier, if set */
  2568. copier = getenv("NNN_COPIER");
  2569. /* Get nowait flag */
  2570. nowait |= getenv("NNN_NOWAIT") ? F_NOWAIT : 0;
  2571. signal(SIGINT, SIG_IGN);
  2572. /* Test initial path */
  2573. if (!xdiraccess(ipath)) {
  2574. fprintf(stderr, "%s: %s\n", ipath, strerror(errno));
  2575. exit(1);
  2576. }
  2577. /* Set locale */
  2578. setlocale(LC_ALL, "");
  2579. #ifdef DEBUGMODE
  2580. enabledbg();
  2581. #endif
  2582. initcurses();
  2583. browse(ipath, ifilter);
  2584. exitcurses();
  2585. #ifdef LINUX_INOTIFY
  2586. /* Shutdown inotify */
  2587. if (inotify_wd >= 0)
  2588. inotify_rm_watch(inotify_fd, inotify_wd);
  2589. close(inotify_fd);
  2590. #elif defined(BSD_KQUEUE)
  2591. if (event_fd >= 0)
  2592. close(event_fd);
  2593. close(kq);
  2594. #endif
  2595. #ifdef DEBUGMODE
  2596. disabledbg();
  2597. #endif
  2598. exit(0);
  2599. }