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
436
437
438
//! Pointer-anchored menus built on the shared popup layer.
use std::hash::Hash;

use super::{Popup, Response, ScrollArea, Ui};
use crate::winit::keyboard::KeyCode;
use crate::{
    context::{HitAction, HitRegion},
    Id, Padding, Rect, Vec2,
};

mod access;
mod actions;
mod cache;
pub(in crate::components) mod paint;

/// A stable action ID is independent of its visible label. Separators have no ID.
#[derive(Clone, Debug, PartialEq)]
pub struct ContextMenuItem {
    pub id: Option<Id>,
    pub text: String,
    pub icon: String,
    pub icon_shapes: Vec<crate::Shape>,
    pub left_text: String,
    pub right_text: String,
    pub enabled: bool,
    /// Draws a check mark in the icon column.
    pub checked: bool,
    /// Draws a chevron; set by cascading menus whose item opens a submenu.
    pub(crate) submenu: bool,
    /// Bound to a registered action: see [`ContextMenuItem::action`].
    pub(crate) action: bool,
}

impl ContextMenuItem {
    pub fn new(id: impl Hash, text: impl Into<String>) -> Self {
        Self {
            id: Some(Id::new(id)),
            text: text.into(),
            icon: String::new(),
            icon_shapes: Vec::new(),
            left_text: String::new(),
            right_text: String::new(),
            enabled: true,
            checked: false,
            submenu: false,
            action: false,
        }
    }
    /// A row that runs a registered action. Its caption, shortcut, enabled and checked
    /// state come from the registry on every pass; choosing it raises the action's event
    /// (`ui.actions().triggered(id)`) and is not reported as `selected`. Pass the value the
    /// action was declared with.
    pub fn action(id: impl Hash) -> Self {
        let mut item = Self::new("", "");
        item.id = Some(crate::actions::action_id(id));
        item.action = true;
        item
    }
    pub fn separator() -> Self {
        Self {
            id: None,
            text: String::new(),
            icon: String::new(),
            icon_shapes: Vec::new(),
            left_text: String::new(),
            right_text: String::new(),
            enabled: false,
            checked: false,
            submenu: false,
            action: false,
        }
    }
    /// A font glyph or short symbol, in a dedicated aligned icon column.
    pub fn icon(mut self, icon: impl Into<String>) -> Self {
        self.icon = icon.into();
        self.icon_shapes.clear();
        self
    }
    /// Vector icon drawn in an 18 × 18 logical-pixel box, with local coordinates.
    pub fn icon_shapes(mut self, shapes: impl IntoIterator<Item = crate::Shape>) -> Self {
        self.icon_shapes = shapes.into_iter().collect();
        self.icon.clear();
        self
    }
    pub fn left_text(mut self, text: impl Into<String>) -> Self {
        self.left_text = text.into();
        self
    }
    pub fn right_text(mut self, text: impl Into<String>) -> Self {
        self.right_text = text.into();
        self
    }
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
    pub fn checked(mut self, checked: bool) -> Self {
        self.checked = checked;
        self
    }
}

/// Colors inherit the current UI theme; these overrides control menu proportions
/// and reuse the existing popup and control appearance styles.
#[derive(Clone, Debug)]
pub struct ContextMenuStyle {
    pub min_width: f32,
    pub row_height: f32,
    pub font_size: f32,
    pub separator_height: f32,
    pub padding: Padding,
    pub popup: crate::PopupStyle,
    pub item: crate::ControlStyle,
}
impl ContextMenuStyle {
    /// Sizes that are not finite and positive fall back to the defaults; padding
    /// becomes non-negative.
    #[track_caller]
    pub(in crate::components) fn normalize(&mut self) {
        use super::sanitize::{length, positive};
        let default = Self::default();
        self.min_width =
            positive("ContextMenuStyle::min_width", self.min_width).unwrap_or(default.min_width);
        self.row_height =
            positive("ContextMenuStyle::row_height", self.row_height).unwrap_or(default.row_height);
        self.separator_height =
            positive("ContextMenuStyle::separator_height", self.separator_height)
                .unwrap_or(default.separator_height);
        self.font_size =
            positive("ContextMenuStyle::font_size", self.font_size).unwrap_or(default.font_size);
        self.padding.left = length("ContextMenuStyle::padding", self.padding.left);
        self.padding.right = length("ContextMenuStyle::padding", self.padding.right);
        self.padding.top = length("ContextMenuStyle::padding", self.padding.top);
        self.padding.bottom = length("ContextMenuStyle::padding", self.padding.bottom);
    }
}
impl Default for ContextMenuStyle {
    fn default() -> Self {
        Self {
            min_width: 220.0,
            row_height: 24.0,
            font_size: 14.0,
            separator_height: 9.0,
            padding: Padding::all(4.0),
            popup: Default::default(),
            item: Default::default(),
        }
    }
}

