rust_widgets 0.9.6

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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! AppBar (Top Bar) widget — a mobile-style top navigation bar with title,
//! optional back button, and optional action text.
//!
//! The AppBar is a Material Design-inspired top app bar that displays a title
//! centered in the bar, an optional back arrow (←) on the left, and optional
//! action text on the right. It emits `back_pressed` when the back area is
//! tapped and `action_pressed` when the action area is tapped.

use crate::core::{Color, Font, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::GenericSignal;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};

/// AppBar / Top Bar widget — mobile-style top navigation bar.
///
/// Displays a title centered in the bar, an optional back arrow (←) on the
/// left, and optional action text on the right. Emits signals when the back
/// or action areas are pressed.
pub struct AppBar {
    base: BaseWidget,
    /// The title text centered in the bar.
    title: String,
    /// Whether to show the back arrow (←) on the left side.
    show_back: bool,
    /// Optional action text displayed on the right side.
    action_text: String,
    /// Emitted when the back arrow area is pressed.
    pub back_pressed: GenericSignal,
    /// Emitted when the action text area is pressed.
    pub action_pressed: GenericSignal,
}

impl AppBar {
    /// Creates a new AppBar widget with the given title and geometry.
    ///
    /// By default, the back arrow is hidden and the action text is empty.
    pub fn new(title: &str, geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::AppBar, geometry, "AppBar"),
            title: title.to_string(),
            show_back: false,
            action_text: String::new(),
            back_pressed: GenericSignal::new(),
            action_pressed: GenericSignal::new(),
        }
    }

    /// Sets the title text displayed centered in the bar.
    pub fn set_title(&mut self, title: &str) {
        self.title = title.to_string();
        self.base.request_redraw();
    }

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

    /// Sets whether the back arrow (←) is shown on the left side.
    pub fn set_show_back(&mut self, show_back: bool) {
        self.show_back = show_back;
        self.base.request_redraw();
    }

    /// Returns whether the back arrow is currently shown.
    pub fn show_back(&self) -> bool {
        self.show_back
    }

    /// Sets the action text displayed on the right side.
    ///
    /// Pass an empty string to hide the action area.
    pub fn set_action_text(&mut self, text: &str) {
        self.action_text = text.to_string();
        self.base.request_redraw();
    }

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

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

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

impl Draw for AppBar {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        let is_enabled = self.base.is_enabled();
        let bar_height = rect.height;

        // Draw background
        let bg_color =
            if is_enabled { Color::rgba(248, 248, 250, 255) } else { Color::DISABLED_BACKGROUND };
        context.fill_rect(rect, bg_color);

        // Draw bottom border line
        let border_y = rect.y + bar_height as i32 - 1;
        context.draw_line_stroke(
            Point::new(rect.x, border_y),
            Point::new(rect.x + rect.width as i32, border_y),
            Color::DIVIDER,
            1,
        );

        // Determine font sizes based on bar height
        let title_font_size = (bar_height as f32 * 0.38).clamp(14.0, 22.0);
        let action_font_size = (bar_height as f32 * 0.32).clamp(12.0, 18.0);

        // ── Back arrow (left side) ──
        if self.show_back {
            let back_font = Font::new("sans-serif", action_font_size + 2.0, false, false);
            let back_text = "";
            let metrics = context.measure_text(back_text, &back_font);
            // Left margin: ~12px, back arrow centered vertically
            let back_x = rect.x + 12;
            let back_y = rect.y + (bar_height as i32 / 2) + (metrics.ascent as i32 / 2)
                - (metrics.descent as i32 / 2);
            let back_color =
                if is_enabled { Color::FOREGROUND } else { Color::DISABLED_FOREGROUND };
            context.draw_text(Point::new(back_x, back_y), back_text, &back_font, back_color);
        }

