cranpose-app-shell 0.1.143

Application orchestration shell for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Developer inspection drawn outside the application's composition and semantics.

use std::fmt::Debug;

use cranpose_core::NodeId;
use cranpose_render_common::Renderer;
use cranpose_ui::{KeyCode, KeyEvent, KeyEventType, LayoutTree, SemanticsTree};
use cranpose_ui_graphics::{Point, Rect, Size};

use crate::{AppShell, RootSurface, ShellApp, SurfaceMut};

#[path = "inspector_draw.rs"]
mod draw;

/// The application's visual presentation while inspecting accessibility.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InspectorMode {
    /// Draw the application normally.
    #[default]
    Normal,
    /// Draw accessibility bounds and reading-order numbers over the application.
    Overlay,
    /// Cover the application with its accessible controls and labels.
    Accessibility,
}

/// An inspector control, independent of the application's actions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InspectorAction {
    /// Open or close the inspector.
    Toggle,
    /// Drag the floating panel by its title bar.
    Move,
    /// Show the normal application.
    Normal,
    /// Show accessibility outlines.
    Overlay,
    /// Show only the accessibility representation.
    Accessibility,
    /// Select a control by its screen bounds without activating it.
    Pick,
    /// Select the previous accessible element.
    Previous,
    /// Select the next accessible element.
    Next,
    /// Scroll the selected element's properties toward the beginning.
    DetailsUp,
    /// Scroll the selected element's properties toward the end.
    DetailsDown,
    /// Select an element at its reading-order index.
    Select(usize),
}

/// A sanitized platform-projection element for developer inspection.
#[derive(Clone, Debug, PartialEq)]
pub struct InspectorNode {
    /// The application node owning this accessible element.
    pub node_id: NodeId,
    /// The identity of a virtual canvas child, when present.
    pub canvas_key: Option<u64>,
    /// Accessible bounds in surface-local logical pixels.
    pub bounds: Rect,
    /// Accessible name and role for the reading-order list.
    pub label: String,
    /// Accessible properties and actions, with password values excluded.
    pub details: String,
    /// Whether the application reports this element as focused.
    pub focused: bool,
    /// An actionable naming issue to mark in the overlay.
    pub issue: bool,
}

/// A visible inspector control and its logical hit bounds.
#[derive(Clone, Debug, PartialEq)]
pub struct InspectorControl {
    /// The operation performed by this control.
    pub action: InspectorAction,
    /// Bounds shared by rendering and pointer dispatch.
    pub bounds: Rect,
}

/// A read-only snapshot of developer UI, separate from application semantics.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct InspectorState {
    /// Whether the inspector panel is open.
    pub open: bool,
    /// The selected visual mode.
    pub mode: InspectorMode,
    /// Whether the next application press selects an element.
    pub picking: bool,
    /// Elements in the shared projection's reading order.
    pub nodes: Vec<InspectorNode>,
    /// The selected element's index in `nodes`.
    pub selected: Option<usize>,
    /// The first visible line of the selected element's properties.
    pub detail_offset: usize,
    /// Visible developer controls for deterministic robot input.
    pub controls: Vec<InspectorControl>,
    /// User-positioned launcher origin in logical pixels, clamped to the surface.
    pub launcher_position: Option<Point>,
    /// User-positioned panel origin in logical pixels, clamped to the surface.
    pub panel_position: Option<Point>,
}

/// Projects a surface's trees using the same policy as its platform bridge.
pub type InspectorProjector = fn(&LayoutTree, &SemanticsTree) -> Vec<InspectorNode>;

#[derive(Default)]
pub(crate) struct DeveloperInspector {
    pub(crate) state: InspectorState,
    revision: Option<u64>,
    viewport: Option<Size>,
    dirty: bool,
    pub(crate) pointer_captured: bool,
    keyboard: bool,
    installed: bool,
    drag: Option<InspectorDrag>,
}

struct InspectorDrag {
    action: InspectorAction,
    start: Point,
    origin: Point,
    moved: bool,
}

impl DeveloperInspector {
    fn apply(&mut self, action: InspectorAction) {
        match action {
            InspectorAction::Move => return,
            InspectorAction::Toggle => {
                self.state.open = !self.state.open;
                self.state.picking = false;
                self.keyboard = self.state.open;
                if !self.state.open {
                    self.state.mode = InspectorMode::Normal;
                    self.state.nodes.clear();
                    self.state.selected = None;
                    self.revision = None;
                }
            }
            InspectorAction::Normal => self.state.mode = InspectorMode::Normal,
            InspectorAction::Overlay => self.state.mode = InspectorMode::Overlay,
            InspectorAction::Accessibility => self.state.mode = InspectorMode::Accessibility,
            InspectorAction::Pick => self.state.picking = !self.state.picking,
            InspectorAction::Previous => self.select_relative(false),
            InspectorAction::Next => self.select_relative(true),
            InspectorAction::DetailsUp => {
                self.state.detail_offset = self.state.detail_offset.saturating_sub(3)
            }
            InspectorAction::DetailsDown => {
                let count = draw::detail_line_count(&self.state, self.viewport.unwrap_or_default());
                self.state.detail_offset =
                    (self.state.detail_offset + 3).min(count.saturating_sub(1));
            }
            InspectorAction::Select(index) => {
                self.state.selected = (index < self.state.nodes.len()).then_some(index);
                self.state.detail_offset = 0;
            }
        }
        self.dirty = true;
    }

