rust_widgets 2.7.0

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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! CupertinoNavigationBar — iOS-style large title navigation bar.
//!
//! An iOS-style navigation bar with optional large title (similar to the
//! iOS 13+ large title nav bar), back button with arrow, and translucent
//! background effect.

use crate::core::{Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::widget::capability::coercion::{expect_bool, 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::metrics::{dimensions, ControlMetrics};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// The width of a Cupertino navigation bar's leading back-control area.
///
/// The affordance is the arrow plus a short label ("Back"), so it is fixed rather than
/// proportional: a bar twice as wide does not make the back control twice as wide.
const BACK_BUTTON_WIDTH: u32 = 80;

/// iOS-style large title navigation bar.
///
/// Renders a translucent background with an optional large title and a
/// back button. Emits `back_pressed` when the back button is clicked.
pub struct CupertinoNavigationBar {
    base: BaseWidget,
    title: String,
    large_title: bool,
    back_button_visible: bool,
    back_button_text: String,
    /// Emitted when the back button is pressed.
    pub back_pressed: Signal1<()>,
}

impl CupertinoNavigationBar {
    /// Creates a new CupertinoNavigationBar with the given geometry.
    pub fn new(geometry: Rect) -> Self {
        let base =
            BaseWidget::new(WidgetKind::CupertinoNavigationBar, geometry, "CupertinoNavigationBar");
        Self {
            base,
            title: String::new(),
            large_title: true,
            back_button_visible: false,
            back_button_text: "Back".to_string(),
            back_pressed: Signal1::new(),
        }
    }

    /// Sets whether the back button is visible.
    pub fn show_back_button(&mut self, visible: bool) {
        self.back_button_visible = visible;
        self.base.request_redraw();
    }

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

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

    /// Returns whether large title mode is enabled.
    pub fn is_large_title(&self) -> bool {
        self.large_title
    }

    /// Enables or disables large title mode.
    pub fn set_large_title(&mut self, enabled: bool) {
        self.large_title = enabled;
        self.base.request_redraw();
    }

    /// Returns whether the back button is visible.
    pub fn is_back_button_visible(&self) -> bool {
        self.back_button_visible
    }

    /// Sets the text for the back button.
    pub fn set_back_button_text(&mut self, text: &str) {
        self.back_button_text = text.to_string();
        self.base.request_redraw();
    }

    /// Returns the back button text.
    pub fn back_button_text(&self) -> &str {
        &self.back_button_text
    }
}

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

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

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

    fn kind(&self) -> WidgetKind {
        WidgetKind::CupertinoNavigationBar
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `CupertinoNavigationBar`'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. Both properties now report
/// the bar's real state instead of the placeholder defaults that dispatch
/// returned.
impl WidgetProperties for CupertinoNavigationBar {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "title" => Ok(CapabilityValue::String(self.title().to_string())),
            "large_title" => Ok(CapabilityValue::Bool(self.is_large_title())),
            _ => base_property_get(self, name),
        }
    }

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

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

impl Draw for CupertinoNavigationBar {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        if rect.width == 0 || rect.height == 0 {
            return;
        }

        // Chrome colours resolve explicit style first, then the theme's resolved style for
        // this control, and only then fall back to a literal. Every colour below used to be
        // a literal, so a light/dark switch left the bar, its rule, its title and its back
        // affordance unchanged — the rendering census reported the control as theme-blind.
        //
        // The theme read is a separate manager lock, taken and released inside
        // `resolved_theme_style`, so it is not held across the draw — the global manager's
        // mutex is not re-entrant.
        let style = self.base.style().clone();
        let theme = crate::style::resolved_theme_style("cupertino_navigation_bar");
        // Read as its own lock acquisition and copied out as values, so the guard is dropped
        // before anything else touches the theme. The bar is not in the role table, so it
        // classifies as `Surface` and its resolved background is the window fill itself; the
        // bar below therefore derives its own distinct surface rather than painting the
        // window's. The back affordance is iOS blue only because it used to be hardcoded — it
        // is the bar's action colour, so it reads the theme's primary token.
        let (window_fill, foreground, primary) = {
            let manager = crate::style::theme_manager();
            match manager.current_theme() {
                Some(active) => {
                    (active.colors.background, active.colors.foreground, active.colors.primary)
                }
                None => (Color::rgb(240, 240, 240), Color::BLACK, Color::rgb(0, 122, 255)),
            }
        };

        let ink = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(foreground);
        // A translucent fill cannot tint anything on this surface: `fill_rect` writes raw
        // pixels, so `rgba(255, 255, 255, 230)` *replaced* the page with white at alpha 230
        // instead of frosting it, and the bar kept that colour through a theme switch. Mixing
        // the bar's own surface with the page it covers produces the same translucent
        // appearance with an opaque result that follows the appearance.
        //
        // The filter is on the **resolved** value, not only on the theme's: the active theme
        // is applied to every control before it is drawn, so `style.background_color` already
        // holds `Surface`'s window fill and letting it through unfiltered is exactly the
        // invisible-bar defect this guards against. A caller's own colour still wins.
        let bar_from_theme = window_fill.blend(&ink, 0.06);
        let bar_surface = match style.background_color {
            Some(resolved) if resolved != window_fill => resolved,
            _ => bar_from_theme,
        };
        let bar = bar_surface.blend(&window_fill, 0.10);
        // ── The bar actually painted ──
        //
        // `rect` is the area the control was *given*; a navigation bar is a strip pinned to the
        // **top** of that area, [`dimensions::NAV_BAR_HEIGHT`] tall in compact mode and
        // [`dimensions::NAV_BAR_LARGE_HEIGHT`] in large-title mode. Filling the whole rectangle
        // made a 240x120 census cell a 120 px navigation bar whose compact title sat at `y + 22`
        // — a third of the way down a bar three times its proper height — and it put the bottom
        // rule on the *canvas* edge rather than on the bar's. `top_band` is the shared
        // derivation for "a strip pinned to my top edge", and the hit test below reads the same
        // band so the back affordance and its ink cannot part company.
        let bar_height = if self.large_title {
            dimensions::NAV_BAR_LARGE_HEIGHT
        } else {
            dimensions::NAV_BAR_HEIGHT
        };
        let bar_rect = ControlMetrics::top_band(rect, bar_height);
        context.fill_rect(bar_rect, bar);

        // ── Bottom border line ──
        // A `Surface` role resolves no border colour, so the rule is derived one visible
        // step from the bar and a caller's explicit border still wins.
        let border = style
            .border_color
            .or_else(|| theme.as_ref().and_then(|t| t.border_color))
            .filter(|resolved| *resolved != bar)
            .unwrap_or_else(|| bar.blend(&ink, 0.20));
        let border_y = bar_rect.y + bar_rect.height as i32 - 1;
        context.draw_line(
            Point::new(bar_rect.x, border_y),
            Point::new(bar_rect.x + bar_rect.width as i32, border_y),
            border,
        );

        if self.large_title {
            // ── Large title ──
            let title_font = Font::new("sans-serif", 34.0, true, false);
            if !self.title.is_empty() {
                let metrics = context.measure_text(&self.title, &title_font);
                let title_x = bar_rect.x + 16;
                // Centre the large title on the bar. The origin is the glyph box's top edge,
                // so the offset is half the *line box*; the `ascent / 2` term began the glyph
                // box half a line below the middle.
                let title_y = bar_rect.y + (bar_rect.height as i32 - metrics.height as i32) / 2;
                context.draw_text(
                    Point::new(title_x, title_y),
                    &self.title,
                    &title_font,
                    ink,
                    HorizontalAlignment::Left,
                );
            }
        } else {
            // ── Compact title (centered in navigation bar area) ──
            let title_font = Font::new("sans-serif", 18.0, false, false);
            if !self.title.is_empty() {
                let metrics = context.measure_text(&self.title, &title_font);
                let title_x = bar_rect.x + (bar_rect.width as i32 - metrics.width as i32) / 2;
                // Vertically centred through the shared primitive, so the title sits on the
                // compact bar's middle line whatever height the band was clamped to; the `+ 22`
                // it replaces was a literal for the 44 px bar and landed elsewhere on any other.
                let line = context.text_line(bar_rect, &title_font);
                context.draw_text(
                    Point::new(title_x, line.y),
                    &self.title,
                    &title_font,
                    ink,
                    HorizontalAlignment::Left,
                );
            }
        }

        // ── Back button (left side) ──
        if self.back_button_visible {
            let arrow_font = Font::new("sans-serif", 20.0, false, false);
            let label_font = Font::new("sans-serif", 17.0, false, false);
            let arrow_symbol = "\u{2190}"; // ←
                                           // The affordance sits on the bar, so the theme's primary is contrast-checked
                                           // against it rather than assumed legible.
            let action = primary.contrast_color().blend(&primary, 0.85);

            let arrow_metrics = context.measure_text(arrow_symbol, &arrow_font);
            let arrow_x = bar_rect.x + 8;
            // On the compact bar's own middle line, shared with the title; the removed
            // `+ 22` was a literal for the 44 px bar.
            let arrow_line = context.text_line(bar_rect, &arrow_font);

            // Draw arrow
            context.draw_text(
                Point::new(arrow_x, arrow_line.y),
                arrow_symbol,
                &arrow_font,
                action,
                HorizontalAlignment::Left,
            );

            // Draw text label next to arrow
            if !self.back_button_text.is_empty() {
                let label_x = arrow_x + arrow_metrics.width as i32 + 4;
                // Reads as a small title and shares the compact bar's middle line with the
                // title and the arrow; no literal offset, which had moved it with the bar's
                // height rather than its own line.
                let label_line = context.text_line(bar_rect, &label_font);
                context.draw_text(
                    Point::new(label_x, label_line.y),
                    &self.back_button_text,
                    &label_font,
                    action,
                    HorizontalAlignment::Left,
                );
            }
        }
    }
}

impl EventHandler for CupertinoNavigationBar {
    fn handle_event(&mut self, event: &Event) {
        match event {
            Event::MouseRelease { pos, button } => {
                // A disabled nav bar must not emit navigation. Without this,
                // `set_enabled(false)` had no effect: the back button still fired.
                if !self.base.is_enabled() {
                    self.base.handle_event(event);
                    return;
                }
                if *button != 1 {
                    return;
                }

                // Only handle back button area clicks
                if !self.back_button_visible {
                    return;
                }

                // The back area is the leading end of the bar itself, so it tracks the band the
                // bar is painted in rather than a fixed 80x44 literal: the clickable region and
                // the ink the user aims at are the same rectangle by construction.
                let rect = self.geometry();
                let bar_height = if self.large_title {
                    dimensions::NAV_BAR_LARGE_HEIGHT
                } else {
                    dimensions::NAV_BAR_HEIGHT
                };
                let bar_rect = ControlMetrics::top_band(rect, bar_height);
                let back_area =
                    Rect::new(bar_rect.x, bar_rect.y, BACK_BUTTON_WIDTH, bar_rect.height);
                if back_area.contains_point(*pos) {
                    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,
    };

    #[test]
    fn cupertino_nav_bar_creation() {
        let bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
        assert_eq!(bar.kind(), WidgetKind::CupertinoNavigationBar);
        assert!(bar.title().is_empty());
        assert!(bar.is_large_title());
        assert!(!bar.is_back_button_visible());
    }

    #[test]
    fn cupertino_nav_bar_title_accessors() {
        let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
        bar.set_title("Home");
        assert_eq!(bar.title(), "Home");
    }

    #[test]
    fn cupertino_nav_bar_back_button_visibility() {
        let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
        assert!(!bar.is_back_button_visible());

        bar.show_back_button(true);
        assert!(bar.is_back_button_visible());

        bar.show_back_button(false);
        assert!(!bar.is_back_button_visible());
    }

    #[test]
    fn cupertino_nav_bar_large_title_toggle() {
        let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
        assert!(bar.is_large_title());

        bar.set_large_title(false);
        assert!(!bar.is_large_title());

        bar.set_large_title(true);
        assert!(bar.is_large_title());
    }

    #[test]
    fn cupertino_nav_bar_back_button_text() {
        let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
        assert_eq!(bar.back_button_text(), "Back");

        bar.set_back_button_text("Settings");
        assert_eq!(bar.back_button_text(), "Settings");
    }

    #[test]
    fn cupertino_nav_bar_back_pressed_signal() {
        let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
        bar.show_back_button(true);

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

        // Click on back button area
        bar.handle_event(&Event::MouseRelease { pos: Point::new(20, 22), button: 1 });
        assert!(fired.load(Ordering::SeqCst));
    }

    /// A disabled nav bar must not emit `back_pressed`.
    ///
    /// `handle_event` went straight to the hit test, so `set_enabled(false)` had no
    /// effect on this widget: the back affordance still fired navigation. Every
    /// interactive widget in the crate gates on `is_enabled()` first, so a missing
    /// gate turns `set_enabled` into a silent no-op rather than a policy choice.
    #[test]
    fn cupertino_nav_bar_disabled_ignores_back_click() {
        let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
        bar.show_back_button(true);
        bar.set_enabled(false);

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

        bar.handle_event(&Event::MouseRelease { pos: Point::new(20, 22), button: 1 });
        assert!(!fired.load(Ordering::SeqCst), "a disabled nav bar must not navigate");
    }

    #[test]
    fn cupertino_nav_bar_back_pressed_not_fired_when_hidden() {
        let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
        // back_button_visible is false by default

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

        // Click where back button would be
        bar.handle_event(&Event::MouseRelease { pos: Point::new(20, 22), button: 1 });
        assert!(!fired.load(Ordering::SeqCst));
    }

    #[test]
    fn cupertino_nav_bar_svg_output() {
        let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 375, 96));
        bar.set_title("Settings");
        bar.show_back_button(true);
        let svg = render_to_svg(&mut bar);
        assert!(svg.starts_with("<svg"));
    }

    /// The bar is a top-anchored strip, and its rule sits on the bar's own bottom edge.
    ///
    /// The defect this pins: the bar filled its whole rectangle, so a 240x120 census cell was
    /// a 120 px navigation bar whose compact title sat at a literal `y + 22` — a third of the
    /// way down a bar three times its proper height — and whose bottom rule landed on the
    /// *canvas* edge rather than the bar's own.
    #[test]
    fn the_bar_is_a_top_strip_that_keeps_its_own_height() {
        use crate::widget::metrics::{dimensions, ControlMetrics};
        for height in [96u32, 120, 300] {
            let mut bar = CupertinoNavigationBar::new(Rect::new(0, 0, 240, height));
            bar.set_title("Settings");
            // The large-title bar is the taller of the two modes.
            let band = ControlMetrics::top_band(
                Rect::new(0, 0, 240, height),
                dimensions::NAV_BAR_LARGE_HEIGHT,
            );
            let svg = render_to_svg(&mut bar);
            let fill = format!("x=\"0\" y=\"0\" width=\"240\" height=\"{}\"", band.height);
            assert!(
                svg.contains(&fill),
                "at control height {height} the bar must be {band:?}, in:\n{svg}"
            );
            // And the rule is on the bar, not on the canvas.
            let rule = format!(
                "x1=\"0\" y1=\"{}\" x2=\"240\" y2=\"{}\"",
                band.y + band.height as i32 - 1,
                band.y + band.height as i32 - 1
            );
            assert!(svg.contains(&rule), "the rule must sit on the bar's bottom edge:\n{svg}");
        }
    }
}