        // ── Centered title ──
        if !self.title.is_empty() {
            let title_font = Font::new("sans-serif", title_font_size, false, false);
            let metrics = context.measure_text(&self.title, &title_font);

            // Compute available width: reserve space for back (40px) and action (80px)
            let left_reserve = if self.show_back { 40 } else { 16 };
            let right_reserve = if self.action_text.is_empty() { 16 } else { 80 };
            let available_width = rect.width as i32 - left_reserve - right_reserve;
            let title_width = metrics.width as i32;

            let title_x = if title_width > available_width {
                // Overflow: left-align with left margin
                rect.x + left_reserve
            } else {
                // Center
                rect.x + (rect.width as i32 / 2) - (title_width / 2)
            };
            let title_y = rect.y + (bar_height as i32 / 2) + (metrics.ascent as i32 / 2)
                - (metrics.descent as i32 / 2);

            let title_color =
                if is_enabled { Color::FOREGROUND } else { Color::DISABLED_FOREGROUND };
            context.draw_text(Point::new(title_x, title_y), &self.title, &title_font, title_color);
        }

        // ── Action text (right side) ──
        if !self.action_text.is_empty() {
            let action_font = Font::new("sans-serif", action_font_size, false, false);
            let metrics = context.measure_text(&self.action_text, &action_font);

            // Right margin: ~16px
            let action_x = rect.x + rect.width as i32 - metrics.width as i32 - 16;
            let action_y = rect.y + (bar_height as i32 / 2) + (metrics.ascent as i32 / 2)
                - (metrics.descent as i32 / 2);

            let action_color = if is_enabled { Color::PRIMARY } else { Color::DISABLED_FOREGROUND };
            context.draw_text(
                Point::new(action_x, action_y),
                &self.action_text,
                &action_font,
                action_color,
            );
        }
    }
}

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

        match event {
            Event::MousePress { pos, button } | Event::MouseRelease { pos, button } => {
                if *button != 1 {
                    return;
                }
                let rect = self.geometry();

                // Determine tap zone
                // Left zone (back arrow): first 48px if show_back
                // Right zone (action): last 80px if action_text is non-empty
                // Title/general area: middle (handled below)

                if self.show_back && pos.x >= rect.x && pos.x <= rect.x + 48 {
                    self.back_pressed.emit();
                    self.base.request_redraw();
                    return;
                }

                if !self.action_text.is_empty()
                    && pos.x >= rect.x + rect.width as i32 - 80
                    && pos.x <= rect.x + rect.width as i32
                {
                    self.action_pressed.emit();
                    self.base.request_redraw();
                    return;
                }

                // If neither back nor action matched, treat as back when show_back,
                // otherwise as general click on the bar.
                if self.show_back {
                    self.back_pressed.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_app_bar() -> AppBar {
        AppBar::new("Home", Rect::new(0, 0, 375, 56))
    }

    #[test]
    fn app_bar_default_creation() {
        let bar = make_app_bar();
        assert_eq!(bar.kind(), WidgetKind::AppBar);
        assert_eq!(bar.title(), "Home");
        assert!(!bar.show_back());
        assert_eq!(bar.action_text(), "");
        assert!(bar.is_visible());
        assert!(bar.is_enabled());
        assert_eq!(bar.geometry(), Rect::new(0, 0, 375, 56));
    }

    #[test]
    fn app_bar_title_accessors() {
        let mut bar = make_app_bar();
        assert_eq!(bar.title(), "Home");

        bar.set_title("Settings");
        assert_eq!(bar.title(), "Settings");

        bar.set_title("");
        assert_eq!(bar.title(), "");
    }

    #[test]
    fn app_bar_show_back_accessors() {
        let mut bar = make_app_bar();
        assert!(!bar.show_back());

        bar.set_show_back(true);
        assert!(bar.show_back());

        bar.set_show_back(false);
        assert!(!bar.show_back());
    }

    #[test]
    fn app_bar_action_text_accessors() {
        let mut bar = make_app_bar();
        assert_eq!(bar.action_text(), "");

        bar.set_action_text("Save");
        assert_eq!(bar.action_text(), "Save");

        bar.set_action_text("");
        assert_eq!(bar.action_text(), "");
    }

    #[test]
    fn app_bar_back_pressed_signal_emits_on_left_tap() {
        let mut bar = make_app_bar();
        bar.set_show_back(true);

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        bar.back_pressed.connect(move || {
            f.store(true, Ordering::SeqCst);
        });

        // Tap in left zone (first 48px)
        bar.handle_event(&Event::MousePress { pos: Point::new(10, 28), button: 1 });
        assert!(fired.load(Ordering::SeqCst));
    }

    #[test]
    fn app_bar_back_pressed_emits_on_center_tap_when_back_shown() {
        let mut bar = make_app_bar();
        bar.set_show_back(true);

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        bar.back_pressed.connect(move || {
            f.store(true, Ordering::SeqCst);
        });

        // Tap in center — falls through to back when show_back is true
        bar.handle_event(&Event::MousePress { pos: Point::new(188, 28), button: 1 });
        assert!(fired.load(Ordering::SeqCst));
    }

    #[test]
    fn app_bar_action_pressed_signal_emits_on_right_tap() {
        let mut bar = make_app_bar();
        bar.set_action_text("Save");

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        bar.action_pressed.connect(move || {
            f.store(true, Ordering::SeqCst);
        });

        // Tap in right action zone (last 80px)
        bar.handle_event(&Event::MousePress { pos: Point::new(340, 28), button: 1 });
        assert!(fired.load(Ordering::SeqCst));
    }

    #[test]
    fn app_bar_action_pressed_not_emitted_on_center_tap() {
        let mut bar = make_app_bar();
        bar.set_action_text("Save");
        bar.set_show_back(true);

        let action_fired = Arc::new(AtomicBool::new(false));
        let a = action_fired.clone();
        bar.action_pressed.connect(move || {
            a.store(true, Ordering::SeqCst);
        });

        // Tap in center — action should NOT fire
        bar.handle_event(&Event::MousePress { pos: Point::new(188, 28), button: 1 });
        assert!(!action_fired.load(Ordering::SeqCst));
    }

    #[test]
    fn app_bar_disabled_blocks_events() {
        let mut bar = make_app_bar();
        bar.set_show_back(true);
        bar.set_enabled(false);
        bar.set_action_text("Save");

        let back_fired = Arc::new(AtomicBool::new(false));
        let b = back_fired.clone();
        bar.back_pressed.connect(move || {
            b.store(true, Ordering::SeqCst);
        });

        let action_fired = Arc::new(AtomicBool::new(false));
        let a = action_fired.clone();
        bar.action_pressed.connect(move || {
            a.store(true, Ordering::SeqCst);
        });

        bar.handle_event(&Event::MousePress { pos: Point::new(10, 28), button: 1 });
        assert!(!back_fired.load(Ordering::SeqCst));
        assert!(!action_fired.load(Ordering::SeqCst));
    }

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

    #[test]
    fn app_bar_svg_with_back_and_action() {
        let mut bar = make_app_bar();
        bar.set_show_back(true);
        bar.set_action_text("Cancel");
        let svg = render_to_svg(&mut bar);
        assert!(svg.starts_with("<svg"));
        assert!(svg.contains("width=\"375\""));
        assert!(svg.contains("height=\"56\""));
    }

    #[test]
    fn app_bar_back_pressed_signal_accessor() {
        let bar = make_app_bar();
        let signal = &bar.back_pressed;
        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));
    }

    #[test]
    fn app_bar_action_pressed_signal_accessor() {
        let bar = make_app_bar();
        let signal = &bar.action_pressed;
        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));
    }

    #[test]
    fn app_bar_other_button_noop() {
        let mut bar = make_app_bar();
        bar.set_show_back(true);

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        bar.back_pressed.connect(move || {
            f.store(true, Ordering::SeqCst);
        });

        // Right-button click should be ignored
        bar.handle_event(&Event::MousePress { pos: Point::new(10, 28), button: 2 });
        assert!(!fired.load(Ordering::SeqCst));
    }

    #[test]
    fn app_bar_release_also_emits() {
        let mut bar = make_app_bar();
        bar.set_show_back(true);

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        bar.back_pressed.connect(move || {
            f.store(true, Ordering::SeqCst);
        });

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