#[derive(Clone, Copy, Debug, Default)]
pub struct ContextMenuOutput {
    pub open: bool,
    pub rect: Option<Rect>,
    /// Exactly one activation per gesture. The menu closes before returning it.
    pub selected: Option<Id>,
}

#[derive(Default)]
pub(crate) struct MenuState {
    open: bool,
    position: Vec2,
    active: Option<Id>,
    pointer: Option<Vec2>,
    keyboard: bool,
    cache: Option<cache::MenuCache>,
    pub(crate) last_frame: u64,
}

pub struct ContextMenu<'a> {
    source: Id,
    items: &'a [ContextMenuItem],
    style: ContextMenuStyle,
    position: Option<Vec2>,
    target: access::Target,
}
impl<'a> ContextMenu<'a> {
    pub fn new(source: impl Hash, items: &'a [ContextMenuItem]) -> Self {
        Self {
            source: Id::new(source),
            items,
            style: Default::default(),
            position: None,
            target: access::Target::Find,
        }
    }
    pub fn style(mut self, style: ContextMenuStyle) -> Self {
        self.style = style;
        self
    }
    /// Open programmatically on this pass. Omit on later passes to retain state.
    #[track_caller]
    pub fn open_at(mut self, position: Vec2) -> Self {
        self.position =
            super::sanitize::finite_vec2("ContextMenu::open_at", position).or(self.position);
        self
    }
    /// Attach after building the target, in the same UI scope. Works with passive
    /// text as well as controls, and follows deferred layout and scroll clipping.
    /// Action IDs must be unique within this menu.
    pub fn show(self, ui: &mut Ui<'_>, target: Response) -> ContextMenuOutput {
        if !actions::any(self.items) {
            return self.show_items(ui, target);
        }
        let items = actions::resolve(ui, self.items);
        let menu = ContextMenu {
            source: self.source,
            items: &items,
            style: self.style,
            position: self.position,
            target: self.target,
        };
        let mut output = menu.show_items(ui, target);
        actions::raise(ui, &items, &mut output.selected);
        output
    }

