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