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
439
440
441
442
443
444
445
446
447
use std::hash::Hash;

use crate::{
    context::{HitAction, HitRegion, Paint},
    Border, CornerRadius, Id, Padding, Rect, Vec2,
};

mod action;

use super::appearance::Appearance;
use super::{font_size, visible_label, HoverStyle, Response, Ui, Widget};

/// A clickable button. A `##suffix` is part of its ID but hidden from its caption.
pub struct Button<F = fn(&mut crate::Painter<'_>, crate::ControlPaint)> {
    text: String,
    id: Option<Id>,
    enabled: bool,
    width: Option<f32>,
    min_size: Vec2,
    align: crate::Align,
    padding: Option<Padding>,
    rounding: Option<CornerRadius>,
    border: Option<Border>,
    selected: bool,
    /// `selected` was set: the button is a two-state control, not a plain command.
    toggle: bool,
    status: crate::SemanticStatus,
    variant: super::button_variant::ButtonVariant,
    blur: Option<f32>,
    hover_style: Option<HoverStyle>,
    style: super::theme::ButtonStyle,
    painter: Option<super::theme::painter::PaintCallbackHook<F>>,
    icon: Option<crate::ImageSource>,
    action: Option<Id>,
}

impl Button {
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            text: text.into(),
            id: None,
            enabled: true,
            width: None,
            min_size: Vec2::ZERO,
            align: crate::Align::Center,
            padding: None,
            rounding: None,
            border: None,
            selected: false,
            toggle: false,
            status: Default::default(),
            variant: Default::default(),
            blur: None,
            hover_style: None,
            style: Default::default(),
            painter: None,
            icon: None,
            action: None,
        }
    }

    /// A button that runs an action: caption, icon, enabled and checked state come from the
    /// registry, a tooltip names its shortcut, and a click raises the action's event.
    /// Pass the value the action was declared with.
    pub fn action(id: impl Hash) -> Self {
        Self::new("").triggers(id)
    }
}
impl<F: Fn(&mut crate::Painter<'_>, crate::ControlPaint)> Button<F> {
    /// A leading icon before the caption, drawn in the caption's color and one line tall.
    /// It makes the button wider by the icon and a small gap; alignment, hover, pressed and
    /// disabled looks apply to icon and caption together.
    pub fn icon(mut self, icon: impl Into<crate::ImageSource>) -> Self {
        self.icon = Some(icon.into());
        self
    }
    pub fn style(mut self, style: super::theme::ButtonStyle) -> Self {
        self.style = style;
        self
    }
    pub fn painter<G: Fn(&mut crate::Painter<'_>, crate::ControlPaint)>(
        self,
        mode: crate::PaintMode,
        paint: G,
    ) -> Button<G> {
        Button {
            text: self.text,
            id: self.id,
            enabled: self.enabled,
            width: self.width,
            min_size: self.min_size,
            align: self.align,
            padding: self.padding,
            rounding: self.rounding,
            border: self.border,
            selected: self.selected,
            toggle: self.toggle,
            status: self.status,
            variant: self.variant,
            blur: self.blur,
            hover_style: self.hover_style,
            style: self.style,
            icon: self.icon,
            action: self.action,
            painter: Some(super::theme::painter::PaintCallbackHook {
                mode,
                callback: paint,
            }),
        }
    }
    pub fn id_source(mut self, source: impl Hash) -> Self {
        self.id = Some(Id::new(source));
        self
    }
    pub fn enabled(mut self, value: bool) -> Self {
        self.enabled = value;
        self
    }
    pub fn status(mut self, status: crate::SemanticStatus) -> Self {
        self.status = status;
        self
    }
    /// Emphasis preset; explicit `style`, `border` and `rounding` still win.
    pub fn variant(mut self, variant: super::button_variant::ButtonVariant) -> Self {
        self.variant = variant;
        self
    }
    /// Draw the button as chosen. A button given a selected state is announced as a
    /// toggle button by screen readers.
    pub fn selected(mut self, selected: bool) -> Self {
        self.selected = selected;
        self.toggle = true;
        self
    }
    pub fn corner_radius(mut self, radius: impl Into<CornerRadius>) -> Self {
        self.rounding = Some(radius.into());
        self
    }
    /// Exact width in logical pixels, limited by the available layout width.
    #[track_caller]
    pub fn width(mut self, width: f32) -> Self {
        self.width = super::sanitize::positive("Button::width", width).or(self.width);
        self
    }
    #[track_caller]
    pub fn min_size(mut self, size: Vec2) -> Self {
        self.min_size = super::sanitize::size("Button::min_size", size).unwrap_or(self.min_size);
        self
    }
    pub fn padding(mut self, padding: Padding) -> Self {
        self.padding = Some(padding);
        self
    }
    /// Horizontal position of the caption inside the padding; centered by default.
    /// `Start` and `End` suit full-width, text-only buttons in a list.
    pub fn align(mut self, align: crate::Align) -> Self {
        self.align = align;
        self
    }
    #[deprecated(
        note = "use `.corner_radius(..)`; one name for the corner radius of every component"
    )]
    pub fn rounding(self, rounding: CornerRadius) -> Self {
        self.corner_radius(rounding)
    }
    pub fn border(mut self, border: Border) -> Self {
        self.border = Some(border);
        self
    }
    pub fn hover_style(mut self, style: HoverStyle) -> Self {
        self.hover_style = Some(style);
        self
    }
    /// Explicitly blur this button's backdrop. Background blur is not inherited.
    pub fn blur(mut self, radius: f32) -> Self {
        self.blur = Some(super::blur::normalize_radius(radius));
        self
    }
}

