Skip to main content

strata/runtime/
mcp.rs

1//! Model Context Protocol (MCP) cursor control, keyboard typing, and element inspection.
2
3use super::*;
4
5impl AppRuntime {
6    /// Ensures that an emulated MCP cursor state is active, initializing it at center viewport if needed.
7    pub fn ensure_mcp_cursor(&mut self) -> &mut strata_platform::McpCursorState {
8        if self.mcp_cursor.is_none() {
9            self.mcp_cursor = Some(strata_platform::McpCursorState::new(
10                self.viewport_width / 2.0,
11                self.viewport_height / 2.0,
12            ));
13        }
14        self.mcp_cursor.as_mut().unwrap()
15    }
16
17    /// Emulates AI pointer movement to `(x, y)` and returns `(needs_rebuild, needs_redraw)`.
18    ///
19    /// Paint-only hover transitions and cursor-only motion return `(false, true)` so automation
20    /// benchmarks exercise the real fast hover path instead of forcing full DOM rebuilds.
21    pub fn mcp_move_pointer_outcome(&mut self, x: f32, y: f32, smooth: bool) -> (bool, bool) {
22        let cursor_icon = Self::hit_test_cursor(&self.root_blueprint, &self.layout_root, x, y);
23        let cursor = self.ensure_mcp_cursor();
24        let cursor_moved = (cursor.target_x - x).abs() > 0.01
25            || (cursor.target_y - y).abs() > 0.01
26            || (cursor.current_x - x).abs() > 0.01
27            || (cursor.current_y - y).abs() > 0.01
28            || cursor.cursor_icon != cursor_icon;
29        cursor.move_to(x, y, smooth);
30        cursor.cursor_icon = cursor_icon;
31
32        self.last_mouse_pos = (x, y);
33        let mut needs_rebuild = false;
34        let mut needs_redraw = cursor_moved;
35
36        let signals_before = strata_dom::reactive::has_dirty_signals();
37        if self.dispatch_pointer_move(x, y) {
38            let retained_only = !signals_before
39                && !strata_dom::reactive::has_dirty_signals()
40                && self.target_is_retained_canvas3d(x, y);
41            if !retained_only {
42                needs_rebuild = true;
43            }
44        }
45        if self.update_hover(x, y) {
46            if self.hover_is_paint_only() {
47                needs_redraw = true;
48            } else {
49                needs_rebuild = true;
50            }
51        }
52        if needs_redraw {
53            self.mark_paint_dirty();
54        }
55
56        (needs_rebuild, needs_redraw)
57    }
58
59    /// Emulates AI pointer movement to `(x, y)`. Smooth interpolation is enabled by default.
60    ///
61    /// Automatically resolves and applies the element's CSS `cursor` style (e.g. pointer, text).
62    /// Returns true only when a view rebuild or display list redraw is genuinely required.
63    pub fn mcp_move_pointer(&mut self, x: f32, y: f32, smooth: bool) -> bool {
64        let (rebuild, redraw) = self.mcp_move_pointer_outcome(x, y, smooth);
65        rebuild || redraw
66    }
67
68    /// Emulates AI mouse button down event, returning `(needs_rebuild, needs_redraw)`.
69    pub fn mcp_mouse_down_outcome(
70        &mut self,
71        button: strata_platform::MouseButton,
72        x: Option<f32>,
73        y: Option<f32>,
74    ) -> (bool, bool) {
75        let mut needs_rebuild = false;
76        let mut needs_redraw = false;
77        let (px, py) = match (x, y) {
78            (Some(px), Some(py)) => {
79                let (rb, rd) = self.mcp_move_pointer_outcome(px, py, false);
80                needs_rebuild |= rb;
81                needs_redraw |= rd;
82                (px, py)
83            }
84            _ => {
85                let c = self.ensure_mcp_cursor();
86                (c.current_x, c.current_y)
87            }
88        };
89
90        let cursor = self.ensure_mcp_cursor();
91        let down_changed = !cursor.is_down;
92        cursor.set_down(true);
93        if down_changed {
94            needs_redraw = true;
95        }
96
97        let btn_idx = button.to_button_index();
98        let signals_before = strata_dom::reactive::has_dirty_signals();
99
100        if button == strata_platform::MouseButton::Left {
101            if self.check_scrollbar_thumb_press(px, py) {
102                self.mark_paint_dirty();
103                return (needs_rebuild, true);
104            }
105            self.begin_window_drag_candidate(px, py);
106            if self.dispatch_pointer_down_with_modifiers(
107                px,
108                py,
109                strata_platform::Modifiers::default(),
110            ) {
111                let retained_only = !signals_before
112                    && !strata_dom::reactive::has_dirty_signals()
113                    && self.target_is_retained_canvas3d(px, py);
114                if !retained_only {
115                    needs_rebuild = true;
116                }
117            }
118            if self.dispatch_mouse_click(px, py, btn_idx, 1) {
119                needs_rebuild = true;
120            }
121            if self.drain_edit_commands() {
122                needs_rebuild = true;
123            }
124        } else if button == strata_platform::MouseButton::Middle {
125            if self.dispatch_pointer_down(px, py) {
126                let retained_only = !signals_before
127                    && !strata_dom::reactive::has_dirty_signals()
128                    && self.target_is_retained_canvas3d(px, py);
129                if !retained_only {
130                    needs_rebuild = true;
131                }
132            }
133            if self.dispatch_mouse_click(px, py, btn_idx, 1) {
134                needs_rebuild = true;
135            }
136        } else if button == strata_platform::MouseButton::Right {
137            if self.dispatch_context_menu(px, py) {
138                needs_rebuild = true;
139            }
140            if self.drain_edit_commands() {
141                needs_rebuild = true;
142            }
143        }
144
145        if needs_redraw {
146            self.mark_paint_dirty();
147        }
148        (needs_rebuild, needs_redraw)
149    }
150
151    /// Emulates AI mouse button down event.
152    pub fn mcp_mouse_down(
153        &mut self,
154        button: strata_platform::MouseButton,
155        x: Option<f32>,
156        y: Option<f32>,
157    ) -> bool {
158        let (rebuild, redraw) = self.mcp_mouse_down_outcome(button, x, y);
159        rebuild || redraw
160    }
161
162    /// Emulates AI mouse button release up event, returning `(needs_rebuild, needs_redraw)`.
163    pub fn mcp_mouse_up_outcome(
164        &mut self,
165        _button: strata_platform::MouseButton,
166        x: Option<f32>,
167        y: Option<f32>,
168    ) -> (bool, bool) {
169        let mut needs_rebuild = false;
170        let mut needs_redraw = false;
171        let (px, py) = match (x, y) {
172            (Some(px), Some(py)) => {
173                let (rb, rd) = self.mcp_move_pointer_outcome(px, py, false);
174                needs_rebuild |= rb;
175                needs_redraw |= rd;
176                (px, py)
177            }
178            _ => {
179                let c = self.ensure_mcp_cursor();
180                (c.current_x, c.current_y)
181            }
182        };
183
184        let cursor = self.ensure_mcp_cursor();
185        if cursor.is_down {
186            needs_redraw = true;
187        }
188        cursor.set_down(false);
189
190        if self.scrollbar_drag.is_some() {
191            self.scrollbar_drag = None;
192            needs_redraw = true;
193        }
194        self.pending_window_drag = None;
195        let signals_before = strata_dom::reactive::has_dirty_signals();
196        if self.dispatch_pointer_up(px, py) {
197            let retained_only = !signals_before
198                && !strata_dom::reactive::has_dirty_signals()
199                && self.target_is_retained_canvas3d(px, py);
200            if !retained_only {
201                needs_rebuild = true;
202            }
203        }
204
205        if needs_redraw {
206            self.mark_paint_dirty();
207        }
208        (needs_rebuild, needs_redraw)
209    }
210
211    /// Emulates AI mouse button release up event.
212    pub fn mcp_mouse_up(
213        &mut self,
214        button: strata_platform::MouseButton,
215        x: Option<f32>,
216        y: Option<f32>,
217    ) -> bool {
218        let (rebuild, redraw) = self.mcp_mouse_up_outcome(button, x, y);
219        rebuild || redraw
220    }
221
222    /// Emulates AI mouse click (press down and release), returning `(needs_rebuild, needs_redraw)`.
223    pub fn mcp_mouse_click_outcome(
224        &mut self,
225        button: strata_platform::MouseButton,
226        x: Option<f32>,
227        y: Option<f32>,
228        count: usize,
229    ) -> (bool, bool) {
230        let mut needs_rebuild = false;
231        let mut needs_redraw = false;
232        let (px, py) = match (x, y) {
233            (Some(px), Some(py)) => {
234                let (rb, rd) = self.mcp_move_pointer_outcome(px, py, false);
235                needs_rebuild |= rb;
236                needs_redraw |= rd;
237                (px, py)
238            }
239            _ => {
240                let c = self.ensure_mcp_cursor();
241                (c.current_x, c.current_y)
242            }
243        };
244
245        for _ in 0..count.max(1) {
246            let (d_rb, d_rd) = self.mcp_mouse_down_outcome(button, Some(px), Some(py));
247            let (u_rb, u_rd) = self.mcp_mouse_up_outcome(button, Some(px), Some(py));
248            needs_rebuild |= d_rb || u_rb;
249            needs_redraw |= d_rd || u_rd;
250        }
251
252        (needs_rebuild, needs_redraw)
253    }
254
255    /// Emulates AI mouse click (press down and release).
256    pub fn mcp_mouse_click(
257        &mut self,
258        button: strata_platform::MouseButton,
259        x: Option<f32>,
260        y: Option<f32>,
261        count: usize,
262    ) -> bool {
263        let (rebuild, redraw) = self.mcp_mouse_click_outcome(button, x, y, count);
264        rebuild || redraw
265    }
266
267    /// Emulates AI mouse wheel scroll event, returning `(needs_rebuild, needs_redraw)`.
268    pub fn mcp_mouse_scroll_outcome(
269        &mut self,
270        delta_x: f32,
271        delta_y: f32,
272        x: Option<f32>,
273        y: Option<f32>,
274    ) -> (bool, bool) {
275        let mut needs_rebuild = false;
276        let mut needs_redraw = false;
277        let (px, py) = match (x, y) {
278            (Some(px), Some(py)) => {
279                let (rb, rd) = self.mcp_move_pointer_outcome(px, py, false);
280                needs_rebuild |= rb;
281                needs_redraw |= rd;
282                (px, py)
283            }
284            _ => {
285                let c = self.ensure_mcp_cursor();
286                (c.current_x, c.current_y)
287            }
288        };
289
290        self.ensure_mcp_cursor().touch_activity();
291        let signals_before = strata_dom::reactive::has_dirty_signals();
292        let (wheel_handled, scroll_changed) =
293            self.dispatch_smooth_scroll_action(px, py, delta_x, delta_y);
294        if wheel_handled {
295            let retained_only = !signals_before
296                && !strata_dom::reactive::has_dirty_signals()
297                && self.target_is_retained_canvas3d(px, py);
298            if !retained_only {
299                needs_rebuild = true;
300            }
301        }
302        if scroll_changed {
303            needs_redraw = true;
304            self.mark_paint_dirty();
305        }
306        (needs_rebuild, needs_redraw)
307    }
308
309    /// Emulates AI mouse wheel scroll event.
310    pub fn mcp_mouse_scroll(
311        &mut self,
312        delta_x: f32,
313        delta_y: f32,
314        x: Option<f32>,
315        y: Option<f32>,
316    ) -> bool {
317        let (rebuild, redraw) = self.mcp_mouse_scroll_outcome(delta_x, delta_y, x, y);
318        rebuild || redraw
319    }
320
321    /// Emulates AI keyboard character input, returning `(needs_rebuild, needs_redraw)`.
322    pub fn mcp_keyboard_type_outcome(&mut self, text: &str) -> (bool, bool) {
323        self.ensure_mcp_cursor().touch_activity();
324        let mut needs_rebuild = false;
325        let mut needs_redraw = false;
326        for ch in text.chars() {
327            let ev = strata_platform::PlatformEvent::ReceivedCharacter(ch);
328            let res = self.dispatch_key_event(&ev);
329            if res.needs_rebuild() {
330                needs_rebuild = true;
331            } else if res.needs_redraw() {
332                needs_redraw = true;
333            }
334        }
335        if needs_redraw {
336            self.mark_paint_dirty();
337        }
338        (needs_rebuild, needs_redraw)
339    }
340
341    /// Emulates AI keyboard character input.
342    pub fn mcp_keyboard_type(&mut self, text: &str) -> bool {
343        let (rebuild, redraw) = self.mcp_keyboard_type_outcome(text);
344        rebuild || redraw
345    }
346
347    /// Emulates AI key combination or non-character navigation key, returning `(needs_rebuild, needs_redraw)`.
348    pub fn mcp_keyboard_key_outcome(
349        &mut self,
350        key: strata_platform::KeyCode,
351        modifiers: strata_platform::Modifiers,
352    ) -> (bool, bool) {
353        self.ensure_mcp_cursor().touch_activity();
354        let ev_down = strata_platform::PlatformEvent::KeyDown { key, modifiers };
355        let res_down = self.dispatch_key_event(&ev_down);
356        let ev_up = strata_platform::PlatformEvent::KeyUp { key, modifiers };
357        let res_up = self.dispatch_key_event(&ev_up);
358        let needs_rebuild = res_down.needs_rebuild() || res_up.needs_rebuild();
359        let needs_redraw = res_down.needs_redraw() || res_up.needs_redraw();
360        if needs_redraw {
361            self.mark_paint_dirty();
362        }
363        (needs_rebuild, needs_redraw)
364    }
365
366    /// Emulates AI key combination or non-character navigation key.
367    pub fn mcp_keyboard_key(
368        &mut self,
369        key: strata_platform::KeyCode,
370        modifiers: strata_platform::Modifiers,
371    ) -> bool {
372        let (rebuild, redraw) = self.mcp_keyboard_key_outcome(key, modifiers);
373        rebuild || redraw
374    }
375
376    fn mcp_input_text(
377        &self,
378        bp: &NodeBlueprint,
379        attributes: &[strata_dom::Attribute],
380        layout: &LayoutNode,
381    ) -> String {
382        let is_password = Self::is_password_input_attrs(attributes);
383        let mask_if_pw = |s: String| {
384            if is_password {
385                Self::mask_password_text(&s)
386            } else {
387                s
388            }
389        };
390        let input_id = attributes.iter().find_map(|attr| match attr {
391            strata_dom::Attribute::Property { key, value } if key == "id" && !value.is_empty() => {
392                Some(value.as_str())
393            }
394            _ => None,
395        });
396
397        if let Some(ref active) = self.active_focus {
398            let matches_active = Self::find_layout_for_focus(
399                &self.root_blueprint,
400                &self.layout_root,
401                active.input_index,
402                active.input_id.as_deref(),
403                active.entity_id,
404            )
405            .is_some_and(|l| std::ptr::eq(l, layout));
406            if matches_active {
407                return mask_if_pw(active.state.text.get());
408            }
409        }
410
411        if let Some(id) = input_id {
412            if let Some(state) = self.input_states.get(id) {
413                return mask_if_pw(state.text.get());
414            }
415        } else {
416            let mut idx = 0usize;
417            while let Some(found) =
418                Self::find_input_layout(&self.root_blueprint, &self.layout_root, idx, None, &mut 0)
419            {
420                if std::ptr::eq(found, layout) {
421                    if let Some(state) = self.input_states.get(&format!("input:{idx}")) {
422                        return mask_if_pw(state.text.get());
423                    }
424                    break;
425                }
426                idx += 1;
427            }
428        }
429
430        for attr in attributes {
431            if let strata_dom::Attribute::Property { key, value } = attr {
432                if key == "value" && !value.is_empty() {
433                    return mask_if_pw(value.clone());
434                }
435            }
436        }
437
438        Self::extract_text_content(bp)
439    }
440
441    /// Inspects the layout element at coordinates `(x, y)` returning tag, CSS classes, bounds, text, and cursor style.
442    pub fn mcp_inspect_element(
443        &self,
444        x: f32,
445        y: f32,
446    ) -> (
447        String,
448        Vec<String>,
449        strata_layout::Rect,
450        String,
451        strata_platform::window::CursorIcon,
452    ) {
453        let cursor_icon = Self::hit_test_cursor(&self.root_blueprint, &self.layout_root, x, y);
454        if let Some(path) = Self::hit_test_node_path(&self.root_blueprint, &self.layout_root, x, y)
455        {
456            if let Some((bp, layout)) =
457                Self::find_node_by_path(&self.root_blueprint, &self.layout_root, &path)
458            {
459                let (tag_name, classes) = match bp {
460                    NodeBlueprint::Element { tag, classes, .. } => {
461                        (format!("{:?}", tag).to_ascii_lowercase(), classes.clone())
462                    }
463                    NodeBlueprint::Text(_) | NodeBlueprint::DynamicText(_) => {
464                        ("#text".to_string(), strata_dom::ClassList::Empty)
465                    }
466                    _ => ("div".to_string(), strata_dom::ClassList::Empty),
467                };
468                let text = match bp {
469                    NodeBlueprint::Element {
470                        tag: Tag::Input | Tag::Textarea,
471                        attributes,
472                        ..
473                    } => self.mcp_input_text(bp, attributes, layout),
474                    _ => Self::extract_text_content(bp),
475                };
476                return (
477                    tag_name,
478                    classes.to_vec(),
479                    layout.geometry.border_box,
480                    text,
481                    cursor_icon,
482                );
483            }
484        }
485
486        (
487            "body".to_string(),
488            Vec::new(),
489            strata_layout::Rect {
490                x: 0.0,
491                y: 0.0,
492                width: self.viewport_width,
493                height: self.viewport_height,
494            },
495            String::new(),
496            cursor_icon,
497        )
498    }
499}