    fn show_items(mut self, ui: &mut Ui<'_>, target: Response) -> ContextMenuOutput {
        self.style.normalize();
        let style = &self.style;
        let id = ui.scope.with(("context-menu", self.source, target.id));
        let anchor_id = id.with("anchor");
        let hit = HitRegion {
            id: anchor_id,
            window: ui.window,
            rect: target.rect,
            clip: ui.clip,
            action: HitAction::ContextMenu,
        };
        if !ui.attach_tooltip_anchor(target.id, hit) {
            ui.context.register_hit(hit);
        }
        let popup_id = Popup::id(ui, Id::new(id));
        let mut state = ui
            .context
            .menus
            .context_menus
            .remove(&id)
            .unwrap_or_default();
        state.last_frame = ui.context.frame;
        if ui.context.take_popup_dismissal(popup_id) {
            state.open = false;
        }
        // The same secondary-click signal that `Response::secondary_clicked` reports.
        let pointer_open = ui.context.gestures.secondary_position(anchor_id);
        // A request from assistive technology opens the menu at the target, with the first
        // item highlighted as the keyboard would leave it.
        let asked = access::asked(ui, self.target, target, anchor_id, !self.items.is_empty());
        let placed = self.position.or(pointer_open);
        let opening = placed.or(asked);
        if let Some(position) = opening {
            state.position = position;
            state.keyboard = placed.is_none();
            state.open = ui.enabled;
            state.active = self
                .items
                .iter()
                .find(|i| i.enabled && i.id.is_some())
                .and_then(|i| i.id);
            ui.context.request_repaint();
        }
        state.open &= ui.enabled && !self.items.is_empty();
        let mut output = ContextMenuOutput::default();
        if state.open {
            let pointer = ui.context.input().pointer;
            let pointer_moved = pointer != state.pointer;
            state.pointer = pointer;
            if pointer_moved {
                state.keyboard = false;
            }
            let cache = match state.cache.take() {
                Some(cache) if cache.matches(self.items, style) => cache,
                _ => cache::MenuCache::new(ui, self.items, style),
            };
            let enabled = &cache.enabled;
            if !state.active.is_some_and(|id| enabled.contains(&id)) {
                state.active = enabled.first().copied();
            }
            let mut reveal = false;
            for key in ui.context.take_menu_keys(id) {
                let index = state
                    .active
                    .and_then(|a| enabled.iter().position(|i| *i == a))
                    .unwrap_or(0);
                let next = match key {
                    KeyCode::ArrowDown => Some((index + 1) % enabled.len().max(1)),
                    KeyCode::ArrowUp => {
                        Some((index + enabled.len().saturating_sub(1)) % enabled.len().max(1))
                    }
                    KeyCode::Home => Some(0),
                    KeyCode::End => Some(enabled.len().saturating_sub(1)),
                    KeyCode::Enter | KeyCode::Space => {
                        output.selected = state.active;
                        None
                    }
                    _ => None,
                };
                if let Some(next) = next {
                    state.active = enabled.get(next).copied();
                    state.keyboard = true;
                    reveal = true;
                }
            }
            let metrics = &cache.metrics;
            let popup_style = paint::popup_style(ui, style);
            let mut popup = Popup::new(id, Rect::from_min_size(state.position, Vec2::ZERO))
                .size(Vec2::new(
                    metrics.width + style.padding.size().x,
                    metrics.height + style.padding.size().y,
                ))
                .gap(0.0)
                .padding(style.padding)
                .style(popup_style);
            // The shared keyboard queue preserves multiple key events per redraw.
            popup.key_target = Some(id);
            if placed.is_none() && asked.is_some() {
                // Asked for without a pointer: focus goes back to the widget it belongs to.
                popup = popup.return_focus(target.id);
            }
            let active = state.keyboard.then_some(state.active).flatten();
            let focus = id.with("focus");
            let shown = popup.show(ui, &mut state.open, |ui| {
                // The open menu holds keyboard focus, on a region under its rows.
                ui.context.register_hit(HitRegion {
                    id: focus,
                    window: ui.window,
                    rect: ui.layout.bounds,
                    clip: ui.clip,
                    action: HitAction::Focus,
                });
                let mut scroll = ui.style().scroll;
                scroll.padding = Padding::all(0.0);
                scroll.spacing = 0.0;
                scroll.bar_margin = 0.0;
                let mut scroll_area = ScrollArea::vertical()
                    .id_source(id.with("scroll"))
                    .max_height(ui.available_height())
                    .overlay_scrollbars(true)
                    .style(scroll)
                    .show_hints(false)
                    .middle_mouse_scroll(false)
                    .a11y_hidden();
                // The highlighted row speaks for the menu that holds focus.
                let menu = ui.a11y_begin(id, crate::AccessRole::Menu, |node| {
                    node.focus_on(focus);
                    if let Some(active) = active {
                        node.active_descendant(id.with(("item", active)));
                    }
                });
                if reveal {
                    if let Some(index) = self
                        .items
                        .iter()
                        .position(|item| item.id == active && item.id.is_some())
                    {
                        scroll_area = scroll_area.scroll_to_rect(Rect::from_min_size(
                            Vec2::new(0.0, cache.offsets[index]),
                            Vec2::new(metrics.width, style.row_height),
                        ));
                    }
                }
                let area = scroll_area.show(ui, |ui| {
                    ui.layout.spacing = 0.0;
                    let origin = ui.layout.bounds.min;
                    let visible = ui.clip_rect();
                    let first = cache
                        .offsets
                        .partition_point(|y| *y <= visible.min.y - origin.y)
                        .saturating_sub(1)
                        .min(self.items.len());
                    let end = cache
                        .offsets
                        .partition_point(|y| *y < visible.max.y - origin.y)
                        .min(self.items.len())
                        .max(first);
                    ui.add_space(cache.offsets[first]);
                    for item in &self.items[first..end] {
                        let (response, selected) = paint::row(ui, id, item, active, metrics, style);
                        if selected {
                            output.selected = item.id;
                        }
                        if let Some(response) = response {
                            if pointer_moved && response.hovered && response.enabled {
                                state.active = item.id;
                            }
                        }
                    }
                    ui.add_space(metrics.height - cache.offsets[end]);
                });
                ui.context.a11y_scroll(&menu, area.id);
                ui.a11y_end(menu, Some(area.viewport));
            });
            output.rect = shown.map(|p| p.rect);
            if opening.is_some() && state.open {
                ui.context.set_focus(Some(focus));
            }
            if output.selected.is_some() {
                ui.context.close_popup();
                state.open = false;
            }
            state.cache = Some(cache);
        }
        output.open = state.open;
        ui.context.menus.context_menus.insert(id, state);
        output
    }
}

/// A widget with a context menu attached; see [`super::Widget::context_menu`].
pub struct ContextMenuWidget<'a, W> {
    widget: W,
    items: &'a [ContextMenuItem],
}
impl<'a, W> ContextMenuWidget<'a, W> {
    pub(super) fn new(widget: W, items: &'a [ContextMenuItem]) -> Self {
        Self { widget, items }
    }
}
impl<W: super::Widget> super::Widget for ContextMenuWidget<'_, W> {
    fn ui(self, ui: &mut Ui<'_>) -> Response {
        let before = access::before(ui);
        let mut response = self.widget.ui(ui);
        let mut menu = ContextMenu::new(response.id, self.items);
        menu.target = access::wrapped(ui, before);
        response.menu_selected = menu.show(ui, response).selected;
        response
    }
}

impl Ui<'_> {
    pub fn context_menu(
        &mut self,
        target: Response,
        items: &[ContextMenuItem],
    ) -> ContextMenuOutput {
        ContextMenu::new(target.id, items).show(self, target)
    }
}