My build of nnn with minor changes
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

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