rust_widgets 2.0.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ 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
430
431
432
433
434
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! FAB (Floating Action Button) widget — a circular floating button for
//! primary actions.
//!
//! The FAB is a Material Design-style circular button that floats above the UI.
//! It displays an icon as a text character (e.g., "+") and supports press
//! animation, shadow, and click signal emission.

use crate::core::{Color, HorizontalAlignment, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::widget::capability::coercion::expect_string;
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::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// Floating Action Button widget.
///
/// A circular button with a background color (typically accent), an icon
/// rendered as centered text, a drop shadow, and a press animation that
/// briefly shrinks the button. Emits `clicked` on press-release.
pub struct FAB {
    base: BaseWidget,
    /// The icon text character displayed in the center (e.g. "+", "✕", "↓").
    icon_text: String,
    /// The fill color of the circular button.
    accent_color: Color,
    /// Whether this is a mini FAB (smaller size).
    mini: bool,
    /// Whether the button is currently pressed (for press animation).
    pressed: bool,
}

impl FAB {
    /// Creates a new FAB widget with the given geometry.
    ///
    /// Defaults: icon text "+", accent color `Color::PRIMARY`, normal size.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::FAB, geometry, "FAB"),
            icon_text: String::from("+"),
            accent_color: Color::PRIMARY,
            mini: false,
            pressed: false,
        }
    }

    /// Sets the icon text displayed in the center of the button.
    ///
    /// Common values: `"+"`, `"✕"`, `"↓"`, `"↑"`, `"✓"`, `"✎"`.
    pub fn set_icon_text(&mut self, text: &str) {
        self.icon_text = text.to_string();
        self.base.request_redraw();
    }

    /// Returns the current icon text.
    pub fn icon_text(&self) -> &str {
        &self.icon_text
    }

    /// Sets the accent (fill) color of the circular button.
    pub fn set_accent_color(&mut self, color: Color) {
        self.accent_color = color;
        self.base.request_redraw();
    }

    /// Returns the current accent color.
    pub fn accent_color(&self) -> Color {
        self.accent_color
    }

    /// Sets whether this FAB renders in mini (smaller) mode.
    ///
    /// Mini FABs are typically 40×40 instead of the standard 56×56.
    /// The geometry rect should be adjusted separately; this flag controls
    /// visual proportions like shadow offset and press scale factor.
    pub fn set_mini(&mut self, mini: bool) {
        self.mini = mini;
        self.base.request_redraw();
    }

    /// Returns whether this FAB is in mini mode.
    pub fn is_mini(&self) -> bool {
        self.mini
    }

    /// Programmatically trigger a click cycle (press then release).
    pub fn click(&mut self) {
        self.base.clicked.emit();
    }
}

