rust_widgets 2.8.1

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! `ToastStack` — the container that queues toasts and lays them out as rows.

use super::item::{ToastItem, ToastLevel};
use crate::core::{Color, Font, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::menu_toolbar::popup_reveal::PopupReveal;
use crate::widget::metrics::ControlMetrics;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// Toast stack with keyboard/mouse activation and dismiss.
pub struct ToastStack {
    base: BaseWidget,
    toasts: Vec<ToastItem>,
    selected_index: Option<usize>,
    row_height: u32,
    /// The newest toast's rise-in reveal, so a toast arrives from the bottom edge instead of
    /// appearing on the frame it was pushed.
    ///
    /// # Why one reveal and not one per toast
    ///
    /// Toasts are queued, so at most one is ever *arriving* — the others have already settled. A
    /// per-toast driver would be N state machines for one visible movement, plus the lifetime
    /// bookkeeping to retire them. One driver, re-aimed on every `push`, says the same thing: the
    /// newest row rises, the rest sit still.
    reveal: PopupReveal,
    /// Emitted when toast is activated.
    pub toast_activated: Signal1<String>,
    /// Emitted when toast is dismissed.
    pub toast_dismissed: Signal1<String>,
}

impl ToastStack {
    /// Creates empty toast stack.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::PopupWindow, geometry, "ToastStack"),
            toasts: Vec::new(),
            selected_index: None,
            row_height: 30,
            reveal: PopupReveal::new(true),
            toast_activated: Signal1::new(),
            toast_dismissed: Signal1::new(),
        }
    }

    /// Returns toast items.
    pub fn toasts(&self) -> &[ToastItem] {
        &self.toasts
    }

    /// Adds a toast to the stack.
    pub fn push(&mut self, item: ToastItem) {
        self.toasts.push(item);
        self.selected_index = Some(self.toasts.len() - 1);
        // The new row starts fully below its seat and rises into it. `jump_to(false)` before
        // aiming at open, so the first painted frame is the start of the movement rather than a
        // snap to the middle of it.
        self.reveal.jump_to(false);
        self.reveal.set_open(true);
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// Clears all toasts.
    pub fn clear(&mut self) {
        self.toasts.clear();
        self.selected_index = None;
        self.base.request_layout();
        self.base.request_redraw();
    }

    /// Returns selected toast id.
    pub fn selected_id(&self) -> Option<&str> {
        let index = self.selected_index?;
        self.toasts.get(index).map(|item| item.id.as_str())
    }

    /// Selects toast by index.
    pub fn select_index(&mut self, index: usize) -> bool {
        if index >= self.toasts.len() {
            return false;
        }
        self.selected_index = Some(index);
        self.base.request_redraw();
        true
    }

    /// Activates selected toast.
    pub fn activate_selected(&mut self) -> bool {
        let Some(index) = self.selected_index else {
            return false;
        };
        let Some(item) = self.toasts.get(index) else {
            return false;
        };
        self.toast_activated.emit(item.id.clone());
        true
    }

    /// Dismisses selected toast.
    pub fn dismiss_selected(&mut self) -> bool {
        let Some(index) = self.selected_index else {
            return false;
        };
        if index >= self.toasts.len() {
            return false;
        }

        let id = self.toasts[index].id.clone();
        self.toasts.remove(index);
        self.toast_dismissed.emit(id);

        if self.toasts.is_empty() {
            self.selected_index = None;
        } else if index >= self.toasts.len() {
            self.selected_index = Some(self.toasts.len() - 1);
        }

        self.base.request_layout();
        self.base.request_redraw();
        true
    }

    /// The region the stack actually occupies: the bottom of the control's rectangle, as many
    /// rows tall as there are toasts, clamped to the rectangle.
    ///
    /// # Why the stack is not the rectangle
    ///
    /// A toast stack is a column of fixed-height bars. Filling the whole rectangle made a
    /// 240x120 census cell a 120 px panel behind two 26 px rows — a surface much larger than
    /// the toasts it holds, whose top edge was painted but never occupied. Anchoring the band to
    /// the bottom and sizing it from the rows is the same derivation the draw and the hit test
    /// read, so the panel and the rows it contains cannot disagree.
    ///
    /// An empty stack still claims **one row**: the control is a drop target that has to show
    /// where a toast will land, and an empty container that paints nothing is indistinguishable
    /// from a control that was never laid out (the census's P1 defect).
    fn stack_band(&self) -> Rect {
        let rows = (self.toasts.len() as u32).max(1);
        let height = rows.saturating_mul(self.row_height);
        ControlMetrics::bottom_band(self.geometry(), height)
    }

    fn row_at(&self, pos: Point) -> Option<usize> {
        if self.toasts.is_empty() {
            return None;
        }
        let band = self.stack_band();
        if pos.x < band.x
            || pos.x >= band.x + band.width as i32
            || pos.y < band.y
            || pos.y >= band.y + band.height as i32
        {
            return None;
        }

        let bottom = band.y + band.height as i32;
        for index in 0..self.toasts.len() {
            let top = bottom - ((index + 1) as i32 * self.row_height as i32);
            if pos.y >= top && pos.y < top + self.row_height as i32 {
                return Some(self.toasts.len() - 1 - index);
            }
        }
        None
    }
}