/// Space between a leading icon and the caption.
const ICON_GAP: f32 = 6.0;

impl<F: Fn(&mut crate::Painter<'_>, crate::ControlPaint)> Button<F> {
    /// Width the icon takes before the caption: its side (one line tall) and the gap.
    fn icon_lead(&self, font_size: f32) -> f32 {
        if self.icon.is_some() {
            (font_size * 1.15).round() + ICON_GAP
        } else {
            0.0
        }
    }
}

impl<F: Fn(&mut crate::Painter<'_>, crate::ControlPaint)> Widget for Button<F> {
    fn ui(mut self, ui: &mut Ui<'_>) -> Response {
        self.enabled &= ui.is_enabled();
        let action = self.apply_action(ui);
        let style = ui.style().clone();
        let mut component = style.button;
        component.merge(self.variant.style(&style));
        component.merge(self.style);
        let size = font_size(component.font_size.unwrap_or(style.font_size));
        let weight = component
            .font_weight
            .unwrap_or(style.typography.weights.control);
        let id = ui
            .scope
            .with(("button", self.id.unwrap_or_else(|| Id::new(&self.text))));
        let label = visible_label(&self.text);
        let text_size = ui.context.measure_text(label, size, weight, f32::INFINITY);
        let lead = self.icon_lead(size);
        let content = text_size + Vec2::new(lead, 0.0);
        let padding = self
            .padding
            .or(component.padding)
            .unwrap_or(style.button_padding);
        let mut desired_size = (content + padding.size())
            .max(self.min_size)
            .max(component.min_size.unwrap_or(Vec2::ZERO))
            .max(Vec2::new(24.0, style.control_height));
        if let Some(width) = self.width {
            desired_size.x = width;
        }
        let rect = ui.allocate_space(Vec2::new(
            desired_size.x.min(ui.available_width()),
            desired_size.y.min(ui.available_height()),
        ));
        let response = ui.response(id, rect, self.enabled);
        ui.context.register_hit(HitRegion {
            id,
            window: ui.window,
            rect,
            clip: ui.clip,
            action: if self.enabled {
                HitAction::Activate
            } else {
                HitAction::Block
            },
        });
        ui.a11y(id, rect, crate::AccessRole::Button, |node| {
            node.label(label).disabled(!self.enabled).clicks(id);
            if let Some((_, view)) = &action {
                super::actions::describe(node, view);
            }
            if self.toggle {
                node.toggled(self.selected);
            }
        });
        if let Some((action, view)) = &action {
            super::actions::finish_button(ui, *action, view, response, self.enabled);
        }
        let preset = self
            .hover_style
            .or(ui.hover_style)
            .unwrap_or(style.hover_style);
        let mut state = super::theme::ControlState::from_response(response, self.selected);
        state.status = self.status;
        let fill = if !self.enabled {
            style.button_fill
        } else if response.pressed {
            style.button_pressed
        } else if self.selected {
            style.selected_fill
        } else {
            style.button_fill
        };
        let mut base = Appearance::new(
            fill,
            self.border.unwrap_or(style.border),
            if self.selected {
                style.selected_text
            } else {
                style.text_color
            },
        );
        if self.enabled {
            match self.status {
                crate::SemanticStatus::Normal => {}
                crate::SemanticStatus::Success => {
                    base.fill = crate::Gradient::new(style.success, style.success);
                    base.text_color = style.on_success;
                }
                crate::SemanticStatus::Warning => {
                    base.fill = crate::Gradient::new(style.warning, style.warning);
                    base.text_color = style.on_warning;
                }
                crate::SemanticStatus::Error => {
                    base.fill = crate::Gradient::new(style.error, style.error);
                    base.text_color = style.on_error;
                }
            }
        }
        base.rounding = self.rounding.unwrap_or(CornerRadius::all(5.0));
        base.blur = self.blur.unwrap_or(0.0);
        base.opacity = style.opacity;
        base.shadow = style.elevation;
        let mut hover = ui.animate_control(
            response,
            preset,
            self.hover_style.or(ui.hover_style).is_some(),
            component.surface,
            state,
            base,
            if self.status != crate::SemanticStatus::Normal {
                base.fill.start
            } else if self.selected {
                style.selected_fill
            } else {
                style.button_hovered
            },
        );
        // Geometry builders are invariant across interaction states.
        if let Some(v) = self.rounding {
            hover.rounding = v;
        }
        if let Some(v) = self.blur {
            hover.blur = v;
        }
        if let Some(v) = self.border.filter(|_| !state.focus) {
            hover.border = v;
        }
        let (blur, filter) = ui.resolved_blur(
            hover.blur,
            self.blur.is_some() || component.surface.has_blur_override(),
        );
        let rounding = hover.rounding;
        if self
            .painter
            .as_ref()
            .is_none_or(|h| h.mode != crate::PaintMode::Replace)
        {
            ui.context.paint_blur(
                id.with("blur"),
                ui.window,
                ui.clip,
                crate::Blur::new(rect)
                    .radius(filter)
                    .corner_radius(rounding),
            );
        }
        let mut body = Vec::new();
        let info = super::theme::ControlPaint {
            bounds: rect,
            part: super::theme::PaintPart::Button,
            style: hover.surface(),
            state,
            value: if self.selected { 1.0 } else { 0.0 },
        };
        if let Some(hook) = &self.painter {
            if hook.mode != super::theme::PaintMode::After {
                hook.run(&mut body, ui.clip_rect(), info);
            }
        }
        if self
            .painter
            .as_ref()
            .is_none_or(|h| h.mode != super::theme::PaintMode::Replace)
        {
            hover.paint_shadow(rect, rounding, &mut body);
            hover.paint_body(rect, rounding, &style, blur, &mut body);
        }
        if let Some(hook) = &self.painter {
            if hook.mode == super::theme::PaintMode::After {
                hook.run(&mut body, ui.clip_rect(), info);
            }
        }
        ui.context.paint(id.with("body"), ui.window, ui.clip, body);
        // Fixed-height Grid/Table cells may be shorter than the theme's button.
        // Fit the allocation first, then reduce padding before clipping its label.
        let spare = (rect.size() - content).max(Vec2::ZERO);
        let psize = padding.size();
        let x = if psize.x > 0.0 {
            (spare.x / psize.x).min(1.0)
        } else {
            1.0
        };
        let y = if psize.y > 0.0 {
            (spare.y / psize.y).min(1.0)
        } else {
            1.0
        };
        let text_rect = Padding {
            left: padding.left * x,
            right: padding.right * x,
            top: padding.top * y,
            bottom: padding.bottom * y,
        }
        .inset(rect)
        .intersect(rect);
        let optical = ui.context.centered_line_offset(label, size, weight);
        let color = super::appearance::alpha(hover.text_color, hover.opacity);
        let start = match self.align {
            crate::Align::Start => text_rect.min.x,
            crate::Align::Center => rect.center().x - content.x * 0.5,
            crate::Align::End => text_rect.max.x - content.x,
        };
        if let Some(icon) = self.icon.clone() {
            let side = lead - ICON_GAP;
            let glyph = Rect::from_min_size(
                Vec2::new(start, rect.center().y - side * 0.5),
                Vec2::splat(side),
            );
            ui.paint_image_in(id.with("icon"), icon, glyph, color);
        }
        ui.context.paint(
            id.with("caption"),
            ui.window,
            ui.clip.intersect(text_rect),
            vec![Paint::Text {
                text: label.to_owned(),
                position: Vec2::new(start + lead, rect.center().y - text_size.y * 0.5 + optical),
                size,
                weight,
                wrap_width: f32::INFINITY,
                color,
            }],
        );
        response
    }
}

impl Ui<'_> {
    #[deprecated(note = "use `ui.add(Button::new(text).enabled(enabled))`")]
    pub fn button_enabled(&mut self, enabled: bool, text: impl Into<String>) -> Response {
        self.add(Button::new(text).enabled(enabled))
    }
    pub fn selectable(&mut self, selected: bool, text: impl Into<String>) -> Response {
        self.add(Button::new(text).selected(selected))
    }
    pub fn selectable_value<T: PartialEq>(
        &mut self,
        selected: &mut T,
        value: T,
        text: impl Into<String>,
    ) -> Response {
        let mut response = self.selectable(*selected == value, text);
        if response.clicked() && *selected != value {
            *selected = value;
            response.changed = true;
        }
        response
    }
    pub fn button(&mut self, text: impl Into<String>) -> Response {
        self.add(Button::new(text))
    }
}