zaxis 0.0.5

An event-driven immediate mode GUI for desktop tools
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
//! Simulated input and read-only state inspection for integration tests.
//!
//! [`Driver`] injects input the way the winit event path does; [`Probe`] borrows
//! retained internal state so tests can assert on it. Neither is a stable API.

#![allow(private_interfaces)]

use super::*;
use crate::{Rect, Vec2};
use std::sync::Arc;
use winit::{event::ElementState, keyboard::KeyCode};

/// Input and focus injection for [`Context`].
pub trait Driver {
    fn move_pointer(&mut self, pointer: Vec2);
    fn primary_button(&mut self, state: ElementState) -> bool;
    fn secondary_button(&mut self, state: ElementState) -> bool;
    fn middle_button(&mut self, state: ElementState) -> bool;
    fn key(&mut self, code: KeyCode, state: ElementState, repeat: bool) -> bool;
    fn scroll_wheel(&mut self, delta: Vec2) -> bool;
    fn scroll_from(&mut self, id: Id, delta: Vec2, middle: bool) -> bool;
    fn set_focus(&mut self, focus: Option<Id>);
    fn set_modifiers(&mut self, modifiers: winit::keyboard::ModifiersState);
    fn dismiss_popup(&mut self, restore_focus: bool);
    fn clipboard_text(&mut self) -> Result<String, ClipboardError>;
    fn copy_text(&mut self, text: String) -> Result<(), ClipboardError>;
    fn take_slider_input(&mut self, id: Id) -> Vec<SliderInput>;
    fn text_carets(
        &mut self,
        text: &str,
        size: f32,
        font: impl Into<TextFont>,
    ) -> Vec<(usize, f32)>;
    fn measure_text(&mut self, text: &str, size: f32, font: impl Into<TextFont>, wrap: f32)
        -> Vec2;
    fn paragraph_layout(
        &mut self,
        text: &str,
        size: f32,
        font: impl Into<TextFont>,
        wrap: f32,
        tab: u16,
    ) -> Arc<crate::text::TextLayout>;
    fn report(
        &mut self,
        kind: DiagnosticKind,
        id: Option<Id>,
        rect: Option<Rect>,
        message: impl FnOnce() -> String,
    );
    fn paint(&mut self, id: Id, layer: Id, clip: Rect, paint: Vec<Paint>);
    fn register_hit(&mut self, hit: HitRegion);
}

impl Driver for Context {
    fn move_pointer(&mut self, pointer: Vec2) {
        Context::move_pointer(self, pointer)
    }
    fn primary_button(&mut self, state: ElementState) -> bool {
        Context::primary_button(self, state)
    }
    fn secondary_button(&mut self, state: ElementState) -> bool {
        Context::secondary_button(self, state)
    }
    fn middle_button(&mut self, state: ElementState) -> bool {
        Context::middle_button(self, state)
    }
    fn key(&mut self, code: KeyCode, state: ElementState, repeat: bool) -> bool {
        Context::key(self, code, state, repeat)
    }
    fn scroll_wheel(&mut self, delta: Vec2) -> bool {
        Context::scroll_wheel(self, delta)
    }
    fn scroll_from(&mut self, id: Id, delta: Vec2, middle: bool) -> bool {
        Context::scroll_from(self, id, delta, middle)
    }
    fn set_focus(&mut self, focus: Option<Id>) {
        Context::set_focus(self, focus)
    }
    fn set_modifiers(&mut self, modifiers: winit::keyboard::ModifiersState) {
        self.input.modifiers = modifiers;
    }
    fn dismiss_popup(&mut self, restore_focus: bool) {
        Context::dismiss_popup(self, restore_focus)
    }
    fn clipboard_text(&mut self) -> Result<String, ClipboardError> {
        Context::clipboard_text(self)
    }
    fn copy_text(&mut self, text: String) -> Result<(), ClipboardError> {
        Context::copy_text(self, text)
    }
    fn take_slider_input(&mut self, id: Id) -> Vec<SliderInput> {
        Context::take_slider_input(self, id)
    }
    fn text_carets(
        &mut self,
        text: &str,
        size: f32,
        font: impl Into<TextFont>,
    ) -> Vec<(usize, f32)> {
        Context::text_carets(self, text, size, font)
    }
    fn measure_text(
        &mut self,
        text: &str,
        size: f32,
        font: impl Into<TextFont>,
        wrap: f32,
    ) -> Vec2 {
        Context::measure_text(self, text, size, font, wrap)
    }
    fn paragraph_layout(
        &mut self,
        text: &str,
        size: f32,
        font: impl Into<TextFont>,
        wrap: f32,
        tab: u16,
    ) -> Arc<crate::text::TextLayout> {
        Context::paragraph_layout(self, text, size, font, wrap, tab)
    }
    fn report(
        &mut self,
        kind: DiagnosticKind,
        id: Option<Id>,
        rect: Option<Rect>,
        message: impl FnOnce() -> String,
    ) {
        Context::report(self, kind, id, rect, message)
    }
    fn paint(&mut self, id: Id, layer: Id, clip: Rect, paint: Vec<Paint>) {
        Context::paint(self, id, layer, clip, paint)
    }
    fn register_hit(&mut self, hit: HitRegion) {
        Context::register_hit(self, hit)
    }
}