impl Widget for ToastStack {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(320, 200)
    }

    /// Advances the newest toast's rise-in; `true` while it still owes frames.
    fn tick(&mut self, delta_ms: u32) -> bool {
        self.reveal.tick(delta_ms)
    }

    fn is_animating(&self) -> bool {
        self.reveal.is_animating()
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `ToastStack`'s property contract.
///
/// `toast_count` and `selected_id` describe the live stack. `row_height` is the
/// one writable name here: the stack lays its toasts out bottom-up from the
/// geometry it was given, so its row height must stay adjustable when a host
/// changes density.
impl WidgetProperties for ToastStack {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "toast_count" => Ok(CapabilityValue::UInt(self.toasts().len() as u64)),
            "selected_id" => match self.selected_id() {
                Some(id) => Ok(CapabilityValue::String(id.to_string())),
                None => Ok(CapabilityValue::Null),
            },
            "row_height" => Ok(CapabilityValue::UInt(self.row_height as u64)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "row_height" => match value {
                CapabilityValue::UInt(height) => {
                    let height =
                        u32::try_from(height).map_err(|_| CapabilityAccessError::TypeMismatch)?;
                    self.row_height = height.max(1);
                    self.base.request_layout();
                    self.base.request_redraw();
                    Ok(())
                }
                _ => Err(CapabilityAccessError::TypeMismatch),
            },
            "toast_count" | "selected_id" => Err(CapabilityAccessError::ReadOnlyProperty),
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["toast_count", "selected_id", "row_height", BASE_PROPERTY_NAMES]
    }

    /// Runs one of the commands `toast_stack` publishes.
    ///
    /// `clear`, `activate_selected` and `dismiss_selected` are payload-free and
    /// map onto the widget's real methods; the two `*_selected` actions report
    /// `OutOfRange` when no toast is selected. `push` needs a whole `ToastItem`,
    /// and `select_index` an index, so those are answered as needing a payload.
    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        match name {
            "clear" => {
                self.clear();
                Ok(())
            }
            "activate_selected" => {
                if self.activate_selected() {
                    Ok(())
                } else {
                    Err(CapabilityAccessError::OutOfRange)
                }
            }
            "dismiss_selected" => {
                if self.dismiss_selected() {
                    Ok(())
                } else {
                    Err(CapabilityAccessError::OutOfRange)
                }
            }
            "push" | "select_index" => Err(CapabilityAccessError::OutOfRange),
            _ => Err(CapabilityAccessError::UnknownCommand),
        }
    }
}

impl EventHandler for ToastStack {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }

        match event {
            Event::MousePress { pos, button: 1 } => {
                if let Some(index) = self.row_at(*pos) {
                    let _ = self.select_index(index);
                    let _ = self.activate_selected();
                }
            }
            Event::KeyPress { key, modifiers: _ } => match *key {
                38 => {
                    if let Some(index) = self.selected_index {
                        if index > 0 {
                            let _ = self.select_index(index - 1);
                        }
                    }
                }
                40 => {
                    if let Some(index) = self.selected_index {
                        if index + 1 < self.toasts.len() {
                            let _ = self.select_index(index + 1);
                        }
                    }
                }
                13 => {
                    let _ = self.activate_selected();
                }
                46 => {
                    let _ = self.dismiss_selected();
                }
                // Unknown key; ignore
                _ => {}
            },
            // Other events are not relevant for this widget
            _ => {}
        }
    }
}

