reticle_tauri/lib.rs
1//! Reticle support for a Tauri app: screenshots, and a headless mode that actually stays awake.
2//!
3//! Tauri has no preload stage, so there is nowhere to install a JavaScript shim before app code
4//! runs. Everything here is therefore Rust-side, and the browser SDK finds it on its own: it invokes
5//! `reticle_capture` through Tauri's internals when no preload channel exists. An app wires this up
6//! with two lines in `main.rs` and nothing at all in its frontend.
7//!
8//! ```no_run
9//! tauri::Builder::default()
10//! .invoke_handler(tauri::generate_handler![reticle_tauri::reticle_capture])
11//! .on_page_load(reticle_tauri::on_page_load)
12//! # ;
13//! ```
14
15mod capture;
16
17pub use capture::*;
18
19use tauri::{Runtime, Webview};
20
21/// Whether this build does anything at all: debug builds, or a release build with `in-release`.
22///
23/// A signed release binary must carry no Reticle capability. On macOS a build signed differently
24/// from the installed app is a different app to the keychain, and every keychain read prompts; a
25/// dev-only crate that stays live in the shipped binary also hands a screenshot command to anything
26/// that can invoke it. So in a release build `reticle_capture` refuses and `on_page_load` does
27/// nothing, and the compiler drops the code behind them.
28pub const ACTIVE: bool = cfg!(any(debug_assertions, feature = "in-release"));
29
30/// What `reticle_capture` answers in a release build.
31pub const INERT_IN_RELEASE: &str =
32 "reticle-tauri is inert in a release build (enable its `in-release` feature to test one)";
33
34/// The refusal for a build where this crate is inert, else none.
35pub fn inert_refusal() -> Option<&'static str> {
36 if ACTIVE {
37 None
38 } else {
39 Some(INERT_IN_RELEASE)
40 }
41}
42
43/// Filename prefix the daemon requires before it will read a capture off disk.
44///
45/// Source of truth is `RETICLE_CAPTURE_FILE_PREFIX` in `@reticlehq/core`; the two cannot share a
46/// module graph, so `desktop-contract.test.ts` asserts this file still spells it the same way.
47const CAPTURE_FILE_PREFIX: &str = "reticle-capture-";
48
49/// How long to wait for the webview to hand back a snapshot before giving up.
50const SNAPSHOT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
51
52/// Returned when `fullPage` is asked of a platform that can only give the composited viewport.
53///
54/// The SDK matches on this exact text, and `desktop-contract.test.ts` pins it to the daemon's
55/// `VisualReason.FULL_PAGE_UNSUPPORTED`. Refusing beats downgrading: a caller who asked for the
56/// whole scroll height and silently got the visible part banks a baseline that says nothing about
57/// the content below the fold, and a later diff calls it a match.
58pub const FULL_PAGE_UNSUPPORTED: &str = "full-page-unsupported";
59
60/// Environment variable that asks for a window nobody can see.
61const HEADLESS_ENV: &str = "RETICLE_HEADLESS";
62
63/// Older macOS versions have no public WebKit background scheduling control.
64#[cfg(target_os = "macos")]
65const OFFSCREEN_PX: i32 = -32_000;
66
67/// Keep the window drivable behind other windows, and hide it when `RETICLE_HEADLESS=1`.
68///
69/// macOS throttles an occluded WKWebView: its timers and rendering stop, so every check a drive
70/// makes while the window is behind another comes back "has not rendered". Reported from a drive the
71/// platform's chat asked for, which proved nothing until the window was brought forward by hand. On
72/// macOS 14+ WebKit can be told to keep scheduling while inactive, and this crate is dev-only, so it
73/// is done for every window it is installed in.
74///
75/// Headless mode then hides the window, after its first load: a webview that has never been
76/// presented may not load. Older macOS has no scheduling control, so headless falls back to an
77/// offscreen position (AppKit may constrain it back onto a display). Linux and Windows hide directly.
78pub fn on_page_load<R: Runtime>(
79 webview: &Webview<R>,
80 payload: &tauri::webview::PageLoadPayload<'_>,
81) {
82 if !ACTIVE || payload.event() != tauri::webview::PageLoadEvent::Finished {
83 return;
84 }
85 let headless = std::env::var(HEADLESS_ENV).as_deref() == Ok("1");
86 #[cfg(target_os = "macos")]
87 {
88 awake_macos(webview, headless);
89 }
90 #[cfg(not(target_os = "macos"))]
91 {
92 if headless {
93 let _ = webview.window().hide();
94 }
95 }
96}
97
98#[cfg(target_os = "macos")]
99fn awake_macos<R: Runtime>(webview: &Webview<R>, headless: bool) {
100 use objc2::{runtime::NSObjectProtocol, sel};
101 use objc2_web_kit::{WKInactiveSchedulingPolicy, WKWebView};
102
103 let window = webview.window();
104 let _ = webview.with_webview(move |inner| {
105 // SAFETY: Tauri supplies the live WKWebView and executes this closure on the main thread.
106 let wk: &WKWebView = unsafe { &*(inner.inner() as *const WKWebView) };
107 let preferences = unsafe { wk.configuration().preferences() };
108 let awake = preferences.respondsToSelector(sel!(setInactiveSchedulingPolicy:));
109 if awake {
110 // SAFETY: this public selector is available on macOS 14+, checked above. Changing the
111 // live view's preferences keeps its task scheduling active while it is not in front.
112 unsafe { preferences.setInactiveSchedulingPolicy(WKInactiveSchedulingPolicy::None) };
113 }
114 if !headless {
115 return;
116 }
117 if awake {
118 let _ = window.hide();
119 } else {
120 let _ = window.set_position(tauri::PhysicalPosition::new(OFFSCREEN_PX, OFFSCREEN_PX));
121 }
122 });
123}
124
125#[cfg(test)]
126mod release_tests {
127 /// A release build of the app (the one a person signs and ships) must carry no Reticle
128 /// capability: a signed app that Reticle can screenshot or re-schedule is a dev tool in a
129 /// customer's hands. `cargo test --release` runs this with the release profile.
130 #[cfg(all(not(debug_assertions), not(feature = "in-release")))]
131 #[test]
132 fn a_release_build_is_inert() {
133 assert_eq!(crate::inert_refusal(), Some(crate::INERT_IN_RELEASE));
134 }
135
136 #[cfg(any(debug_assertions, feature = "in-release"))]
137 #[test]
138 fn a_dev_build_is_active() {
139 assert_eq!(crate::inert_refusal(), None);
140 }
141}