/// Files dragged in and dialogs answered without a window, a system or a GPU.
///
/// The desktop calls take the pointer as it is (see [`Driver::move_pointer`]), as the system
/// reports no position of its own; the `_at` calls give the exact one a browser reports.
/// A file per event reaches the context just as winit sends them.
pub trait FileInput {
    /// Files start hovering over the window.
    fn simulate_hover_files(&mut self, files: Vec<crate::PickedFile>);
    /// A browser drag over the canvas at `position`.
    fn simulate_hover_files_at(&mut self, files: Vec<crate::PickedFile>, position: Vec2);
    /// The drag left the window or was cancelled.
    fn simulate_hover_cancel(&mut self);
    /// Files are dropped; the next pass delivers them.
    fn simulate_drop_files(&mut self, files: Vec<crate::PickedFile>);
    /// A browser drop at `position`.
    fn simulate_drop_files_at(&mut self, files: Vec<crate::PickedFile>, position: Vec2);
    /// The user answers a dialog without any window.
    #[cfg(feature = "file-dialogs")]
    fn simulate_dialog_result(
        &mut self,
        request: &crate::DialogRequest,
        result: crate::DialogResult,
    );
}

impl FileInput for Context {
    fn simulate_hover_files(&mut self, files: Vec<crate::PickedFile>) {
        for file in files {
            self.file_hovered(file);
        }
        self.request_repaint();
    }
    fn simulate_hover_files_at(&mut self, files: Vec<crate::PickedFile>, position: Vec2) {
        if self.file_hover_replace(files, position) {
            self.request_repaint();
        }
    }
    fn simulate_hover_cancel(&mut self) {
        if self.file_hover_cancelled() {
            self.request_repaint();
        }
    }
    fn simulate_drop_files(&mut self, files: Vec<crate::PickedFile>) {
        for file in files {
            self.file_dropped(file);
        }
        self.request_repaint();
    }
    fn simulate_drop_files_at(&mut self, files: Vec<crate::PickedFile>, position: Vec2) {
        self.file_drop_batch(files, position);
        self.request_repaint();
    }
    #[cfg(feature = "file-dialogs")]
    fn simulate_dialog_result(
        &mut self,
        request: &crate::DialogRequest,
        result: crate::DialogResult,
    ) {
        self.dialog_answer(request, result)
    }
}

/// Read-only view of the retained state behind a [`Context`].
pub trait Inspect {
    fn probe(&self) -> Probe<'_>;
    fn focus_visible(&self, id: Id) -> bool;
    fn probe_mut(&mut self) -> ProbeMut<'_>;
    fn hovered(&self, id: Id, window: Id, rect: Rect, clip: Rect) -> bool;
    fn top_modal_id(&self) -> Option<Id>;
    fn input_blocked(&self) -> bool;
    fn hit_test(&self, pointer: Vec2) -> Option<HitRegion>;
    fn clicked(&self, id: Id) -> bool;
    fn top_window(&self, pointer: Vec2) -> Option<Id>;
    fn front_window(&self) -> Option<Id>;
    fn layer_rank(&self, id: Id) -> usize;
}