impl Draw for ToastStack {
    fn draw(&mut self, context: &mut RenderContext) {
        // Chrome colours resolve explicit style first, then the theme's resolved
        // style for this control, and only then a literal. The theme step is what
        // makes an appearance switch visible; previously every colour below was a
        // hardcoded literal, so light and dark rendered identically.
        //
        // `resolved_theme_style` takes and releases the global manager's lock
        // internally, so no guard is held across the draw (the mutex is not
        // re-entrant).
        let style = self.base.style().clone();
        let theme = crate::style::resolved_theme_style("toast_stack");
        // `toast_stack` is not a control kind in the role table, so it classifies as
        // `Surface`, whose background is `theme.colors.background` — byte-identical
        // to the window behind it. The stack's own fill is therefore a step toward
        // the foreground, so it reads as a surface of its own.
        let resolved = style
            .background_color
            .or_else(|| theme.as_ref().and_then(|t| t.background_color))
            .unwrap_or(Color::rgb(250, 251, 253));
        let border = style
            .border_color
            .or_else(|| theme.as_ref().and_then(|t| t.border_color))
            .unwrap_or_else(|| crate::core::Color::border_of(resolved));
        let text_color = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(Color::rgb(0, 0, 0));
        let background = resolved.blend(&text_color, 0.08);
        // Row chrome is derived from the resolved pair: the selected row reads as
        // tinted toward the text colour, an ordinary row more faintly.
        let selected_background = background.blend(&text_color, 0.14);
        let row_background = background.blend(&text_color, 0.05);
        let row_border = background.blend(&text_color, 0.2);

        // ── The stack actually painted ──
        //
        // The panel is the bottom-anchored region the rows occupy, not the whole rectangle: a
        // 240x120 census cell was a 120 px panel behind two 26 px rows. An empty stack paints
        // nothing, because a stack with no toasts has no bar to show.
        let band = self.stack_band();
        if band.height == 0 {
            return;
        }
        context.fill_rect(band, background);
        context.draw_rect(band, border);

        // Bottom-up: the newest toast is the lowest row, which is the end the stack grows from.
        let bottom = band.y + band.height as i32;
        for (index, item) in self.toasts.iter().enumerate() {
            let visual_order = self.toasts.len() - 1 - index;
            let y = bottom - ((visual_order + 1) as i32 * self.row_height as i32);
            if y < band.y {
                continue;
            }

            let row = Rect::new(
                band.x + 4,
                y + 2,
                band.width.saturating_sub(8),
                self.row_height.saturating_sub(4),
            );
            // # Why only the newest row moves
            //
            // The reveal is re-aimed on every `push`, so applying it to every row would make the
            // whole stack rise whenever one is added — the settled toasts would appear to be
            // re-arriving, which says the opposite of what happened. Only the row that was just
            // pushed is still on its way in, so only that one is offset; the rest are at rest by
            // definition.
            let is_arriving = index + 1 == self.toasts.len();
            let row = if is_arriving && self.reveal.is_animating() {
                // Rises from `row_height` below its seat to its seat, so a tall row travels
                // proportionally further than a short one rather than a fixed number of pixels.
                let offset = (self.row_height as f32 * (1.0 - self.reveal.value())) as i32;
                Rect::new(row.x, row.y + offset, row.width, row.height)
            } else {
                row
            };
            let bg = if self.selected_index == Some(index) {
                selected_background
            } else {
                row_background
            };
            context.fill_rect(row, bg);
            context.draw_rect(row, row_border);

            // The badge is a *state* indicator, so it reads the theme's semantic
            // tokens rather than a literal colour per level.
            let badge = crate::style::semantic_color(match item.level {
                ToastLevel::Info => crate::style::SemanticColor::Info,
                ToastLevel::Success => crate::style::SemanticColor::Success,
                ToastLevel::Warning => crate::style::SemanticColor::Warning,
                ToastLevel::Error => crate::style::SemanticColor::Error,
            })
            .map(|token| token.blend(&bg, 0.15))
            .unwrap_or_else(|| bg.blend(&text_color, 0.6));
            context.fill_rect(Rect::new(row.x + 6, row.y + 9, 8, 8), badge);
            context.draw_text(
                Point::new(row.x + 20, row.y + 17),
                &item.message,
                &Font::default(),
                text_color,
                HorizontalAlignment::Left,
            );
        }
    }
}