Skip to main content

waft_widgets/widgets/
banner.rs

1//! Flutter `widgets/banner.dart`.
2
3use std::any::Any;
4use std::cell::RefCell;
5use std::f64::consts::{FRAC_1_SQRT_2, PI};
6use std::fmt::{self, Debug};
7use std::rc::Rc;
8
9use waft_embedder::{
10    BlurStyle, Canvas, Color, FontWeight, Offset, Paint, Rect, Size, TextAlign, TextDirection,
11};
12use waft_foundation::{App, DiagnosticPropertiesBuilder, EnumProperty, Handle, StringProperty};
13use waft_painting::{BoxShadow, ColorProperty, PaintingBinding, TextPainter, TextSpan, TextStyle};
14use waft_rendering::CustomPainter;
15
16use crate::framework::{
17    BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, StatelessWidget, WidgetRef,
18};
19use crate::widgets::basic::{CustomPaint, Directionality};
20
21/// Distance to bottom of banner, at a 45 degree angle inwards.
22const K_OFFSET: f64 = 40.0;
23/// Height of banner.
24const K_HEIGHT: f64 = 12.0;
25const K_BOTTOM_OFFSET: f64 = K_OFFSET + FRAC_1_SQRT_2 * K_HEIGHT;
26const K_RECT: Rect = Rect::from_ltwh(-K_OFFSET, K_OFFSET - K_HEIGHT, K_OFFSET * 2.0, K_HEIGHT);
27const K_COLOR: Color = Color::new(0xA0B7_1C1C);
28
29fn k_shadow() -> BoxShadow {
30    BoxShadow::new(
31        Color::new(0x7F00_0000),
32        Offset::ZERO,
33        6.0,
34        0.0,
35        BlurStyle::Normal,
36    )
37}
38
39fn k_text_style() -> TextStyle {
40    TextStyle::new()
41        .color(Color::new(0xFFFF_FFFF))
42        .font_size(K_HEIGHT * 0.85)
43        .font_weight(FontWeight::W900)
44        .height(1.0)
45}
46
47/// Where to show a [`Banner`].
48///
49/// The start and end locations are relative to the ambient [`Directionality`]
50/// (which can be overridden by [`Banner::layout_direction`]).
51#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
52pub enum BannerLocation {
53    /// Show the banner in the top-right corner when the ambient [`Directionality`]
54    /// (or [`Banner::layout_direction`]) is [`TextDirection::Rtl`] and in the
55    /// top-left corner when the ambient [`Directionality`] is
56    /// [`TextDirection::Ltr`].
57    TopStart,
58    /// Show the banner in the top-left corner when the ambient [`Directionality`]
59    /// (or [`Banner::layout_direction`]) is [`TextDirection::Rtl`] and in the
60    /// top-right corner when the ambient [`Directionality`] is
61    /// [`TextDirection::Ltr`].
62    TopEnd,
63    /// Show the banner in the bottom-right corner when the ambient
64    /// [`Directionality`] (or [`Banner::layout_direction`]) is
65    /// [`TextDirection::Rtl`] and in the bottom-left corner when the ambient
66    /// [`Directionality`] is [`TextDirection::Ltr`].
67    BottomStart,
68    /// Show the banner in the bottom-left corner when the ambient
69    /// [`Directionality`] (or [`Banner::layout_direction`]) is
70    /// [`TextDirection::Rtl`] and in the bottom-right corner when the ambient
71    /// [`Directionality`] is [`TextDirection::Ltr`].
72    BottomEnd,
73}
74
75/// Paints a [`Banner`].
76pub struct BannerPainter {
77    /// The message to show in the banner.
78    pub message: String,
79    /// The directionality of the text.
80    ///
81    /// This value is used to disambiguate how to render bidirectional text. For
82    /// example, if the message is an English phrase followed by a Hebrew phrase,
83    /// in a [`TextDirection::Ltr`] context the English phrase will be on the left
84    /// and the Hebrew phrase to its right, while in a [`TextDirection::Rtl`]
85    /// context, the English phrase will be on the right and the Hebrew phrase on
86    /// its left.
87    ///
88    /// See also [`layout_direction`](Self::layout_direction), which controls the
89    /// interpretation of values in [`location`](Self::location).
90    pub text_direction: TextDirection,
91    /// Where to show the banner (e.g., the upper right corner).
92    pub location: BannerLocation,
93    /// The directionality of the layout.
94    ///
95    /// This value is used to interpret the [`location`](Self::location) of the banner.
96    ///
97    /// See also [`text_direction`](Self::text_direction), which controls the
98    /// reading direction of the [`message`](Self::message).
99    pub layout_direction: TextDirection,
100    /// The color to paint behind the [`message`](Self::message).
101    ///
102    /// Defaults to a dark red.
103    pub color: Color,
104    /// The text style to use for the [`message`](Self::message).
105    ///
106    /// Defaults to bold, white text.
107    pub text_style: TextStyle,
108    /// The shadow of the banner.
109    pub shadow: BoxShadow,
110    /// Dart's `_prepared`, `_textPainter`, `_paintShadow` and `_paintBanner`, filled on the
111    /// first paint.
112    prepared: RefCell<Option<Prepared>>,
113}
114
115struct Prepared {
116    text_painter: TextPainter,
117    paint_shadow: Paint,
118    paint_banner: Paint,
119}
120
121impl BannerPainter {
122    /// Creates a banner painter.
123    pub fn new(
124        message: impl Into<String>,
125        text_direction: TextDirection,
126        location: BannerLocation,
127        layout_direction: TextDirection,
128    ) -> BannerPainter {
129        BannerPainter {
130            message: message.into(),
131            text_direction,
132            location,
133            layout_direction,
134            color: K_COLOR,
135            text_style: k_text_style(),
136            shadow: k_shadow(),
137            prepared: RefCell::new(None),
138        }
139    }
140
141    /// Dart `BannerPainter(color:)`.
142    pub fn color(mut self, color: Color) -> BannerPainter {
143        self.color = color;
144        self
145    }
146
147    /// Dart `BannerPainter(textStyle:)`.
148    pub fn text_style(mut self, text_style: TextStyle) -> BannerPainter {
149        self.text_style = text_style;
150        self
151    }
152
153    /// Dart `BannerPainter(shadow:)`.
154    pub fn shadow(mut self, shadow: BoxShadow) -> BannerPainter {
155        self.shadow = shadow;
156        self
157    }
158
159    /// Release resources held by this painter.
160    ///
161    /// After calling this method, this object is no longer usable.
162    pub fn dispose(&self) {
163        self.prepared.borrow_mut().take();
164    }
165
166    fn prepare(&self) -> Prepared {
167        let mut text_painter = TextPainter::new();
168        text_painter.set_text(Some(Rc::new(
169            TextSpan::new()
170                .style(self.text_style.clone())
171                .text(self.message.clone()),
172        )));
173        text_painter.set_text_align(TextAlign::Center);
174        text_painter.set_text_direction(Some(self.text_direction));
175        Prepared {
176            text_painter,
177            paint_shadow: self.shadow.to_paint(),
178            paint_banner: Paint {
179                color: self.color.into(),
180                ..Paint::default()
181            },
182        }
183    }
184
185    fn translation_x(&self, width: f64) -> f64 {
186        match (self.layout_direction, self.location) {
187            (TextDirection::Rtl, BannerLocation::TopStart) => width,
188            (TextDirection::Ltr, BannerLocation::TopStart) => 0.0,
189            (TextDirection::Rtl, BannerLocation::TopEnd) => 0.0,
190            (TextDirection::Ltr, BannerLocation::TopEnd) => width,
191            (TextDirection::Rtl, BannerLocation::BottomStart) => width - K_BOTTOM_OFFSET,
192            (TextDirection::Ltr, BannerLocation::BottomStart) => K_BOTTOM_OFFSET,
193            (TextDirection::Rtl, BannerLocation::BottomEnd) => K_BOTTOM_OFFSET,
194            (TextDirection::Ltr, BannerLocation::BottomEnd) => width - K_BOTTOM_OFFSET,
195        }
196    }
197
198    fn translation_y(&self, height: f64) -> f64 {
199        match self.location {
200            BannerLocation::BottomStart | BannerLocation::BottomEnd => height - K_BOTTOM_OFFSET,
201            BannerLocation::TopStart | BannerLocation::TopEnd => 0.0,
202        }
203    }
204
205    fn rotation(&self) -> f64 {
206        let turns = match (self.layout_direction, self.location) {
207            (TextDirection::Rtl, BannerLocation::TopStart | BannerLocation::BottomEnd) => 1.0,
208            (TextDirection::Ltr, BannerLocation::TopStart | BannerLocation::BottomEnd) => -1.0,
209            (TextDirection::Rtl, BannerLocation::BottomStart | BannerLocation::TopEnd) => -1.0,
210            (TextDirection::Ltr, BannerLocation::BottomStart | BannerLocation::TopEnd) => 1.0,
211        };
212        PI / 4.0 * turns
213    }
214}
215
216impl CustomPainter for BannerPainter {
217    fn paint(&self, app: &mut App, canvas: &mut Canvas, size: Size) {
218        let mut prepared = self.prepared.borrow_mut();
219        let prepared = prepared.get_or_insert_with(|| self.prepare());
220        canvas.translate(
221            self.translation_x(size.width()) as f32,
222            self.translation_y(size.height()) as f32,
223        );
224        canvas.rotate(self.rotation() as f32);
225        canvas.draw_rect(K_RECT, &prepared.paint_shadow);
226        canvas.draw_rect(K_RECT, &prepared.paint_banner);
227        let width = K_OFFSET * 2.0;
228        let fonts = PaintingBinding::instance(app).fonts(app);
229        let fonts = app.get_mut(fonts);
230        prepared.text_painter.layout(fonts, width, width);
231        let text_height = prepared.text_painter.height();
232        prepared.text_painter.paint(
233            fonts,
234            canvas,
235            K_RECT.top_left() + Offset::new(0.0, (K_RECT.height() - text_height) / 2.0),
236        );
237    }
238
239    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
240        let Some(old_delegate) = old_delegate.as_any().downcast_ref::<BannerPainter>() else {
241            return true;
242        };
243        self.message != old_delegate.message
244            || self.location != old_delegate.location
245            || self.color != old_delegate.color
246            || self.text_style != old_delegate.text_style
247    }
248
249    fn hit_test(&self, _app: &App, _position: Offset) -> Option<bool> {
250        Some(false)
251    }
252
253    fn as_any(&self) -> &dyn Any {
254        self
255    }
256}
257
258impl Debug for BannerPainter {
259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
260        f.debug_struct("BannerPainter")
261            .field("message", &self.message)
262            .field("location", &self.location)
263            .finish_non_exhaustive()
264    }
265}
266
267/// Displays a diagonal message above the corner of another widget.
268///
269/// Useful for showing the execution mode of an app (e.g., that asserts are
270/// enabled.)
271///
272/// See also:
273///
274///  * [`CheckedModeBanner`], which the `WidgetsApp` widget includes by default in
275///    debug mode, to show a banner that says "DEBUG".
276pub struct Banner {
277    pub key: Option<KeyRef>,
278    /// The widget to show behind the banner.
279    pub child: Option<WidgetRef>,
280    /// The message to show in the banner.
281    pub message: String,
282    /// The directionality of the text.
283    ///
284    /// This is used to disambiguate how to render bidirectional text. For
285    /// example, if the message is an English phrase followed by a Hebrew phrase,
286    /// in a [`TextDirection::Ltr`] context the English phrase will be on the left
287    /// and the Hebrew phrase to its right, while in a [`TextDirection::Rtl`]
288    /// context, the English phrase will be on the right and the Hebrew phrase on
289    /// its left.
290    ///
291    /// Defaults to the ambient [`Directionality`], if any.
292    ///
293    /// See also [`layout_direction`](Self::layout_direction), which controls the
294    /// interpretation of the [`location`](Self::location).
295    pub text_direction: Option<TextDirection>,
296    /// Where to show the banner (e.g., the upper right corner).
297    pub location: BannerLocation,
298    /// The directionality of the layout.
299    ///
300    /// This is used to resolve the [`location`](Self::location) values.
301    ///
302    /// Defaults to the ambient [`Directionality`], if any.
303    ///
304    /// See also [`text_direction`](Self::text_direction), which controls the
305    /// reading direction of the [`message`](Self::message).
306    pub layout_direction: Option<TextDirection>,
307    /// The color of the banner.
308    pub color: Color,
309    /// The style of the text shown on the banner.
310    pub text_style: TextStyle,
311    /// The shadow of the banner.
312    pub shadow: BoxShadow,
313}
314
315impl Banner {
316    /// Creates a banner.
317    pub fn new(message: impl Into<String>, location: BannerLocation) -> Banner {
318        Banner {
319            key: None,
320            child: None,
321            message: message.into(),
322            text_direction: None,
323            location,
324            layout_direction: None,
325            color: K_COLOR,
326            text_style: k_text_style(),
327            shadow: k_shadow(),
328        }
329    }
330
331    /// Dart `Banner(key:)`.
332    pub fn key(mut self, key: KeyRef) -> Banner {
333        self.key = Some(key);
334        self
335    }
336
337    /// Dart `Banner(child:)`.
338    #[cfg_attr(debug_assertions, track_caller)]
339    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Banner {
340        self.child = Some(child.into_widget());
341        self
342    }
343
344    /// Dart `Banner(textDirection:)`.
345    pub fn text_direction(mut self, text_direction: TextDirection) -> Banner {
346        self.text_direction = Some(text_direction);
347        self
348    }
349
350    /// Dart `Banner(layoutDirection:)`.
351    pub fn layout_direction(mut self, layout_direction: TextDirection) -> Banner {
352        self.layout_direction = Some(layout_direction);
353        self
354    }
355
356    /// Dart `Banner(color:)`.
357    pub fn color(mut self, color: Color) -> Banner {
358        self.color = color;
359        self
360    }
361
362    /// Dart `Banner(textStyle:)`.
363    pub fn text_style(mut self, text_style: TextStyle) -> Banner {
364        self.text_style = text_style;
365        self
366    }
367
368    /// Dart `Banner(shadow:)`.
369    pub fn shadow(mut self, shadow: BoxShadow) -> Banner {
370        self.shadow = shadow;
371        self
372    }
373}
374
375impl Debug for Banner {
376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377        f.debug_struct("Banner")
378            .field("message", &self.message)
379            .field("location", &self.location)
380            .field("child", &self.child)
381            .finish_non_exhaustive()
382    }
383}
384
385impl StatefulWidget for Banner {
386    type State = BannerState;
387
388    fn key(&self) -> Option<&KeyRef> {
389        self.key.as_ref()
390    }
391
392    fn create_state(&self) -> BannerState {
393        BannerState {
394            state: StateData::new(),
395        }
396    }
397}
398
399/// Dart's `_BannerState`. The painter it builds is owned by the `CustomPaint`, and dropping
400/// it releases the text painter that Dart's `_painter?.dispose()` does.
401pub struct BannerState {
402    state: StateData<Banner>,
403}
404
405impl State for BannerState {
406    type Widget = Banner;
407    crate::state_accessors!();
408
409    fn debug_fill_properties(
410        self: Handle<Self>,
411        app: &App,
412        properties: &mut DiagnosticPropertiesBuilder,
413    ) {
414        let widget = self.widget(app);
415        properties.add(
416            StringProperty::new("message", Some(widget.message.clone())).with_show_name(false),
417        );
418        properties.add(
419            EnumProperty::<TextDirection>::new("textDirection", widget.text_direction)
420                .default_value(None),
421        );
422        properties.add(EnumProperty::new("location", widget.location));
423        properties.add(
424            EnumProperty::<TextDirection>::new("layoutDirection", widget.layout_direction)
425                .default_value(None),
426        );
427        properties.add(ColorProperty::new("color", widget.color).with_show_name(false));
428        widget
429            .text_style
430            .debug_fill_properties_with_prefix(properties, "text ");
431    }
432
433    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
434        let (text_direction, layout_direction) = {
435            let widget = self.widget(app);
436            (widget.text_direction, widget.layout_direction)
437        };
438        let text_direction = text_direction.unwrap_or_else(|| Directionality::of(app, context));
439        let layout_direction = layout_direction.unwrap_or_else(|| Directionality::of(app, context));
440        let widget = self.widget(app);
441        let painter = BannerPainter::new(
442            widget.message.clone(),
443            text_direction,
444            widget.location,
445            layout_direction,
446        )
447        .color(widget.color)
448        .text_style(widget.text_style.clone())
449        .shadow(widget.shadow);
450        let child = widget.child.clone();
451        let mut custom_paint = CustomPaint::new().foreground_painter(painter);
452        if let Some(child) = child {
453            custom_paint = custom_paint.child(child);
454        }
455        custom_paint.into_widget()
456    }
457}
458
459/// Displays a [`Banner`] saying "DEBUG" when running in debug mode.
460/// `WidgetsApp` builds one of these by default.
461///
462/// Does nothing in release mode.
463#[derive(Debug)]
464pub struct CheckedModeBanner {
465    pub key: Option<KeyRef>,
466    /// The widget to show behind the banner.
467    pub child: WidgetRef,
468}
469
470impl CheckedModeBanner {
471    /// Creates a const debug mode banner.
472    #[cfg_attr(debug_assertions, track_caller)]
473    pub fn new<K>(child: impl IntoWidget<K>) -> CheckedModeBanner {
474        CheckedModeBanner {
475            key: None,
476            child: child.into_widget(),
477        }
478    }
479
480    /// Dart `CheckedModeBanner(key:)`.
481    pub fn key(mut self, key: KeyRef) -> CheckedModeBanner {
482        self.key = Some(key);
483        self
484    }
485}
486
487impl StatelessWidget for CheckedModeBanner {
488    fn key(&self) -> Option<&KeyRef> {
489        self.key.as_ref()
490    }
491
492    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
493        let message = if cfg!(debug_assertions) {
494            "\"DEBUG\""
495        } else {
496            "disabled"
497        };
498        properties.add(waft_foundation::MessageProperty::new("", message));
499    }
500
501    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
502        if cfg!(debug_assertions) {
503            return Banner::new("DEBUG", BannerLocation::TopEnd)
504                .text_direction(TextDirection::Ltr)
505                .child(self.child.clone())
506                .into_widget();
507        }
508        self.child.clone()
509    }
510}
511
512#[cfg(test)]
513mod tests {
514    use waft_embedder::valo::Op;
515    use waft_foundation::AppCell;
516    use waft_rendering::RenderCustomPaint;
517
518    use super::*;
519    use crate::test_harness::Harness;
520    use crate::widgets::basic::SizedBox;
521
522    /// What the shell does at start-up: the app-wide fonts, here the OS fonts.
523    fn install_fonts(app: &mut App) {
524        let binding = PaintingBinding::instance(app);
525        if !binding.has_fonts(app) {
526            binding.install_fonts(app, |fonts| {
527                fonts.add_source(valo_system_fonts::SystemFonts::load());
528            });
529        }
530    }
531
532    #[test]
533    fn a_banner_paints_a_rotated_shadowed_rect_with_its_message_in_the_corner() {
534        let cell = AppCell::new();
535        let mut app = cell.borrow_mut();
536        install_fonts(&mut app);
537        let harness = Harness::mount(
538            &mut app,
539            Directionality::new(
540                TextDirection::Ltr,
541                CheckedModeBanner::new(SizedBox::expand()),
542            )
543            .into_widget(),
544        );
545        harness.pump(&mut app);
546        let custom_paint = harness
547            .render_root(&app)
548            .child(&app)
549            .expect("the banner's custom paint")
550            .as_object()
551            .downcast::<RenderCustomPaint>(&app)
552            .expect("a RenderCustomPaint");
553        let painter = custom_paint
554            .foreground_painter(&app)
555            .expect("the banner painter");
556        let banner = painter
557            .as_any()
558            .downcast_ref::<BannerPainter>()
559            .expect("a BannerPainter");
560        assert_eq!(banner.message, "DEBUG");
561        assert_eq!(banner.location, BannerLocation::TopEnd);
562        assert_eq!(
563            banner.translation_x(300.0),
564            300.0,
565            "top end sits at the right edge"
566        );
567        assert_eq!(banner.rotation(), PI / 4.0);
568
569        let mut canvas = Canvas::new();
570        painter.paint(&mut app, &mut canvas, Size::new(300.0, 200.0));
571        let ops = canvas.build().ops().to_vec();
572        let rects = ops
573            .iter()
574            .filter(|op| matches!(op, Op::DrawRect { .. } | Op::RRectBlur { .. }))
575            .count();
576        assert!(rects >= 2, "the shadow and the banner: {ops:?}");
577        assert!(
578            ops.iter().any(|op| matches!(op, Op::Transform(_))),
579            "the corner rotation: {ops:?}"
580        );
581    }
582}