    fn select_relative(&mut self, forward: bool) {
        self.state.detail_offset = 0;
        let len = self.state.nodes.len();
        if len == 0 {
            self.state.selected = None;
            return;
        }
        self.state.selected = Some(match self.state.selected {
            Some(index) if forward => (index + 1) % len,
            Some(index) => (index + len - 1) % len,
            None if forward => 0,
            None => len - 1,
        });
    }

    fn replace_nodes(&mut self, nodes: Vec<InspectorNode>) {
        if self.state.nodes == nodes {
            return;
        }
        let identity = self
            .state
            .selected
            .and_then(|index| self.state.nodes.get(index))
            .map(|node| (node.node_id, node.canvas_key));
        self.state.selected = identity.and_then(|identity| {
            nodes
                .iter()
                .position(|node| (node.node_id, node.canvas_key) == identity)
        });
        self.state.detail_offset = 0;
        self.state.nodes = nodes;
        self.dirty = true;
    }

    fn pick(&mut self, x: f32, y: f32) {
        self.state.selected = self
            .state
            .nodes
            .iter()
            .enumerate()
            .filter(|(_, node)| node.bounds.contains(x, y))
            .min_by(|(_, a), (_, b)| {
                (a.bounds.width * a.bounds.height).total_cmp(&(b.bounds.width * b.bounds.height))
            })
            .map(|(index, _)| index);
        self.state.picking = false;
        self.state.detail_offset = 0;
        self.keyboard = true;
        self.dirty = true;
    }

    fn start_drag(&mut self, action: InspectorAction, x: f32, y: f32) {
        let viewport = self.viewport.unwrap_or_default();
        let bounds = if action == InspectorAction::Move {
            draw::panel_bounds(&self.state, viewport)
        } else {
            draw::launcher_bounds(&self.state, viewport)
        };
        self.drag = Some(InspectorDrag {
            action,
            start: Point { x, y },
            origin: Point {
                x: bounds.x,
                y: bounds.y,
            },
            moved: false,
        });
    }

    fn move_pointer(&mut self, x: f32, y: f32) -> bool {
        let Some(drag) = &mut self.drag else {
            return false;
        };
        let dx = x - drag.start.x;
        let dy = y - drag.start.y;
        drag.moved |= dx * dx + dy * dy >= 16.0;
        if !drag.moved {
            return false;
        }
        let position = Some(Point {
            x: drag.origin.x + dx,
            y: drag.origin.y + dy,
        });
        if drag.action == InspectorAction::Move {
            self.state.panel_position = position;
        } else {
            self.state.launcher_position = position;
        }
        self.dirty = true;
        true
    }

    pub(crate) fn release_pointer(&mut self) -> bool {
        if !std::mem::take(&mut self.pointer_captured) {
            return false;
        }
        if let Some(drag) = self.drag.take()
            && !drag.moved
            && drag.action != InspectorAction::Move
        {
            self.apply(drag.action);
        }
        true
    }

    pub(crate) fn cancel_pointer(&mut self) {
        self.pointer_captured = false;
        self.drag = None;
    }
}

impl<R: Renderer> AppShell<R>
where
    R::Error: Debug,
{
    /// Installs or disables the developer inspector without adding application nodes.
    ///
    /// Hosts install the platform projection in debug builds. `None` removes all
    /// inspector drawing and input handling, including on secondary surfaces.
    pub fn set_inspector_projector(&mut self, projector: Option<InspectorProjector>) {
        self.app.inspector_projector = projector;
        for surface in &mut self.surfaces {
            surface.inspector = DeveloperInspector {
                dirty: true,
                ..Default::default()
            };
            if projector.is_none() {
                surface.renderer.set_inspector_overlay(None);
            }
            surface.is_dirty = true;
        }
    }

    /// The primary surface's inspector state, independent of application semantics.
    pub fn inspector_state(&self) -> &InspectorState {
        &self.surfaces[0].inspector.state
    }
}