/// Mutable view of the retained state behind a [`Context`].
pub struct ProbeMut<'a> {
    pub cache: &'a mut HashMap<Id, CachedElement>,
    pub scrolling: &'a mut scroll::Scrolling,
    pub drag: &'a mut drag::DragRuntime,
    pub placements: &'a mut placement::Placements,
    pub visual_depth: &'a mut usize,
    pub slider_input: &'a mut HashMap<Id, Vec<SliderInput>>,
    pub next_repaint: &'a mut Option<Instant>,
    pub text: &'a mut TextSystem,
    pub elements: &'a mut Vec<Element>,
    pub logical_size: &'a mut Vec2,
    pub modified: &'a mut HashSet<Id>,
    pub seen: &'a mut HashSet<Id>,
    pub stats: &'a mut CacheStats,
    pub style: &'a mut Style,
    pub native_chrome: &'a mut Option<native_chrome::NativeChrome>,
    pub draw_data: &'a mut DrawData,
}

pub struct Probe<'a> {
    pub input: &'a InputState,
    pub style: &'a Style,
    pub scale: f32,
    pub dirty: bool,
    pub next_repaint: Option<Instant>,
    pub frame: u64,
    pub frame_time: Instant,
    pub style_revision: u64,
    pub local_style_serial: u64,
    pub visual_depth: usize,
    pub stats: CacheStats,
    pub cache: &'a HashMap<Id, CachedElement>,
    pub visual_meshes: &'a HashMap<Id, paint::VisualMesh>,
    pub input_transforms: &'a HashMap<Id, crate::Transform>,
    pub effect_states: &'a HashMap<Id, crate::components::effects::EffectState>,
    pub elements: &'a [Element],
    /// Hit regions registered so far in the current pass.
    pub hits: &'a [HitRegion],
    pub previous_hits: &'a [HitRegion],
    pub capture: &'a Option<interaction::Capture>,
    pub clicked: &'a HashSet<Id>,
    pub slider_input: &'a HashMap<Id, Vec<SliderInput>>,
    pub combo_boxes: &'a HashMap<Id, crate::components::combo_box::ComboBoxState>,
    /// The leaf popup.
    pub popup: LeafPopup<'a>,
    /// The open popups from the root to the leaf.
    pub popups: &'a [popup::PopupState],
    pub popup_layers: &'a [Id],
    pub modals: &'a modal::Modals,
    pub color_pickers: &'a HashMap<Id, crate::components::color_picker::ColorPickerState>,
    pub text_edits: &'a HashMap<Id, crate::components::text_edit::TextEditState>,
    pub ime_area: Option<Rect>,
    pub focused_widget: Option<Id>,
    pub windows: &'a HashMap<Id, WindowState>,
    pub tab_pages: &'a HashMap<Id, crate::components::motion::TabPagesState>,
    pub visible_windows: &'a HashSet<Id>,
    pub scrolling: &'a scroll::Scrolling,
    pub placements: &'a placement::Placements,
    pub cards: &'a HashMap<Id, crate::components::card::CardState>,
    pub carousels: &'a HashMap<Id, crate::components::carousel::CarouselState>,
    pub carousel_wheel_queued: usize,
    pub camera_routing_counts: (usize, usize),
    pub grids: &'a HashMap<Id, crate::components::grid::GridState>,
    pub list_boxes: &'a HashMap<Id, crate::components::list_box::ListState>,
    pub drag: &'a drag::DragRuntime,
    pub counts: Counts,
    pub seen: &'a HashSet<Id>,
    pub native_chrome: &'a Option<native_chrome::NativeChrome>,
    pub draw_data: &'a DrawData,
}

/// Sizes of retained per-widget tables, for cleanup assertions.
pub struct Counts {
    pub context_menus: usize,
    pub docks: usize,
    pub splits: usize,
    pub collapsing_headers: usize,
    pub split_input: usize,
    pub tree_input: usize,
    pub selection_items: usize,
    pub selection_scopes: usize,
}