impl Widget for FAB {
    fn base(&self) -> &BaseWidget {
        &self.base
    }

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

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(56, 56)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `FAB`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before.
impl WidgetProperties for FAB {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "icon" => Ok(CapabilityValue::String(self.icon_text().to_string())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "icon" => {
                self.set_icon_text(&expect_string(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

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

impl Draw for FAB {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        let dpi = self.base.dpi_scale();
        let is_enabled = self.base.is_enabled();

        // Compute button center and radius
        let cx = rect.x + (rect.width as i32) / 2;
        let cy = rect.y + (rect.height as i32) / 2;
        let base_radius = rect.width.min(rect.height) / 2;

        // When pressed, shrink by ~10% for press animation
        let (radius, shadow_offset) = if self.pressed && is_enabled {
            let shrunk = (base_radius as f32 * 0.9) as u32;
            (shrunk, (2.0 * dpi) as u32)
        } else {
            (base_radius, (3.0 * dpi) as u32)
        };

        let center = Point::new(cx, cy);

        // Draw shadow (offset darker circle underneath)
        let shadow_center =
            Point::new(cx + shadow_offset as i32 / 2, cy + shadow_offset as i32 / 2);
        let shadow_color = Color::rgba(0, 0, 0, 60);
        context.fill_circle_aa(shadow_center, radius, shadow_color);

        // Determine button fill color
        let fill_color = if !is_enabled {
            Color::rgba(self.accent_color.r, self.accent_color.g, self.accent_color.b, 120)
        } else {
            self.accent_color
        };

        // Draw filled circle
        context.fill_circle_aa(center, radius, fill_color);

        // Draw icon text centered in the button
        if !self.icon_text.is_empty() {
            // Use a default monospace-like font at a size proportional to button
            let font_size = if self.mini {
                (radius as f32 * 0.7).max(12.0)
            } else {
                (radius as f32 * 0.7).max(16.0)
            };
            use crate::core::Font;
            let font = Font::new("sans-serif", font_size, false, false);

            let metrics = context.measure_text(&self.icon_text, &font);
            let text_x = cx - (metrics.width as i32) / 2;
            let text_y = cy - (metrics.height as i32) / 2 + (metrics.ascent as i32);

            let text_color =
                if !is_enabled { Color::rgba(255, 255, 255, 120) } else { Color::WHITE };
            context.draw_text(
                Point::new(text_x, text_y),
                &self.icon_text,
                &font,
                text_color,
                HorizontalAlignment::Left,
            );
        }
    }
}

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

        match event {
            Event::MousePress { pos: _, button } => {
                if *button == 1 {
                    self.pressed = true;
                    self.base.request_redraw();
                }
            }
            Event::MouseRelease { pos: _, button } => {
                if *button == 1 && self.pressed {
                    self.pressed = false;
                    self.base.clicked.emit();
                    self.base.request_redraw();
                }
            }
            #[cfg(feature = "touch")]
            Event::TouchBegin { .. } => {
                self.pressed = true;
                self.base.request_redraw();
            }
            #[cfg(feature = "touch")]
            Event::TouchEnd { .. } => {
                if self.pressed {
                    self.pressed = false;
                    self.base.clicked.emit();
                    self.base.request_redraw();
                }
            }
            #[cfg(feature = "touch")]
            Event::Tap { .. } => {
                self.base.clicked.emit();
                self.base.request_redraw();
            }
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::svg::render_to_svg;
    use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };

    fn make_fab() -> FAB {
        FAB::new(Rect::new(0, 0, 56, 56))
    }

    #[test]
    fn fab_default_creation() {
        let fab = make_fab();
        assert_eq!(fab.kind(), WidgetKind::FAB);
        assert_eq!(fab.icon_text(), "+");
        assert_eq!(fab.accent_color(), Color::PRIMARY);
        assert!(!fab.is_mini());
        assert_eq!(fab.geometry(), Rect::new(0, 0, 56, 56));
        assert!(fab.is_visible());
        assert!(fab.is_enabled());
    }

    #[test]
    fn fab_icon_text() {
        let mut fab = make_fab();
        assert_eq!(fab.icon_text(), "+");

        fab.set_icon_text("");
        assert_eq!(fab.icon_text(), "");

        fab.set_icon_text("");
        assert_eq!(fab.icon_text(), "");
    }

    #[test]
    fn fab_accent_color() {
        let mut fab = make_fab();
        assert_eq!(fab.accent_color(), Color::PRIMARY);

        fab.set_accent_color(Color::ERROR);
        assert_eq!(fab.accent_color(), Color::ERROR);

        fab.set_accent_color(Color::SUCCESS);
        assert_eq!(fab.accent_color(), Color::SUCCESS);
    }

    #[test]
    fn fab_mini_mode() {
        let mut fab = make_fab();
        assert!(!fab.is_mini());

        fab.set_mini(true);
        assert!(fab.is_mini());

        fab.set_mini(false);
        assert!(!fab.is_mini());
    }

    #[test]
    fn fab_click_signal_emits() {
        let mut fab = make_fab();
        let clicked = Arc::new(AtomicBool::new(false));
        let c = clicked.clone();
        fab.clicked_signal().connect(move || {
            c.store(true, Ordering::SeqCst);
        });

        fab.click();
        assert!(clicked.load(Ordering::SeqCst));
    }

    #[test]
    fn fab_mouse_press_release_emits_clicked() {
        let mut fab = make_fab();
        let clicked = Arc::new(AtomicBool::new(false));
        let c = clicked.clone();
        fab.clicked_signal().connect(move || {
            c.store(true, Ordering::SeqCst);
        });

        fab.handle_event(&Event::MousePress { pos: Point::new(28, 28), button: 1 });
        assert!(fab.pressed);
        assert!(!clicked.load(Ordering::SeqCst));

        fab.handle_event(&Event::MouseRelease { pos: Point::new(28, 28), button: 1 });
        assert!(!fab.pressed);
        assert!(clicked.load(Ordering::SeqCst));
    }

    #[test]
    fn fab_mouse_press_release_other_button_noop() {
        let mut fab = make_fab();
        let clicked = Arc::new(AtomicBool::new(false));
        let c = clicked.clone();
        fab.clicked_signal().connect(move || {
            c.store(true, Ordering::SeqCst);
        });

        fab.handle_event(&Event::MousePress { pos: Point::new(28, 28), button: 2 });
        assert!(!fab.pressed);
        assert!(!clicked.load(Ordering::SeqCst));
    }

    #[test]
    fn fab_disabled_blocks_events() {
        let mut fab = make_fab();
        fab.set_enabled(false);

        let clicked = Arc::new(AtomicBool::new(false));
        let c = clicked.clone();
        fab.clicked_signal().connect(move || {
            c.store(true, Ordering::SeqCst);
        });

        fab.handle_event(&Event::MousePress { pos: Point::new(28, 28), button: 1 });
        assert!(!fab.pressed);

        fab.handle_event(&Event::MouseRelease { pos: Point::new(28, 28), button: 1 });
        assert!(!clicked.load(Ordering::SeqCst));
    }

    #[cfg(feature = "touch")]
    #[test]
    fn fab_tap_emits_clicked() {
        let mut fab = make_fab();
        let clicked = Arc::new(AtomicBool::new(false));
        let c = clicked.clone();
        fab.clicked_signal().connect(move || {
            c.store(true, Ordering::SeqCst);
        });

        fab.handle_event(&Event::Tap { pos: Point::new(28, 28) });
        assert!(clicked.load(Ordering::SeqCst));
    }

    #[test]
    fn fab_svg_output() {
        let mut fab = make_fab();
        let svg = render_to_svg(&mut fab);
        assert!(svg.starts_with("<svg"));
        assert!(svg.ends_with("</svg>"));
        assert!(svg.contains("width=\"56\""));
        assert!(svg.contains("height=\"56\""));
    }

    #[test]
    fn fab_svg_output_mini() {
        let mut fab = FAB::new(Rect::new(0, 0, 40, 40));
        fab.set_mini(true);
        let svg = render_to_svg(&mut fab);
        assert!(svg.starts_with("<svg"));
        assert!(svg.contains("width=\"40\""));
        assert!(svg.contains("height=\"40\""));
    }

    #[test]
    fn fab_press_animation_sets_pressed_state() {
        let mut fab = make_fab();
        assert!(!fab.pressed);

        fab.handle_event(&Event::MousePress { pos: Point::new(28, 28), button: 1 });
        assert!(fab.pressed);

        fab.handle_event(&Event::MouseRelease { pos: Point::new(28, 28), button: 1 });
        assert!(!fab.pressed);
    }

    #[test]
    fn fab_clicked_signal_accessor() {
        let fab = make_fab();
        let signal = fab.clicked_signal();
        // Signal should be valid and connectable
        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        signal.connect(move || {
            f.store(true, Ordering::SeqCst);
        });
        signal.emit();
        assert!(fired.load(Ordering::SeqCst));
    }
}