impl<R: Renderer> SurfaceMut<'_, R>
where
    R::Error: Debug,
{
    /// This surface's developer UI and projected application elements.
    pub fn inspector_state(&self) -> &InspectorState {
        &self.surface().inspector.state
    }

    pub(crate) fn inspector_owns_keyboard(&self) -> bool {
        let inspector = &self.surface().inspector;
        inspector.state.open && inspector.keyboard
    }

    pub(crate) fn inspector_blocks_pointer(&self, x: f32, y: f32) -> bool {
        let inspector = &self.surface().inspector;
        self.shell_app_ref().inspector_projector.is_some()
            && (inspector.pointer_captured
                || inspector.state.picking
                || inspector
                    .state
                    .controls
                    .iter()
                    .any(|control| control.bounds.contains(x, y))
                || (inspector.state.open
                    && draw::panel_bounds(
                        &inspector.state,
                        inspector.viewport.unwrap_or_default(),
                    )
                    .contains(x, y)))
    }

    pub(crate) fn inspector_move(&mut self, x: f32, y: f32) -> bool {
        self.surface_mut().inspector.move_pointer(x, y)
    }

    pub(crate) fn inspector_scroll(&mut self, delta: f32) -> bool {
        let (x, y) = self.surface().cursor;
        if !self.inspector_blocks_pointer(x, y) {
            return false;
        }
        let inspector = &mut self.surface_mut().inspector;
        if inspector.state.open && delta != 0.0 {
            inspector.apply(if delta < 0.0 {
                InspectorAction::DetailsDown
            } else {
                InspectorAction::DetailsUp
            });
            self.mark_dirty();
        }
        true
    }

    pub(crate) fn inspector_press(&mut self, x: f32, y: f32) -> bool {
        if self.shell_app_ref().inspector_projector.is_none() {
            return false;
        }
        let inspector = &mut self.surface_mut().inspector;
        let action = inspector
            .state
            .controls
            .iter()
            .find(|control| control.bounds.contains(x, y))
            .map(|control| control.action);
        let consumed = if let Some(action) = action {
            if action == InspectorAction::Move || !inspector.state.open || inspector.state.picking {
                inspector.start_drag(action, x, y);
            } else {
                inspector.apply(action);
            }
            inspector.keyboard = inspector.state.open;
            true
        } else if inspector.state.open && inspector.state.picking {
            inspector.pick(x, y);
            true
        } else {
            inspector.keyboard = false;
            inspector.state.open
                && draw::panel_bounds(&inspector.state, inspector.viewport.unwrap_or_default())
                    .contains(x, y)
        };
        if consumed {
            inspector.keyboard = inspector.state.open;
            inspector.pointer_captured = true;
            self.mark_dirty();
        }
        consumed
    }

    pub(crate) fn inspector_key(&mut self, event: &KeyEvent) -> bool {
        if self.shell_app_ref().inspector_projector.is_none() {
            return false;
        }
        let inspector = &mut self.surface_mut().inspector;
        let action = if inspector.state.open && inspector.keyboard {
            match event.key_code {
                KeyCode::Escape => Some(InspectorAction::Toggle),
                KeyCode::ArrowUp | KeyCode::ArrowLeft => Some(InspectorAction::Previous),
                KeyCode::ArrowDown | KeyCode::ArrowRight => Some(InspectorAction::Next),
                KeyCode::Digit1 => Some(InspectorAction::Normal),
                KeyCode::Digit2 => Some(InspectorAction::Overlay),
                KeyCode::Digit3 => Some(InspectorAction::Accessibility),
                KeyCode::P => Some(InspectorAction::Pick),
                KeyCode::PageUp => Some(InspectorAction::DetailsUp),
                KeyCode::PageDown => Some(InspectorAction::DetailsDown),
                _ => None,
            }
        } else {
            None
        };
        let Some(action) = action else {
            return inspector.state.open && inspector.keyboard;
        };
        if event.event_type == KeyEventType::KeyDown {
            inspector.apply(action);
            self.mark_dirty();
        }
        true
    }
}

pub(crate) fn refresh<R: Renderer>(
    app: &mut ShellApp,
    surface: &mut RootSurface<R>,
    revision: u64,
) -> bool {
    let Some(projector) = app.inspector_projector else {
        return false;
    };
    let viewport = surface.viewport_size();
    if surface.inspector.viewport != Some(viewport) {
        surface.inspector.viewport = Some(viewport);
        surface.inspector.dirty = true;
    }
    if surface.inspector.state.open && surface.inspector.revision != Some(revision) {
        surface.layout_tree_in_context(app);
        surface.semantics_tree_in_context(app);
        let nodes = match (&surface.layout_tree, &surface.semantics_tree) {
            (Some(layout), Some(semantics)) => projector(layout, semantics),
            _ => Vec::new(),
        };
        surface.inspector.replace_nodes(nodes);
        surface.inspector.revision = Some(revision);
    }
    if !surface.inspector.dirty && surface.inspector.installed {
        return false;
    }
    let graph = draw::build(&mut surface.inspector.state, viewport);
    surface.renderer.set_inspector_overlay(Some(graph));
    surface.inspector.installed = true;
    surface.inspector.dirty = false;
    true
}

#[cfg(test)]
#[path = "tests/inspector_tests.rs"]
mod tests;