rightkit_browser/
design_mode.rs1use 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}