impl Inspect for Context {
    fn probe(&self) -> Probe<'_> {
        Probe {
            input: &self.input,
            style: &self.style,
            scale: self.scale,
            dirty: self.dirty,
            next_repaint: self.next_repaint,
            frame: self.frame,
            frame_time: self.frame_time,
            style_revision: self.style_revision,
            local_style_serial: self.local_style_serial,
            visual_depth: self.visuals.depth,
            stats: self.stats,
            cache: &self.paint_state.cache,
            visual_meshes: &self.paint_state.visual_meshes,
            input_transforms: self.visuals.published(),
            effect_states: &self.visuals.effects,
            elements: &self.paint_state.elements,
            hits: &self.interaction.hits,
            previous_hits: &self.interaction.previous_hits,
            capture: &self.interaction.capture,
            clicked: &self.interaction.clicked,
            slider_input: &self.values.sliders_input,
            combo_boxes: &self.menus.combo_boxes,
            popup: LeafPopup(self.popups.top()),
            popups: &self.popups.branch,
            popup_layers: &self.popups.layers,
            modals: &self.modals,
            color_pickers: &self.values.color_pickers,
            text_edits: &self.text_fields.states,
            ime_area: self.ime_area,
            focused_widget: self.interaction.focused,
            windows: &self.windows,
            tab_pages: &self.containers.tab_pages,
            visible_windows: &self.visible_windows,
            scrolling: &self.scrolling,
            placements: &self.placements,
            cards: &self.containers.cards,
            carousels: &self.containers.carousels,
            carousel_wheel_queued: self.carousel_wheel.queued(),
            camera_routing_counts: self.camera_routing.counts(),
            grids: &self.containers.grids,
            list_boxes: &self.containers.list_boxes,
            drag: &self.drag,
            seen: &self.paint_state.seen,
            native_chrome: &self.native_chrome,
            draw_data: &self.geometry.draw_data,
            counts: Counts {
                context_menus: self.menus.context_menus.len(),
                docks: self.containers.docks.len(),
                splits: self.splits.states.len(),
                collapsing_headers: self.containers.collapsing_headers.len(),
                split_input: self.splits.pending(),
                tree_input: self.trees.pending(),
                selection_items: self.selection.items.len(),
                selection_scopes: self.selection.scopes.len(),
            },
        }
    }
    fn focus_visible(&self, id: Id) -> bool {
        Context::focus_visible(self, id)
    }
    fn probe_mut(&mut self) -> ProbeMut<'_> {
        ProbeMut {
            cache: &mut self.paint_state.cache,
            scrolling: &mut self.scrolling,
            drag: &mut self.drag,
            placements: &mut self.placements,
            visual_depth: &mut self.visuals.depth,
            slider_input: &mut self.values.sliders_input,
            next_repaint: &mut self.next_repaint,
            text: &mut self.text,
            elements: &mut self.paint_state.elements,
            logical_size: &mut self.logical_size,
            modified: &mut self.paint_state.modified,
            seen: &mut self.paint_state.seen,
            stats: &mut self.stats,
            style: &mut self.style,
            native_chrome: &mut self.native_chrome,
            draw_data: &mut self.geometry.draw_data,
        }
    }
    fn hovered(&self, id: Id, window: Id, rect: Rect, clip: Rect) -> bool {
        Context::hovered(self, id, window, rect, clip)
    }
    fn top_modal_id(&self) -> Option<Id> {
        Context::top_modal_id(self)
    }
    fn input_blocked(&self) -> bool {
        Context::input_blocked(self)
    }
    fn hit_test(&self, pointer: Vec2) -> Option<HitRegion> {
        Context::hit_test(self, pointer)
    }
    fn clicked(&self, id: Id) -> bool {
        Context::clicked(self, id)
    }
    fn top_window(&self, pointer: Vec2) -> Option<Id> {
        Context::top_window(self, pointer)
    }
    fn front_window(&self) -> Option<Id> {
        Context::front_window(self)
    }
    fn layer_rank(&self, id: Id) -> usize {
        Context::layer_rank(self, id)
    }
}

pub use super::clipboard::MemoryClipboard;
pub use super::drag::{preview::layer_id as drag_preview_layer, state::Payload};
pub use super::geometry::Element;
pub use super::interaction::{HitAction, HitRegion};
pub use super::paint::{CachedElement, Paint};
pub use super::values::SliderInput;
#[cfg(feature = "accesskit")]
pub use crate::accessibility::{testing::AccessTree, AccessStats};
pub use crate::components::list_box::{heights::HeightIndex, state::ListState};
pub use crate::components::scroll_area::RowMetrics;
pub use crate::text::{TextFont, DEFAULT_TAB};

/// The leaf popup of a [`Probe`]: `Option`-like, readable from a temporary probe.
#[derive(Clone, Copy)]
pub struct LeafPopup<'a>(Option<&'a popup::PopupState>);

impl<'a> LeafPopup<'a> {
    pub fn as_ref(self) -> Option<&'a popup::PopupState> {
        self.0
    }
    pub fn is_some(self) -> bool {
        self.0.is_some()
    }
    pub fn is_none(self) -> bool {
        self.0.is_none()
    }
}