1use crate::error::{BrowserError, Result};
13use serde::{Deserialize, Serialize};
14use serde_json::Value;
15use std::sync::Mutex;
16use std::time::Instant;
17
18pub const DESIGN_MODE_GESTURE_WINDOW_MS: u64 = 1_500;
20
21const PICKER_TEMPLATE: &str = include_str!("design_mode_picker.js");
24
25pub fn now_ms() -> u64 {
27 static BASE: std::sync::OnceLock<Instant> = std::sync::OnceLock::new();
28 BASE.get_or_init(Instant::now).elapsed().as_millis() as u64 + 1
29}
30
31#[derive(Debug, Default)]
33pub struct NativeGestureLatch(Mutex<u64>);
34
35impl NativeGestureLatch {
36 pub fn new() -> Self {
37 Self::default()
38 }
39
40 pub fn stamp_at(&self, now_ms: u64) {
42 *self.0.lock().unwrap() = now_ms;
43 }
44
45 pub fn stamp(&self) {
46 self.stamp_at(now_ms());
47 }
48
49 pub fn take(&self, now_ms: u64) -> bool {
51 let mut at = self.0.lock().unwrap();
52 let recent = gesture_is_recent(*at, now_ms);
53 *at = 0;
54 recent
55 }
56}
57
58#[derive(Debug, Clone, PartialEq)]
59pub enum DesignModeMarker {
60 ElementSelected(Value),
61 PromptSubmitted(Value),
62 Dismissed,
63}
64
65pub struct DesignModeSession {
67 pub events: tokio::sync::mpsc::UnboundedReceiver<DesignModeMarker>,
68}
69
70#[derive(Debug, Clone)]
72pub struct DesignModeBridge {
73 nonce: String,
74 last_submit_id: u64,
75}
76
77fn check_nonce(nonce: &str) -> Result<()> {
78 if nonce.is_empty() || !nonce.chars().all(|c| c.is_ascii_alphanumeric()) {
79 return Err(BrowserError::Invalid(
80 "design-mode nonce must be non-empty ASCII alphanumeric".into(),
81 ));
82 }
83 Ok(())
84}
85
86pub fn binding_name_for_nonce(nonce: &str) -> String {
88 format!("__omni_{nonce}_bridge__")
89}
90
91pub fn world_name_for_nonce(nonce: &str) -> String {
93 format!("__omni_{nonce}_world__")
94}
95
96impl DesignModeBridge {
97 pub fn new(nonce: &str) -> Result<Self> {
98 check_nonce(nonce)?;
99 Ok(Self {
100 nonce: nonce.to_string(),
101 last_submit_id: 0,
102 })
103 }
104
105 pub fn binding_name(&self) -> String {
106 binding_name_for_nonce(&self.nonce)
107 }
108
109 pub fn world_name(&self) -> String {
110 world_name_for_nonce(&self.nonce)
111 }
112
113 pub fn accept(
118 &mut self,
119 binding: &str,
120 payload: &str,
121 trusted_context: bool,
122 gesture: &NativeGestureLatch,
123 now_ms: u64,
124 ) -> Option<DesignModeMarker> {
125 if !trusted_context || binding != self.binding_name() {
126 return None;
127 }
128 let v: Value = serde_json::from_str(payload).ok()?;
129 if v.get("nonce").and_then(Value::as_str) != Some(self.nonce.as_str()) {
130 return None;
131 }
132 let data = v.get("data").cloned().unwrap_or(Value::Null);
133 match v.get("kind").and_then(Value::as_str)? {
134 "select" => Some(DesignModeMarker::ElementSelected(data)),
135 "dismiss" => Some(DesignModeMarker::Dismissed),
136 "submit" => {
137 let id = data.get("id").and_then(Value::as_u64)?;
138 if id <= self.last_submit_id || !gesture.take(now_ms) {
139 return None;
140 }
141 self.last_submit_id = id;
142 Some(DesignModeMarker::PromptSubmitted(data))
143 }
144 _ => None,
145 }
146 }
147}
148
149pub fn is_native_gesture_input(input_type: &str) -> bool {
151 matches!(input_type, "mouseDown" | "keyDown" | "rawKeyDown")
152}
153
154pub fn gesture_is_recent(last_gesture_at_ms: u64, now_ms: u64) -> bool {
158 last_gesture_at_ms != 0
159 && now_ms.saturating_sub(last_gesture_at_ms) <= DESIGN_MODE_GESTURE_WINDOW_MS
160}
161
162#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
163#[serde(rename_all = "camelCase")]
164pub struct ElementRect {
165 pub x: f64,
166 pub y: f64,
167 pub width: f64,
168 pub height: f64,
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
172#[serde(rename_all = "camelCase")]
173pub struct CaptureRect {
174 pub x: i64,
175 pub y: i64,
176 pub width: u64,
177 pub height: u64,
178}
179
180pub fn normalize_capture_rect(rect: ElementRect, device_scale: f64) -> Option<CaptureRect> {
185 if !rect.x.is_finite()
186 || !rect.y.is_finite()
187 || !rect.width.is_finite()
188 || !rect.height.is_finite()
189 || rect.width <= 0.0
190 || rect.height <= 0.0
191 {
192 return None;
193 }
194 let scale = if device_scale.is_finite() && device_scale > 0.0 {
195 device_scale
196 } else {
197 1.0
198 };
199 Some(CaptureRect {
200 x: (rect.x * scale).round() as i64,
201 y: (rect.y * scale).round() as i64,
202 width: (rect.width * scale).round().max(1.0) as u64,
203 height: (rect.height * scale).round().max(1.0) as u64,
204 })
205}
206
207pub fn build_design_mode_script(nonce: &str) -> Result<String> {
210 check_nonce(nonce)?;
211 Ok(PICKER_TEMPLATE
212 .replace(
213 "\"@@BINDING@@\"",
214 &js_string(&binding_name_for_nonce(nonce)),
215 )
216 .replace("\"@@NONCE@@\"", &js_string(nonce)))
217}
218
219fn js_string(s: &str) -> String {
220 serde_json::to_string(s).unwrap_or_else(|_| "\"\"".into())
221}
222
223#[cfg(test)]
224mod tests {
225 use super::*;
226 use serde_json::json;
227
228 fn call(nonce: &str, kind: &str, data: Value) -> String {
229 json!({"nonce": nonce, "kind": kind, "data": data}).to_string()
230 }
231
232 #[test]
233 fn bridge_rejects_wrong_binding_context_nonce_and_kind() {
234 let g = NativeGestureLatch::new();
235 let mut b = DesignModeBridge::new("abc123").unwrap();
236 let name = b.binding_name();
237 let sel = call("abc123", "select", json!({"tag": "button"}));
238 assert!(matches!(
239 b.accept(&name, &sel, true, &g, 10),
240 Some(DesignModeMarker::ElementSelected(_))
241 ));
242 assert!(b.accept(&name, &sel, false, &g, 10).is_none());
243 assert!(b
244 .accept("__omni_other_bridge__", &sel, true, &g, 10)
245 .is_none());
246 let forged = call("zzz", "select", json!({}));
247 assert!(b.accept(&name, &forged, true, &g, 10).is_none());
248 assert!(b.accept(&name, "not-json", true, &g, 10).is_none());
249 assert!(b
250 .accept(&name, &call("abc123", "bogus", Value::Null), true, &g, 10)
251 .is_none());
252 assert_eq!(
253 b.accept(&name, &call("abc123", "dismiss", Value::Null), true, &g, 10),
254 Some(DesignModeMarker::Dismissed)
255 );
256 }
257
258 #[test]
259 fn submit_needs_a_fresh_id_and_consumes_one_gesture() {
260 let g = NativeGestureLatch::new();
261 let mut b = DesignModeBridge::new("n").unwrap();
262 let name = b.binding_name();
263 let s1 = call("n", "submit", json!({"id": 1, "prompt": "x"}));
264 assert!(b.accept(&name, &s1, true, &g, 2_000).is_none());
265 g.stamp_at(1_000);
266 assert!(matches!(
267 b.accept(&name, &s1, true, &g, 2_000),
268 Some(DesignModeMarker::PromptSubmitted(_))
269 ));
270 g.stamp_at(2_000);
272 assert!(b.accept(&name, &s1, true, &g, 2_100).is_none());
273 g.stamp_at(3_000);
275 let s2 = call("n", "submit", json!({"id": 2}));
276 let s3 = call("n", "submit", json!({"id": 3}));
277 assert!(b.accept(&name, &s2, true, &g, 3_100).is_some());
278 assert!(b.accept(&name, &s3, true, &g, 3_100).is_none());
279 g.stamp_at(1_000);
281 assert!(b.accept(&name, &s3, true, &g, 9_000).is_none());
282 }
283
284 #[test]
285 fn only_real_native_input_types_stamp_the_gesture() {
286 assert!(is_native_gesture_input("mouseDown"));
287 assert!(is_native_gesture_input("keyDown"));
288 assert!(is_native_gesture_input("rawKeyDown"));
289 assert!(!is_native_gesture_input("mouseUp"));
290 assert!(!is_native_gesture_input("wheel"));
291 assert!(!gesture_is_recent(0, 1_000));
292 assert!(gesture_is_recent(1_000, 2_500));
293 assert!(!gesture_is_recent(1_000, 2_501));
294 }
295
296 #[test]
297 fn capture_geometry_preserves_zoom_and_rejects_empty_rectangles() {
298 assert_eq!(
299 normalize_capture_rect(
300 ElementRect {
301 x: 10.25,
302 y: -2.25,
303 width: 40.4,
304 height: 20.4
305 },
306 2.0,
307 ),
308 Some(CaptureRect {
309 x: 21,
310 y: -5,
311 width: 81,
312 height: 41
313 })
314 );
315 assert_eq!(
316 normalize_capture_rect(
317 ElementRect {
318 x: 0.0,
319 y: 0.0,
320 width: 0.0,
321 height: 2.0
322 },
323 1.0
324 ),
325 None
326 );
327 assert_eq!(
328 normalize_capture_rect(
329 ElementRect {
330 x: 0.0,
331 y: 0.0,
332 width: 1.0,
333 height: 1.0
334 },
335 f64::NAN,
336 ),
337 Some(CaptureRect {
338 x: 0,
339 y: 0,
340 width: 1,
341 height: 1
342 })
343 );
344 }
345
346 #[test]
347 fn picker_script_uses_the_binding_not_the_console() {
348 let script = build_design_mode_script("abc123").unwrap();
349 assert!(script.contains("var __OMNI_BINDING = \"__omni_abc123_bridge__\";"));
350 assert!(script.contains("var __OMNI_NONCE = \"abc123\";"));
351 assert!(!script.contains("@@"));
352 assert!(!script.contains("console."));
353 assert!(script.contains("window.__omniDisableDesignMode"));
354 assert!(script.contains("split(/\\s+/)"));
355 }
356
357 #[test]
358 fn picker_script_rejects_unsafe_nonces() {
359 assert!(build_design_mode_script("").is_err());
360 assert!(build_design_mode_script("ab\"cd").is_err());
361 assert!(build_design_mode_script("ab_cd").is_err());
362 }
363}