Skip to main content

waft_material/
material.rs

1//! Flutter counterpart: material_ui's `material.dart`.
2
3use std::any::Any;
4use std::fmt;
5use std::hash::Hash;
6use std::rc::Rc;
7use std::time::Duration;
8
9use waft_animation::{Animatable, ColorTween, Curves, Tween};
10use waft_embedder::{
11    Canvas, ClipOp, Color, Matrix4, Offset, Path, Radius, Rect, Size, TextBaseline, TextDirection,
12};
13use waft_foundation::{
14    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, DoubleProperty, EnumProperty, Handle,
15    HandleId, Listener, Ref, Retained,
16};
17use waft_painting::{
18    BorderRadius, BorderRadiusGeometry, BorderSide, CircleBorder, Clip, ClipContext, ColorProperty,
19    RoundedRectangleBorder, ShapeBorderRef, TextStyle,
20};
21use waft_rendering::{
22    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, CustomClipper, CustomPainter,
23    PaintingContext, RenderBox, RenderBoxData, RenderHandle, RenderObject, RenderObjectData,
24    RenderObjectWithChildData, RenderObjectWithChildMixin, RenderProxyBoxMixin, ShapeBorderClipper,
25};
26use waft_scheduler::{Ticker, TickerCallback, TickerProvider, TickerProviderObject};
27use waft_widgets::{
28    AnimatedDefaultTextStyle, AnimatedPhysicalModel, AnimatedWidgetBaseState, BuildContext,
29    ClipPath, CustomPaint, Directionality, GlobalKey, ImplicitlyAnimatedWidget,
30    ImplicitlyAnimatedWidgetData, ImplicitlyAnimatedWidgetState, ImplicitlyAnimatedWidgetStateData,
31    IntoWidget, KeyRef, LayoutChangedNotification, LookupBoundary, NotificationListener,
32    PhysicalShape, RenderObjectWidget, SingleChildRenderObjectWidget,
33    SingleTickerProviderStateMixin, SingleTickerProviderStateMixinData, State, StateData,
34    StatefulWidget, StatelessWidget, TickerProviderStateMixin, TickerProviderStateMixinData,
35    TweenSlot, TweenVisitor, WidgetRef,
36};
37
38use crate::constants::K_THEME_CHANGE_DURATION;
39use crate::elevation_overlay::ElevationOverlay;
40use crate::theme::Theme;
41
42/// Signature for the callback used by ink effects to obtain the rectangle for the effect.
43///
44/// Used by [`InkHighlight`](crate::InkHighlight) and [`InkSplash`](crate::InkSplash), for
45/// example.
46pub type RectCallback = Rc<dyn Fn(&App) -> Rect>;
47
48/// The various kinds of material in Material Design. Used to
49/// configure the default behavior of [`Material`] widgets.
50///
51/// See also:
52///
53///  * [`Material`], in particular [`Material::type`](Material::r#type).
54///  * [`k_material_edges`]
55#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
56pub enum MaterialType {
57    /// Rectangle using default theme canvas color.
58    Canvas,
59
60    /// Rounded edges, card theme color.
61    Card,
62
63    /// A circle, no color by default (used for floating action buttons).
64    Circle,
65
66    /// Rounded edges, no color by default (used for `MaterialButton` buttons).
67    Button,
68
69    /// A transparent piece of material that draws ink splashes and highlights.
70    ///
71    /// While the material metaphor describes child widgets as printed on the
72    /// material itself and do not hide ink effects, in practice the [`Material`]
73    /// widget draws child widgets on top of the ink effects.
74    /// A [`Material`] with type transparency can be placed on top of opaque widgets
75    /// to show ink effects on top of them.
76    ///
77    /// Prefer using the [`Ink`](crate::Ink) widget for showing ink effects on top of opaque
78    /// widgets.
79    Transparency,
80}
81
82/// The border radii used by the various kinds of material in Material Design.
83///
84/// Dart's `const Map<MaterialType, BorderRadius?> kMaterialEdges`.
85///
86/// See also:
87///
88///  * [`MaterialType`]
89///  * [`Material`]
90pub const fn k_material_edges(r#type: MaterialType) -> Option<BorderRadius> {
91    match r#type {
92        MaterialType::Canvas => None,
93        MaterialType::Card => Some(BorderRadius::all(Radius::circular(2.0))),
94        MaterialType::Circle => None,
95        MaterialType::Button => Some(BorderRadius::all(Radius::circular(2.0))),
96        MaterialType::Transparency => None,
97    }
98}
99
100/// An interface for creating [`InkSplash`](crate::InkSplash)s and
101/// [`InkHighlight`](crate::InkHighlight)s on a [`Material`].
102///
103/// Typically obtained via [`Material::of`], as the erased [`AnyMaterialInkController`].
104pub trait MaterialInkController: Sized + 'static {
105    /// This controller as the erased [`AnyMaterialInkController`] — what to pass where a Dart
106    /// API takes a `MaterialInkController`.
107    fn as_material_ink_controller(self: Handle<Self>) -> AnyMaterialInkController {
108        AnyMaterialInkController {
109            id: self.id(),
110            vtable: const { &MaterialInkControllerVTable::of::<Self>() },
111        }
112    }
113
114    /// The color of the material.
115    fn color(self: Handle<Self>, app: &App) -> Option<Color>;
116
117    /// The ticker provider used by the controller.
118    ///
119    /// Ink features that are added to this controller with
120    /// [`add_ink_feature`](Self::add_ink_feature) should use this vsync to drive their
121    /// animations.
122    fn vsync(self: Handle<Self>, app: &App) -> Rc<dyn TickerProvider>;
123
124    /// Add an [`InkFeature`], such as an [`InkSplash`](crate::InkSplash) or an
125    /// [`InkHighlight`](crate::InkHighlight).
126    ///
127    /// The ink feature will paint as part of this controller.
128    fn add_ink_feature(self: Handle<Self>, app: &mut App, feature: InkFeatureRef);
129
130    /// Notifies the controller that one of its ink features needs to repaint.
131    fn mark_needs_paint(self: Handle<Self>, app: &mut App);
132}
133
134/// The vtable of an erased [`AnyMaterialInkController`]: one `&'static` table per type.
135struct MaterialInkControllerVTable {
136    type_name: fn() -> &'static str,
137    color: fn(&App, HandleId) -> Option<Color>,
138    vsync: fn(&App, HandleId) -> Rc<dyn TickerProvider>,
139    add_ink_feature: fn(&mut App, HandleId, InkFeatureRef),
140    mark_needs_paint: fn(&mut App, HandleId),
141}
142
143/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
144fn resolve<T: 'static>(id: HandleId) -> Handle<T> {
145    Handle::from_id(id)
146}
147
148impl MaterialInkControllerVTable {
149    const fn of<T: MaterialInkController>() -> MaterialInkControllerVTable {
150        MaterialInkControllerVTable {
151            type_name: std::any::type_name::<T>,
152            color: |app, id| T::color(resolve(id), app),
153            vsync: |app, id| T::vsync(resolve(id), app),
154            add_ink_feature: |app, id, feature| T::add_ink_feature(resolve(id), app, feature),
155            mark_needs_paint: |app, id| T::mark_needs_paint(resolve(id), app),
156        }
157    }
158}
159
160/// Erased `MaterialInkController`: one identity and a static vtable.
161///
162/// Equality is Dart's `==` on an object reference.
163#[derive(Clone, Copy)]
164pub struct AnyMaterialInkController {
165    id: HandleId,
166    vtable: &'static MaterialInkControllerVTable,
167}
168
169impl PartialEq for AnyMaterialInkController {
170    fn eq(&self, other: &AnyMaterialInkController) -> bool {
171        self.id == other.id
172    }
173}
174
175impl Eq for AnyMaterialInkController {}
176
177impl fmt::Debug for AnyMaterialInkController {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
180    }
181}
182
183impl AnyMaterialInkController {
184    /// The arena id behind this handle.
185    pub fn id(self) -> HandleId {
186        self.id
187    }
188
189    /// See [`MaterialInkController::color`].
190    pub fn color(self, app: &App) -> Option<Color> {
191        (self.vtable.color)(app, self.id)
192    }
193
194    /// See [`MaterialInkController::vsync`].
195    pub fn vsync(self, app: &App) -> Rc<dyn TickerProvider> {
196        (self.vtable.vsync)(app, self.id)
197    }
198
199    /// See [`MaterialInkController::add_ink_feature`].
200    pub fn add_ink_feature(self, app: &mut App, feature: InkFeatureRef) {
201        (self.vtable.add_ink_feature)(app, self.id, feature);
202    }
203
204    /// See [`MaterialInkController::mark_needs_paint`].
205    pub fn mark_needs_paint(self, app: &mut App) {
206        (self.vtable.mark_needs_paint)(app, self.id);
207    }
208
209    /// Dart's `controller as T`: the typed handle when this controller is a `T`, else `None`.
210    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
211        app.handle::<T>(self.id)
212    }
213
214    /// Dart's `controller.markNeedsPaint` tear-off, as a listener an ink feature's animation
215    /// controllers call.
216    pub fn mark_needs_paint_listener(self) -> Listener {
217        Listener::new(move |app| self.mark_needs_paint(app))
218    }
219}
220
221/// A piece of material.
222///
223/// The Material widget is responsible for:
224///
225/// 1. Clipping: If [`clip_behavior`](Self::clip_behavior) is not [`Clip::None`], Material
226///    clips its widget sub-tree to the shape specified by [`shape`](Self::shape),
227///    [`type`](Self::r#type), and [`border_radius`](Self::border_radius).
228///    By default, [`clip_behavior`](Self::clip_behavior) is [`Clip::None`] for performance
229///    considerations. See [`Ink`](crate::Ink) for an example of how this affects clipping
230///    [`Ink`](crate::Ink) widgets.
231/// 2. Elevation: Material elevates its widget sub-tree on the Z axis by
232///    [`elevation`](Self::elevation) pixels, and draws the appropriate shadow.
233/// 3. Ink effects: Material shows ink effects implemented by [`InkFeature`]s
234///    like [`InkSplash`](crate::InkSplash) and [`InkHighlight`](crate::InkHighlight) below its
235///    children.
236///
237/// ## The Material Metaphor
238///
239/// Material is the central metaphor in Material Design. Each piece of material
240/// exists at a given elevation, which influences how that piece of material
241/// visually relates to other pieces of material and how that material casts
242/// shadows.
243///
244/// Most user interface elements are either conceptually printed on a piece of
245/// material or themselves made of material. Material reacts to user input using
246/// [`InkSplash`](crate::InkSplash) and [`InkHighlight`](crate::InkHighlight) effects. To
247/// trigger a reaction on the material, use a [`MaterialInkController`] obtained via
248/// [`Material::of`].
249///
250/// In general, the features of a [`Material`] should not change over time (e.g. a
251/// [`Material`] should not change its [`color`](Self::color),
252/// [`shadow_color`](Self::shadow_color) or [`type`](Self::r#type)).
253/// Changes to [`elevation`](Self::elevation), [`shadow_color`](Self::shadow_color) and
254/// [`surface_tint_color`](Self::surface_tint_color) are animated
255/// for [`animation_duration`](Self::animation_duration). Changes to [`shape`](Self::shape) are
256/// animated if [`type`](Self::r#type) is not [`MaterialType::Transparency`] and
257/// `ShapeBorder::lerp` between the previous and next [`shape`](Self::shape) values is
258/// supported. Shape changes are also animated for
259/// [`animation_duration`](Self::animation_duration).
260///
261/// ## Shape
262///
263/// The shape for material is determined by [`shape`](Self::shape), [`type`](Self::r#type),
264/// and [`border_radius`](Self::border_radius).
265///
266///  - If [`shape`](Self::shape) is non null, it determines the shape.
267///  - If [`shape`](Self::shape) is null and [`border_radius`](Self::border_radius) is non
268///    null, the shape is a rounded rectangle, with corners specified by
269///    [`border_radius`](Self::border_radius).
270///  - If [`shape`](Self::shape) and [`border_radius`](Self::border_radius) are null,
271///    [`type`](Self::r#type) determines the shape as follows:
272///    - [`MaterialType::Canvas`]: the default material shape is a rectangle.
273///    - [`MaterialType::Card`]: the default material shape is a rectangle with
274///      rounded edges. The edge radii is specified by [`k_material_edges`].
275///    - [`MaterialType::Circle`]: the default material shape is a circle.
276///    - [`MaterialType::Button`]: the default material shape is a rectangle with
277///      rounded edges. The edge radii is specified by [`k_material_edges`].
278///    - [`MaterialType::Transparency`]: the default material shape is a rectangle.
279///
280/// ## Border
281///
282/// If [`shape`](Self::shape) is not null, then its border will also be painted (if any).
283///
284/// ## Layout change notifications
285///
286/// If the layout changes (e.g. because there's a list on the material, and it's
287/// been scrolled), a [`LayoutChangedNotification`] must be dispatched at the
288/// relevant subtree. This in particular means that transitions (e.g.
289/// `SlideTransition`) should not be placed inside [`Material`] widgets so as to
290/// move subtrees that contain [`InkResponse`](crate::InkResponse)s,
291/// [`InkWell`](crate::InkWell)s, [`Ink`](crate::Ink)s, or other widgets that use the
292/// [`InkFeature`] mechanism. Otherwise, in-progress ink features (e.g., ink splashes and ink
293/// highlights) won't move to account for the new layout.
294///
295/// ## Painting over the material
296///
297/// Material widgets will often trigger reactions on their nearest material
298/// ancestor. For example, `ListTile.hoverColor` triggers a reaction on the
299/// tile's material when a pointer is hovering over it. These reactions will be
300/// obscured if any widget in between them and the material paints in such a
301/// way as to obscure the material (such as setting a `BoxDecoration.color` on
302/// a `DecoratedBox`). To avoid this behavior, use [`InkDecoration`](crate::InkDecoration) to
303/// decorate the material itself.
304///
305/// See also:
306///
307///  * `MergeableMaterial`, a piece of material that can split and re-merge.
308///  * `Card`, a wrapper for a [`Material`] of [`type`](Self::r#type) [`MaterialType::Card`].
309///  * <https://material.io/design/>
310///  * <https://m3.material.io/styles/color/the-color-system/color-roles>
311#[derive(Clone, Debug)]
312pub struct Material {
313    pub key: Option<KeyRef>,
314
315    /// The widget below this widget in the tree.
316    pub child: Option<WidgetRef>,
317
318    /// The kind of material to show (e.g., card or canvas). This
319    /// affects the shape of the widget, the roundness of its corners if
320    /// the shape is rectangular, and the default color.
321    pub r#type: MaterialType,
322
323    /// Whether the color should be animated.
324    pub animate_color: bool,
325
326    /// The z-coordinate at which to place this material relative to its parent.
327    ///
328    /// This controls the size of the shadow below the material and the opacity
329    /// of the elevation overlay color if it is applied.
330    ///
331    /// If this is non-zero, the contents of the material are clipped, because the
332    /// widget conceptually defines an independent printed piece of material.
333    ///
334    /// Defaults to 0. Changing this value will cause the shadow and the elevation
335    /// overlay or surface tint to animate over [`Material::animation_duration`].
336    ///
337    /// The value is non-negative.
338    ///
339    /// See also:
340    ///
341    ///  * `ThemeData::use_material3` which defines whether a surface tint or
342    ///    elevation overlay is used to indicate elevation.
343    ///  * `ThemeData::apply_elevation_overlay_color` which controls the whether
344    ///    an overlay color will be applied to indicate elevation.
345    ///  * [`Material::color`] which may have an elevation overlay applied.
346    ///  * [`Material::shadow_color`] which will be used for the color of a drop shadow.
347    ///  * [`Material::surface_tint_color`] which will be used as the overlay tint to
348    ///    show elevation.
349    pub elevation: f64,
350
351    /// The color to paint the material.
352    ///
353    /// Must be opaque. To create a transparent piece of material, use
354    /// [`MaterialType::Transparency`].
355    ///
356    /// If `ThemeData::use_material3` is true then an optional
357    /// [`surface_tint_color`](Self::surface_tint_color) overlay may be applied on top of this
358    /// color to indicate elevation.
359    ///
360    /// If `ThemeData::use_material3` is false and `ThemeData::apply_elevation_overlay_color`
361    /// is true and `ThemeData::brightness` is `Brightness::Dark` then a
362    /// semi-transparent overlay color will be composited on top of this
363    /// color to indicate the elevation. This is no longer needed for Material
364    /// Design 3, which uses [`surface_tint_color`](Self::surface_tint_color).
365    ///
366    /// By default, the color is derived from the [`type`](Self::r#type) of material.
367    pub color: Option<Color>,
368
369    /// The color to paint the shadow below the material.
370    ///
371    /// If null and `ThemeData::use_material3` is true then `ThemeData`'s
372    /// `ColorScheme::shadow` will be used. If `ThemeData::use_material3` is false
373    /// then `ThemeData::shadow_color` will be used.
374    ///
375    /// To remove the drop shadow when [`elevation`](Self::elevation) is greater than 0, set
376    /// [`shadow_color`](Self::shadow_color) to `Colors::TRANSPARENT`.
377    ///
378    /// See also:
379    ///  * `ThemeData::use_material3`, which determines the default value for this
380    ///    property if it is null.
381    ///  * `ThemeData::apply_elevation_overlay_color`, which turns elevation overlay
382    ///    on or off for dark themes.
383    pub shadow_color: Option<Color>,
384
385    /// The color of the surface tint overlay applied to the material color
386    /// to indicate elevation.
387    ///
388    /// Material Design 3 introduced a new way for some components to indicate
389    /// their elevation by using a surface tint color overlay on top of the
390    /// base material [`color`](Self::color). This overlay is painted with an opacity that is
391    /// related to the [`elevation`](Self::elevation) of the material.
392    ///
393    /// If `ThemeData::use_material3` is false, then this property is not used.
394    ///
395    /// If `ThemeData::use_material3` is true and
396    /// [`surface_tint_color`](Self::surface_tint_color) is not null and not
397    /// `Colors::TRANSPARENT`, then it will be used to overlay the base
398    /// [`color`](Self::color) with an opacity based on the [`elevation`](Self::elevation).
399    ///
400    /// Otherwise, no surface tint will be applied.
401    ///
402    /// See also:
403    ///
404    ///   * `ThemeData::use_material3`, which turns this feature on.
405    ///   * [`ElevationOverlay::apply_surface_tint`], which is used to implement the
406    ///     tint.
407    ///   * <https://m3.material.io/styles/color/the-color-system/color-roles>
408    ///     which specifies how the overlay is applied.
409    pub surface_tint_color: Option<Color>,
410
411    /// The typographical style to use for text within this material.
412    pub text_style: Option<TextStyle>,
413
414    /// Defines the material's shape as well its shadow.
415    ///
416    /// If shape is non null, the [`border_radius`](Self::border_radius) is ignored and the
417    /// material's clip boundary and shadow are defined by the shape.
418    ///
419    /// A shadow is only displayed if the [`elevation`](Self::elevation) is greater than
420    /// zero.
421    pub shape: Option<ShapeBorderRef>,
422
423    /// Whether to paint the [`shape`](Self::shape) border in front of the
424    /// [`child`](Self::child).
425    ///
426    /// The default value is true.
427    /// If false, the border will be painted behind the [`child`](Self::child).
428    pub border_on_foreground: bool,
429
430    /// The content will be clipped (or not) according to this option.
431    ///
432    /// Defaults to [`Clip::None`].
433    pub clip_behavior: Clip,
434
435    /// Defines the duration of animated changes for [`shape`](Self::shape),
436    /// [`elevation`](Self::elevation), [`shadow_color`](Self::shadow_color),
437    /// [`surface_tint_color`](Self::surface_tint_color) and the elevation overlay if it is
438    /// applied.
439    ///
440    /// The default value is [`K_THEME_CHANGE_DURATION`].
441    pub animation_duration: Duration,
442
443    /// If non-null, the corners of this box are rounded by this
444    /// [`BorderRadiusGeometry`] value.
445    ///
446    /// Otherwise, the corners specified for the current [`type`](Self::r#type) of material
447    /// are used.
448    ///
449    /// If [`shape`](Self::shape) is non null then the border radius is ignored.
450    ///
451    /// Must be null if [`type`](Self::r#type) is [`MaterialType::Circle`].
452    pub border_radius: Option<BorderRadiusGeometry>,
453}
454
455impl Default for Material {
456    fn default() -> Material {
457        Material {
458            key: None,
459            child: None,
460            r#type: MaterialType::Canvas,
461            animate_color: false,
462            elevation: 0.0,
463            color: None,
464            shadow_color: None,
465            surface_tint_color: None,
466            text_style: None,
467            shape: None,
468            border_on_foreground: true,
469            clip_behavior: Clip::None,
470            animation_duration: K_THEME_CHANGE_DURATION,
471            border_radius: None,
472        }
473    }
474}
475
476impl Material {
477    /// The default radius of an ink splash in logical pixels.
478    pub const DEFAULT_SPLASH_RADIUS: f64 = 35.0;
479
480    /// Creates a piece of material; Dart's named arguments are the setters.
481    ///
482    /// The [`elevation`](Self::elevation) must be non-negative.
483    ///
484    /// If a [`shape`](Self::shape) is specified, then the
485    /// [`border_radius`](Self::border_radius) property must be null and the
486    /// [`type`](Self::r#type) property must not be [`MaterialType::Circle`]. If the
487    /// [`border_radius`](Self::border_radius) is specified, then the [`type`](Self::r#type)
488    /// property must not be [`MaterialType::Circle`]. In both cases, these restrictions are
489    /// intended to catch likely errors.
490    pub fn new() -> Material {
491        Material::default()
492    }
493
494    /// Dart `Material(key:)`.
495    pub fn key(mut self, key: KeyRef) -> Material {
496        self.key = Some(key);
497        self
498    }
499
500    /// Dart `Material(type:)`.
501    pub fn r#type(mut self, r#type: MaterialType) -> Material {
502        self.r#type = r#type;
503        self.debug_assert_shape_fits_type();
504        self
505    }
506
507    /// Dart `Material(elevation:)`.
508    pub fn elevation(mut self, elevation: f64) -> Material {
509        debug_assert!(elevation >= 0.0);
510        self.elevation = elevation;
511        self
512    }
513
514    /// Dart `Material(color:)`.
515    pub fn color(mut self, color: Color) -> Material {
516        self.color = Some(color);
517        self
518    }
519
520    /// Dart `Material(shadowColor:)`.
521    pub fn shadow_color(mut self, shadow_color: Color) -> Material {
522        self.shadow_color = Some(shadow_color);
523        self
524    }
525
526    /// Dart `Material(surfaceTintColor:)`.
527    pub fn surface_tint_color(mut self, surface_tint_color: Color) -> Material {
528        self.surface_tint_color = Some(surface_tint_color);
529        self
530    }
531
532    /// Dart `Material(textStyle:)`.
533    pub fn text_style(mut self, text_style: TextStyle) -> Material {
534        self.text_style = Some(text_style);
535        self
536    }
537
538    /// Dart `Material(borderRadius:)`.
539    pub fn border_radius(mut self, border_radius: impl Into<BorderRadiusGeometry>) -> Material {
540        self.border_radius = Some(border_radius.into());
541        self.debug_assert_shape_fits_type();
542        self
543    }
544
545    /// Dart `Material(shape:)`.
546    pub fn shape(mut self, shape: impl Into<ShapeBorderRef>) -> Material {
547        self.shape = Some(shape.into());
548        self.debug_assert_shape_fits_type();
549        self
550    }
551
552    /// Dart `Material(borderOnForeground:)`.
553    pub fn border_on_foreground(mut self, border_on_foreground: bool) -> Material {
554        self.border_on_foreground = border_on_foreground;
555        self
556    }
557
558    /// Dart `Material(clipBehavior:)`.
559    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Material {
560        self.clip_behavior = clip_behavior;
561        self
562    }
563
564    /// Dart `Material(animationDuration:)`.
565    pub fn animation_duration(mut self, animation_duration: Duration) -> Material {
566        self.animation_duration = animation_duration;
567        self
568    }
569
570    /// Dart `Material(child:)`.
571    #[cfg_attr(debug_assertions, track_caller)]
572    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> Material {
573        self.child = Some(child.into_widget());
574        self
575    }
576
577    /// Dart `Material(animateColor:)`.
578    pub fn animate_color(mut self, animate_color: bool) -> Material {
579        self.animate_color = animate_color;
580        self
581    }
582
583    /// Dart's constructor asserts on `shape`, `borderRadius` and `type`.
584    fn debug_assert_shape_fits_type(&self) {
585        debug_assert!(!(self.shape.is_some() && self.border_radius.is_some()));
586        debug_assert!(
587            !(self.r#type == MaterialType::Circle
588                && (self.border_radius.is_some() || self.shape.is_some()))
589        );
590    }
591
592    /// The ink controller from the closest instance of this class that
593    /// encloses the given context within the closest [`LookupBoundary`].
594    ///
595    /// This method can be expensive (it walks the element tree).
596    ///
597    /// See also:
598    ///
599    /// * [`Material::of`], which is similar to this method, but asserts if
600    ///   no [`Material`] ancestor is found.
601    pub fn maybe_of(app: &App, context: BuildContext) -> Option<AnyMaterialInkController> {
602        LookupBoundary::find_ancestor_render_object_of_type::<RenderInkFeatures>(app, context)
603            .map(|controller| controller.handle().as_material_ink_controller())
604    }
605
606    /// The ink controller from the closest instance of [`Material`] that encloses
607    /// the given context within the closest [`LookupBoundary`].
608    ///
609    /// If no [`Material`] widget ancestor can be found then this method panics.
610    ///
611    /// This method can be expensive (it walks the element tree).
612    ///
613    /// See also:
614    ///
615    /// * [`Material::maybe_of`], which is similar to this method, but returns null if
616    ///   no [`Material`] ancestor is found.
617    pub fn of(app: &App, context: BuildContext) -> AnyMaterialInkController {
618        let Some(controller) = Material::maybe_of(app, context) else {
619            if cfg!(debug_assertions)
620                && LookupBoundary::debug_is_hiding_ancestor_render_object_of_type::<RenderInkFeatures>(
621                    app, context,
622                )
623            {
624                panic!(
625                    "Material.of() was called with a context that does not have access to a \
626                     Material widget.\nThe context provided to Material.of() does have a \
627                     Material widget ancestor, but it is hidden by a LookupBoundary. This can \
628                     happen because you are using a widget that looks for a Material ancestor, \
629                     but no such ancestor exists within the closest LookupBoundary.\nThe \
630                     context used was:\n  {:?}",
631                    context.widget(app)
632                );
633            }
634            panic!(
635                "Material.of() was called with a context that does not contain a Material \
636                 widget.\nNo Material widget ancestor could be found starting from the context \
637                 that was passed to Material.of(). This can happen because you are using a \
638                 widget that looks for a Material ancestor, but no such ancestor exists.\nThe \
639                 context used was:\n  {:?}",
640                context.widget(app)
641            );
642        };
643        controller
644    }
645}
646
647impl StatefulWidget for Material {
648    type State = MaterialWidgetState;
649
650    fn key(&self) -> Option<&KeyRef> {
651        self.key.as_ref()
652    }
653
654    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
655        properties.add(EnumProperty::new("type", self.r#type));
656        properties.add(DoubleProperty::new("elevation", self.elevation).default_value(Some(0.0)));
657        properties.add(ColorProperty::new("color", self.color).default_value(None));
658        properties.add(ColorProperty::new("shadowColor", self.shadow_color).default_value(None));
659        properties.add(
660            ColorProperty::new("surfaceTintColor", self.surface_tint_color).default_value(None),
661        );
662        if let Some(text_style) = &self.text_style {
663            text_style.debug_fill_properties_with_prefix(properties, "textStyle.");
664        }
665        properties.add(
666            DiagnosticsProperty::<ShapeBorderRef>::new("shape", self.shape.clone())
667                .default_value(None),
668        );
669        properties.add(
670            DiagnosticsProperty::<bool>::new("borderOnForeground", self.border_on_foreground)
671                .default_value(Some(true)),
672        );
673        properties.add(
674            DiagnosticsProperty::<BorderRadiusGeometry>::new("borderRadius", self.border_radius)
675                .default_value(None),
676        );
677    }
678
679    fn create_state(&self) -> MaterialWidgetState {
680        MaterialWidgetState {
681            state: StateData::new(),
682            ticker_provider: TickerProviderStateMixinData::new(),
683            ink_feature_renderer: GlobalKey::labeled("ink renderer"),
684        }
685    }
686}
687
688/// Dart's `_MaterialState`; `MaterialState` is `material_state.dart`'s name for `WidgetState`.
689pub struct MaterialWidgetState {
690    state: StateData<Material>,
691    ticker_provider: TickerProviderStateMixinData,
692    ink_feature_renderer: GlobalKey,
693}
694
695impl TickerProviderStateMixin for MaterialWidgetState {
696    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
697        &app.get(self).ticker_provider
698    }
699
700    fn ticker_provider_data_mut(
701        self: Handle<Self>,
702        app: &mut App,
703    ) -> &mut TickerProviderStateMixinData {
704        &mut app.get_mut(self).ticker_provider
705    }
706}
707
708/// Dart's `vsync: this`.
709impl TickerProviderObject for MaterialWidgetState {
710    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
711        TickerProviderStateMixin::create_ticker(self, app, on_tick)
712    }
713}
714
715impl State for MaterialWidgetState {
716    type Widget = Material;
717    waft_widgets::state_accessors!();
718
719    fn activate(self: Handle<Self>, app: &mut App) {
720        TickerProviderStateMixin::activate(self, app);
721    }
722
723    fn dispose(self: Handle<Self>, app: &mut App) {
724        TickerProviderStateMixin::dispose(self, app);
725    }
726
727    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
728        let theme = Theme::of(app, context);
729        let widget = self.widget(app).clone();
730        let background_color = widget.color.or(match widget.r#type {
731            MaterialType::Canvas => Some(theme.canvas_color),
732            MaterialType::Card => Some(theme.card_color),
733            MaterialType::Button | MaterialType::Circle | MaterialType::Transparency => None,
734        });
735        let model_shadow_color = widget.shadow_color.unwrap_or(if theme.use_material3 {
736            theme.color_scheme.shadow()
737        } else {
738            theme.shadow_color
739        });
740        debug_assert!(
741            background_color.is_some() || widget.r#type == MaterialType::Transparency,
742            "If Material type is not MaterialType.transparency, a color must either be passed \
743             in through the `color` property, or be defined in the theme (ex. canvasColor != \
744             null if type is set to MaterialType.canvas)"
745        );
746
747        let mut contents = widget.child.clone();
748        if let Some(child) = contents {
749            let style = widget.text_style.clone().unwrap_or_else(|| {
750                Theme::of(app, context)
751                    .text_theme
752                    .body_medium
753                    .clone()
754                    .expect("every text theme has a body medium style")
755            });
756            contents = Some(
757                AnimatedDefaultTextStyle::new(child, style, widget.animation_duration)
758                    .into_widget(),
759            );
760        }
761        let ink_feature_renderer = app.get(self).ink_feature_renderer.clone();
762        let mut ink_features = InkFeatures::new(
763            ink_feature_renderer.clone(),
764            Rc::new(self),
765            widget.r#type != MaterialType::Transparency,
766        );
767        ink_features.color = background_color;
768        ink_features.child = contents;
769        let contents = NotificationListener::<dyn LayoutChangedNotification>::new(ink_features)
770            .on_notification(move |app, _notification| {
771                let renderer = ink_feature_renderer
772                    .current_context(app)
773                    .expect("the ink renderer is mounted")
774                    .find_render_object(app)
775                    .expect("the ink renderer has a render object")
776                    .downcast::<RenderInkFeatures>(app)
777                    .expect("the ink renderer is a RenderInkFeatures");
778                renderer.did_change_layout(app);
779                false
780            })
781            .into_widget();
782
783        let shape: Option<ShapeBorderRef> = match widget.border_radius {
784            Some(border_radius) => Some(ShapeBorderRef::new(RoundedRectangleBorder::new(
785                BorderSide::NONE,
786                border_radius,
787            ))),
788            None => widget.shape.clone(),
789        };
790
791        // PhysicalModel has a temporary workaround for a performance issue that
792        // speeds up rectangular non transparent material (the workaround is to
793        // skip the call to ui.Canvas.saveLayer if the border radius is 0).
794        // Until the saveLayer performance issue is resolved, we're keeping this
795        // special case here for canvas material type that is using the default
796        // shape (rectangle). We could go down this fast path for explicitly
797        // specified rectangles (e.g shape RoundedRectangleBorder with radius 0, but
798        // we choose not to as we want the change from the fast-path to the
799        // slow-path to be noticeable in the construction site of Material.
800        if widget.r#type == MaterialType::Canvas && shape.is_none() {
801            let background_color = background_color.expect("asserted above");
802            let color = if theme.use_material3 {
803                ElevationOverlay::apply_surface_tint(
804                    background_color,
805                    widget.surface_tint_color,
806                    widget.elevation,
807                )
808            } else {
809                ElevationOverlay::apply_overlay(app, context, background_color, widget.elevation)
810            };
811
812            return AnimatedPhysicalModel::new(
813                contents,
814                color,
815                model_shadow_color,
816                widget.animation_duration,
817            )
818            .curve(Curves::fast_out_slow_in())
819            .clip_behavior(widget.clip_behavior)
820            .elevation(widget.elevation)
821            .animate_color(widget.animate_color)
822            .into_widget();
823        }
824
825        let shape = shape.unwrap_or_else(|| match widget.r#type {
826            MaterialType::Circle => ShapeBorderRef::new(CircleBorder::default()),
827            MaterialType::Canvas | MaterialType::Transparency => {
828                ShapeBorderRef::new(RoundedRectangleBorder::default())
829            }
830            MaterialType::Card | MaterialType::Button => {
831                ShapeBorderRef::new(RoundedRectangleBorder::new(
832                    BorderSide::NONE,
833                    BorderRadius::all(Radius::circular(2.0)).into(),
834                ))
835            }
836        });
837
838        if widget.r#type == MaterialType::Transparency {
839            let text_direction = Directionality::maybe_of(app, context);
840            return ClipPath::new()
841                .clipper(Rc::new(ShapeBorderClipper::new(
842                    shape.clone(),
843                    text_direction,
844                )))
845                .clip_behavior(widget.clip_behavior)
846                .child(ShapeBorderPaint::new(contents, shape))
847                .into_widget();
848        }
849
850        let mut interior = MaterialInterior::new(
851            contents,
852            shape,
853            widget.elevation,
854            background_color.expect("asserted above"),
855            model_shadow_color,
856            widget.surface_tint_color,
857            widget.animation_duration,
858        )
859        .curve(Curves::fast_out_slow_in());
860        interior.border_on_foreground = widget.border_on_foreground;
861        interior.clip_behavior = widget.clip_behavior;
862        interior.into_widget()
863    }
864}
865
866/// Dart's `_RenderInkFeatures`: the proxy box under a [`Material`] that paints its ink
867/// features below its child, and is the [`MaterialInkController`] that
868/// [`Material::of`] finds.
869pub(crate) struct RenderInkFeatures {
870    render_object: RenderObjectData,
871    render_box: RenderBoxData,
872    child: RenderObjectWithChildData<AnyRenderBox>,
873    // This class should exist in a 1:1 relationship with a WidgetState object,
874    // since there's no current support for dynamically changing the ticker
875    // provider.
876    vsync: Rc<dyn TickerProvider>,
877    // This is here to satisfy the MaterialInkController contract.
878    // The actual painting of this color is done by a Container in the
879    // WidgetState build method.
880    color: Option<Color>,
881    absorb_hit_test: bool,
882    ink_features: Option<Vec<InkFeatureRef>>,
883}
884
885impl RenderInkFeatures {
886    fn new(
887        app: &mut App,
888        vsync: Rc<dyn TickerProvider>,
889        absorb_hit_test: bool,
890        color: Option<Color>,
891    ) -> RenderHandle<RenderInkFeatures> {
892        RenderHandle::new_box(
893            app,
894            RenderInkFeatures {
895                render_object: RenderObjectData::new(),
896                render_box: RenderBoxData::new(),
897                child: RenderObjectWithChildData::new(),
898                vsync,
899                color,
900                absorb_hit_test,
901                ink_features: None,
902            },
903        )
904    }
905
906    /// The ink features this material paints, in the order they were added.
907    #[cfg(test)]
908    pub(crate) fn debug_ink_features(
909        self: RenderHandle<Self>,
910        app: &App,
911    ) -> Option<Vec<AnyInkFeature>> {
912        if cfg!(debug_assertions) {
913            return self.get(app).ink_features.as_ref().map(|ink_features| {
914                ink_features
915                    .iter()
916                    .map(|ink_feature| ink_feature.handle())
917                    .collect()
918            });
919        }
920        None
921    }
922
923    /// The ink features' part of Dart's `paint`, below the child.
924    pub(crate) fn paint_ink_features(
925        self: RenderHandle<Self>,
926        app: &mut App,
927        canvas: &mut Canvas,
928        offset: Offset,
929    ) {
930        let ink_features = self.get(app).ink_features.clone();
931        if let Some(ink_features) = &ink_features
932            && !ink_features.is_empty()
933        {
934            let size = self.size(app);
935            canvas.save();
936            canvas.translate(offset.dx() as f32, offset.dy() as f32);
937            canvas.clip_rect(Offset::ZERO & size, ClipOp::Intersect, true);
938            for ink_feature in ink_features {
939                ink_feature.paint(app, canvas);
940            }
941            canvas.restore();
942        }
943        debug_assert!(ink_features == self.get(app).ink_features);
944    }
945
946    fn remove_feature(self: RenderHandle<Self>, app: &mut App, feature: AnyInkFeature) {
947        let ink_features = self
948            .get_mut(app)
949            .ink_features
950            .as_mut()
951            .expect("a feature was added");
952        if let Some(index) = ink_features.iter().position(|added| *added == feature) {
953            ink_features.remove(index);
954        }
955        self.mark_needs_paint(app);
956    }
957
958    fn did_change_layout(self: RenderHandle<Self>, app: &mut App) {
959        if self
960            .get(app)
961            .ink_features
962            .as_ref()
963            .is_some_and(|ink_features| !ink_features.is_empty())
964        {
965            self.mark_needs_paint(app);
966        }
967    }
968}
969
970impl MaterialInkController for RenderInkFeatures {
971    fn color(self: Handle<Self>, app: &App) -> Option<Color> {
972        app.get(self).color
973    }
974
975    fn vsync(self: Handle<Self>, app: &App) -> Rc<dyn TickerProvider> {
976        Rc::clone(&app.get(self).vsync)
977    }
978
979    fn add_ink_feature(self: Handle<Self>, app: &mut App, feature: InkFeatureRef) {
980        debug_assert!(!feature.debug_disposed(app));
981        debug_assert!(feature.controller(app).id() == self.id());
982        let ink_features = app.get_mut(self).ink_features.get_or_insert_with(Vec::new);
983        debug_assert!(!ink_features.contains(&feature));
984        ink_features.push(feature);
985        RenderHandle::from_handle(self).mark_needs_paint(app);
986    }
987
988    fn mark_needs_paint(self: Handle<Self>, app: &mut App) {
989        RenderHandle::from_handle(self).mark_needs_paint(app);
990    }
991}
992
993impl RenderObjectWithChildMixin for RenderInkFeatures {
994    type ChildType = AnyRenderBox;
995
996    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
997        &self.get(app).child
998    }
999
1000    fn child_data_mut(
1001        self: RenderHandle<Self>,
1002        app: &mut App,
1003    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
1004        &mut self.get_mut(app).child
1005    }
1006}
1007
1008impl RenderProxyBoxMixin for RenderInkFeatures {}
1009
1010impl RenderObject for RenderInkFeatures {
1011    waft_rendering::render_object_accessors!();
1012
1013    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1014        RenderProxyBoxMixin::perform_layout(self, app);
1015    }
1016
1017    fn paint(
1018        self: RenderHandle<Self>,
1019        app: &mut App,
1020        context: &mut PaintingContext,
1021        offset: Offset,
1022    ) {
1023        self.paint_ink_features(app, context.canvas(), offset);
1024        RenderProxyBoxMixin::paint(self, app, context, offset);
1025    }
1026
1027    fn visit_children(
1028        self: RenderHandle<Self>,
1029        app: &App,
1030        visitor: &mut dyn FnMut(AnyRenderObject),
1031    ) {
1032        if let Some(child) = self.child(app) {
1033            visitor(child.as_object());
1034        }
1035    }
1036}
1037
1038impl RenderBox for RenderInkFeatures {
1039    waft_rendering::render_box_accessors!();
1040
1041    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1042        RenderProxyBoxMixin::setup_parent_data(self, app, child);
1043    }
1044
1045    fn apply_paint_transform(
1046        self: RenderHandle<Self>,
1047        app: &App,
1048        child: AnyRenderObject,
1049        transform: &mut Matrix4,
1050    ) {
1051        RenderProxyBoxMixin::apply_paint_transform(self, app, child, transform);
1052    }
1053
1054    fn hit_test_self(self: RenderHandle<Self>, app: &App, _position: Offset) -> bool {
1055        self.get(app).absorb_hit_test
1056    }
1057
1058    fn hit_test_children(
1059        self: RenderHandle<Self>,
1060        app: &mut App,
1061        result: &mut BoxHitTestResult<'_>,
1062        position: Offset,
1063    ) -> bool {
1064        RenderProxyBoxMixin::hit_test_children(self, app, result, position)
1065    }
1066
1067    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1068        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
1069    }
1070
1071    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
1072        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
1073    }
1074
1075    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1076        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
1077    }
1078
1079    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1080        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
1081    }
1082
1083    fn compute_distance_to_actual_baseline(
1084        self: RenderHandle<Self>,
1085        app: &mut App,
1086        baseline: TextBaseline,
1087    ) -> Option<f64> {
1088        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
1089    }
1090
1091    fn compute_dry_baseline(
1092        self: RenderHandle<Self>,
1093        app: &mut App,
1094        constraints: BoxConstraints,
1095        baseline: TextBaseline,
1096    ) -> Option<f64> {
1097        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
1098    }
1099
1100    fn compute_dry_layout(
1101        self: RenderHandle<Self>,
1102        app: &mut App,
1103        constraints: BoxConstraints,
1104    ) -> Size {
1105        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
1106    }
1107}
1108
1109/// Dart's `_InkFeatures`.
1110struct InkFeatures {
1111    key: KeyRef,
1112
1113    // This widget must be owned by a WidgetState, which must be provided as the vsync.
1114    // This relationship must be 1:1 and cannot change for the lifetime of the WidgetState.
1115    color: Option<Color>,
1116
1117    vsync: Rc<dyn TickerProvider>,
1118
1119    absorb_hit_test: bool,
1120
1121    child: Option<WidgetRef>,
1122}
1123
1124impl InkFeatures {
1125    fn new(key: GlobalKey, vsync: Rc<dyn TickerProvider>, absorb_hit_test: bool) -> InkFeatures {
1126        InkFeatures {
1127            key: key.into(),
1128            color: None,
1129            vsync,
1130            absorb_hit_test,
1131            child: None,
1132        }
1133    }
1134}
1135
1136impl fmt::Debug for InkFeatures {
1137    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1138        f.debug_struct("InkFeatures")
1139            .field("color", &self.color)
1140            .field("absorb_hit_test", &self.absorb_hit_test)
1141            .finish_non_exhaustive()
1142    }
1143}
1144
1145impl RenderObjectWidget for InkFeatures {
1146    type RenderObject = RenderInkFeatures;
1147
1148    fn key(&self) -> Option<&KeyRef> {
1149        Some(&self.key)
1150    }
1151
1152    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
1153        RenderInkFeatures::new(
1154            app,
1155            Rc::clone(&self.vsync),
1156            self.absorb_hit_test,
1157            self.color,
1158        )
1159        .as_object()
1160    }
1161
1162    fn update_render_object(
1163        &self,
1164        app: &mut App,
1165        _context: BuildContext,
1166        render_object: RenderHandle<RenderInkFeatures>,
1167    ) {
1168        let render = render_object.get_mut(app);
1169        render.color = self.color;
1170        render.absorb_hit_test = self.absorb_hit_test;
1171    }
1172}
1173
1174impl SingleChildRenderObjectWidget for InkFeatures {
1175    fn child(&self) -> Option<&WidgetRef> {
1176        self.child.as_ref()
1177    }
1178}
1179
1180/// The fields of Dart's `InkFeature`, which every ink feature leaf carries.
1181pub struct InkFeatureData {
1182    controller: Handle<RenderInkFeatures>,
1183    reference_box: AnyRenderBox,
1184    on_removed: Option<Listener>,
1185    debug_disposed: bool,
1186}
1187
1188impl InkFeatureData {
1189    /// Initializes fields for subclasses.
1190    ///
1191    /// # Panics
1192    ///
1193    /// If `controller` is not a [`Material`]'s, as Dart's `controller as _RenderInkFeatures`.
1194    pub fn new(
1195        app: &App,
1196        controller: AnyMaterialInkController,
1197        reference_box: AnyRenderBox,
1198        on_removed: Option<Listener>,
1199    ) -> InkFeatureData {
1200        InkFeatureData {
1201            controller: controller
1202                .downcast::<RenderInkFeatures>(app)
1203                .expect("an ink feature's controller is a Material's"),
1204            reference_box,
1205            on_removed,
1206            debug_disposed: false,
1207        }
1208    }
1209}
1210
1211/// The [`InkFeatureData`] bag of every ink feature leaf.
1212pub trait InkFeatureLeafData {
1213    /// The leaf's [`InkFeature`] bag.
1214    fn ink_feature(&self) -> &InkFeatureData;
1215
1216    /// The leaf's [`InkFeature`] bag, mutably.
1217    fn ink_feature_mut(&mut self) -> &mut InkFeatureData;
1218}
1219
1220/// The virtuals of Dart's abstract `InkFeature`, which a leaf implements.
1221pub trait InkFeatureLeaf: InkFeatureLeafData + Sized + 'static {
1222    /// Free up the resources associated with this ink feature.
1223    ///
1224    /// Dart's `@mustCallSuper`: an override ends with [`InkFeature::dispose`].
1225    fn dispose(self: Handle<Self>, app: &mut App) {
1226        InkFeature::dispose(self, app);
1227    }
1228
1229    /// Override this method to paint the ink feature.
1230    ///
1231    /// The transform argument gives the coordinate conversion from the coordinate
1232    /// system of the canvas to the coordinate system of the
1233    /// [`reference_box`](InkFeature::reference_box).
1234    fn paint_feature(self: Handle<Self>, app: &mut App, canvas: &mut Canvas, transform: &Matrix4);
1235}
1236
1237/// Mints the erased [`AnyInkFeature`] of a leaf.
1238pub trait InkFeatureObject: Sized + 'static {
1239    /// This feature as the erased [`AnyInkFeature`] — what to pass where a Dart API takes an
1240    /// `InkFeature`.
1241    fn as_ink_feature(self: Handle<Self>) -> AnyInkFeature;
1242}
1243
1244/// What a field Dart types as `InkFeature` holds: the material's list, an ink well's state.
1245pub type InkFeatureRef = Retained<AnyInkFeature>;
1246
1247waft_foundation::erased_handle!(
1248    AnyInkFeature: InkFeatureLeaf => InkFeatureObject::as_ink_feature
1249);
1250
1251impl<F: InkFeatureLeaf> InkFeatureObject for F {
1252    fn as_ink_feature(self: Handle<Self>) -> AnyInkFeature {
1253        AnyInkFeature {
1254            id: self.id(),
1255            vtable: const { &InkFeatureVTable::of::<F>() },
1256        }
1257    }
1258}
1259
1260/// The vtable of an erased [`AnyInkFeature`]: one `&'static` table per leaf type.
1261struct InkFeatureVTable {
1262    type_name: fn() -> &'static str,
1263    paint: fn(&mut App, HandleId, &mut Canvas),
1264    dispose: fn(&mut App, HandleId),
1265    controller: fn(&App, HandleId) -> AnyMaterialInkController,
1266    reference_box: fn(&App, HandleId) -> AnyRenderBox,
1267    debug_disposed: fn(&App, HandleId) -> bool,
1268}
1269
1270impl InkFeatureVTable {
1271    const fn of<F: InkFeatureLeaf>() -> InkFeatureVTable {
1272        InkFeatureVTable {
1273            type_name: std::any::type_name::<F>,
1274            paint: |app, id, canvas| InkFeature::paint(resolve::<F>(id), app, canvas),
1275            dispose: |app, id| F::dispose(resolve(id), app),
1276            controller: |app, id| InkFeature::controller(resolve::<F>(id), app),
1277            reference_box: |app, id| InkFeature::reference_box(resolve::<F>(id), app),
1278            debug_disposed: |app, id| app.get(resolve::<F>(id)).ink_feature().debug_disposed,
1279        }
1280    }
1281}
1282
1283/// Erased `InkFeature`: one identity and a static vtable.
1284///
1285/// Equality is Dart's `==` on an object reference.
1286#[derive(Clone, Copy)]
1287pub struct AnyInkFeature {
1288    id: HandleId,
1289    vtable: &'static InkFeatureVTable,
1290}
1291
1292impl fmt::Debug for AnyInkFeature {
1293    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1294        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
1295    }
1296}
1297
1298impl AnyInkFeature {
1299    /// The arena id behind this handle.
1300    pub fn id(self) -> HandleId {
1301        self.id
1302    }
1303
1304    /// Dart's `feature as T`: the typed handle when this feature is a `T`, else `None`.
1305    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
1306        app.handle::<T>(self.id)
1307    }
1308
1309    /// See [`InkFeature::controller`].
1310    pub fn controller(self, app: &App) -> AnyMaterialInkController {
1311        (self.vtable.controller)(app, self.id)
1312    }
1313
1314    /// See [`InkFeature::reference_box`].
1315    pub fn reference_box(self, app: &App) -> AnyRenderBox {
1316        (self.vtable.reference_box)(app, self.id)
1317    }
1318
1319    /// See [`InkFeatureLeaf::dispose`].
1320    pub fn dispose(self, app: &mut App) {
1321        (self.vtable.dispose)(app, self.id);
1322    }
1323
1324    /// Dart's private `_paint`.
1325    fn paint(self, app: &mut App, canvas: &mut Canvas) {
1326        (self.vtable.paint)(app, self.id, canvas);
1327    }
1328
1329    /// Dart's private `_debugDisposed`.
1330    fn debug_disposed(self, app: &App) -> bool {
1331        (self.vtable.debug_disposed)(app, self.id)
1332    }
1333}
1334
1335/// Dart's abstract `InkFeature`: a visual reaction on a piece of [`Material`].
1336///
1337/// To add an ink feature to a piece of [`Material`], obtain the
1338/// [`MaterialInkController`] via [`Material::of`] and call
1339/// [`MaterialInkController::add_ink_feature`].
1340///
1341/// Its bodies are associated fns taking the leaf's `Handle`; a leaf's override calls one
1342/// where Dart writes `super`. Its fields are [`InkFeatureData`].
1343pub struct InkFeature;
1344
1345impl InkFeature {
1346    /// The [`MaterialInkController`] associated with this [`InkFeature`].
1347    ///
1348    /// Typically used by subclasses to call
1349    /// [`MaterialInkController::mark_needs_paint`] when they need to repaint.
1350    pub fn controller<F: InkFeatureLeaf>(this: Handle<F>, app: &App) -> AnyMaterialInkController {
1351        app.get(this)
1352            .ink_feature()
1353            .controller
1354            .as_material_ink_controller()
1355    }
1356
1357    /// The render box whose visual position defines the frame of reference for this ink
1358    /// feature.
1359    pub fn reference_box<F: InkFeatureLeaf>(this: Handle<F>, app: &App) -> AnyRenderBox {
1360        app.get(this).ink_feature().reference_box
1361    }
1362
1363    /// Called when the ink feature is no longer visible on the material.
1364    pub fn on_removed<F: InkFeatureLeaf>(this: Handle<F>, app: &App) -> Option<Listener> {
1365        app.get(this).ink_feature().on_removed.clone()
1366    }
1367
1368    /// Dart's `InkFeature.dispose`: frees up the resources associated with this ink feature.
1369    /// The feature itself goes once the controller's list and its owner let go of it.
1370    pub fn dispose<F: InkFeatureLeaf>(this: Handle<F>, app: &mut App) {
1371        debug_assert!(!app.get(this).ink_feature().debug_disposed);
1372        if cfg!(debug_assertions) {
1373            app.get_mut(this).ink_feature_mut().debug_disposed = true;
1374        }
1375        let controller = RenderHandle::from_handle(app.get(this).ink_feature().controller);
1376        controller.remove_feature(app, this.as_ink_feature());
1377        if let Some(on_removed) = InkFeature::on_removed(this, app) {
1378            on_removed.call(app);
1379        }
1380    }
1381
1382    // Returns the paint transform that allows `fromRenderObject` to perform paint
1383    // in `toRenderObject`'s coordinate space.
1384    //
1385    // Returns null if either `fromRenderObject` or `toRenderObject` is not in the
1386    // same render tree, or either of them is in an offscreen subtree (see
1387    // RenderObject.paintsChild).
1388    fn get_paint_transform(
1389        app: &App,
1390        from_render_object: AnyRenderObject,
1391        to_render_object: AnyRenderObject,
1392    ) -> Option<Matrix4> {
1393        // The paths to fromRenderObject and toRenderObject's common ancestor.
1394        let mut from_path = vec![from_render_object];
1395        let mut to_path = vec![to_render_object];
1396
1397        let mut from = from_render_object;
1398        let mut to = to_render_object;
1399
1400        while from != to {
1401            let from_depth = from.depth(app);
1402            let to_depth = to.depth(app);
1403
1404            if from_depth >= to_depth {
1405                let from_parent = from.parent(app);
1406                // Return early if the 2 render objects are not in the same render tree,
1407                // or either of them is offscreen and thus won't get painted.
1408                let from_parent = from_parent.filter(|parent| parent.paints_child(app, from))?;
1409                from_path.push(from_parent);
1410                from = from_parent;
1411            }
1412
1413            if from_depth <= to_depth {
1414                let to_parent = to.parent(app);
1415                let to_parent = to_parent.filter(|parent| parent.paints_child(app, to))?;
1416                to_path.push(to_parent);
1417                to = to_parent;
1418            }
1419        }
1420        debug_assert!(from == to);
1421
1422        let mut transform = Matrix4::IDENTITY;
1423        let mut inverse_transform = Matrix4::IDENTITY;
1424
1425        for index in (1..to_path.len()).rev() {
1426            to_path[index].apply_paint_transform(app, to_path[index - 1], &mut transform);
1427        }
1428        for index in (1..from_path.len()).rev() {
1429            from_path[index].apply_paint_transform(
1430                app,
1431                from_path[index - 1],
1432                &mut inverse_transform,
1433            );
1434        }
1435
1436        inverse_transform
1437            .invert()
1438            .map(|inverse_transform| inverse_transform.then(&transform))
1439    }
1440
1441    /// Dart's private `_paint`.
1442    fn paint<F: InkFeatureLeaf>(this: Handle<F>, app: &mut App, canvas: &mut Canvas) {
1443        let reference_box = InkFeature::reference_box(this, app);
1444        debug_assert!(reference_box.as_object().attached(app));
1445        debug_assert!(!app.get(this).ink_feature().debug_disposed);
1446        // determine the transform that gets our coordinate system to be like theirs
1447        let controller = RenderHandle::from_handle(app.get(this).ink_feature().controller);
1448        let transform =
1449            InkFeature::get_paint_transform(app, controller.as_object(), reference_box.as_object());
1450        if let Some(transform) = transform {
1451            this.paint_feature(app, canvas, &transform);
1452        }
1453    }
1454}
1455
1456/// An interpolation between two [`ShapeBorder`]s.
1457///
1458/// This class specializes the interpolation of `Tween` to use `ShapeBorder::lerp`.
1459///
1460/// A value rather than an arena object, as waft-widgets' `DecorationTween`: a driven
1461/// animation holds a clone.
1462#[derive(Clone, Debug)]
1463pub struct ShapeBorderTween {
1464    /// The value this variable has at the beginning of the animation.
1465    pub begin: Option<ShapeBorderRef>,
1466
1467    /// The value this variable has at the end of the animation.
1468    pub end: Option<ShapeBorderRef>,
1469}
1470
1471impl ShapeBorderTween {
1472    /// Creates a [`ShapeBorder`] tween.
1473    ///
1474    /// the [`begin`](Self::begin) and [`end`](Self::end) properties may be null; see
1475    /// `ShapeBorder::lerp` for the null handling semantics.
1476    pub fn new(begin: Option<ShapeBorderRef>, end: Option<ShapeBorderRef>) -> ShapeBorderTween {
1477        ShapeBorderTween { begin, end }
1478    }
1479
1480    /// Returns the value this tween has at the given animation clock value.
1481    pub fn lerp(&self, t: f64) -> Option<ShapeBorderRef> {
1482        ShapeBorderRef::lerp(self.begin.as_ref(), self.end.as_ref(), t)
1483    }
1484}
1485
1486/// Dart's `Tween.transform`, which hands back the nullable endpoints themselves at 0 and 1.
1487impl Animatable<Option<ShapeBorderRef>> for ShapeBorderTween {
1488    fn transform(&self, _app: &App, t: f64) -> Option<ShapeBorderRef> {
1489        if t == 0.0 {
1490            return self.begin.clone();
1491        }
1492        if t == 1.0 {
1493            return self.end.clone();
1494        }
1495        self.lerp(t)
1496    }
1497}
1498
1499/// Dart's `Tween<ShapeBorder?>`: an unset endpoint and a null one are the same.
1500impl TweenSlot for ShapeBorderTween {
1501    type Value = Option<ShapeBorderRef>;
1502
1503    fn begin(&self, _app: &App) -> Option<Option<ShapeBorderRef>> {
1504        self.begin.clone().map(Some)
1505    }
1506
1507    fn set_begin(&mut self, _app: &mut App, begin: Option<Option<ShapeBorderRef>>) {
1508        self.begin = begin.flatten();
1509    }
1510
1511    fn end(&self, _app: &App) -> Option<Option<ShapeBorderRef>> {
1512        self.end.clone().map(Some)
1513    }
1514
1515    fn set_end(&mut self, _app: &mut App, end: Option<Option<ShapeBorderRef>>) {
1516        self.end = end.flatten();
1517    }
1518}
1519
1520/// The interior of non-transparent material.
1521///
1522/// Animates [`elevation`](Self::elevation), [`shadow_color`](Self::shadow_color), and
1523/// [`shape`](Self::shape).
1524///
1525/// Dart's `_MaterialInterior`.
1526#[derive(Debug)]
1527struct MaterialInterior {
1528    implicitly_animated_widget: ImplicitlyAnimatedWidgetData,
1529
1530    /// The widget below this widget in the tree.
1531    child: WidgetRef,
1532
1533    /// The border of the widget.
1534    ///
1535    /// This border will be painted, and in addition the outer path of the border
1536    /// determines the physical shape.
1537    shape: ShapeBorderRef,
1538
1539    /// Whether to paint the border in front of the child.
1540    ///
1541    /// The default value is true.
1542    /// If false, the border will be painted behind the child.
1543    border_on_foreground: bool,
1544
1545    /// The content will be clipped (or not) according to this option.
1546    ///
1547    /// Defaults to [`Clip::None`].
1548    clip_behavior: Clip,
1549
1550    /// The target z-coordinate at which to place this physical object relative
1551    /// to its parent.
1552    ///
1553    /// The value is non-negative.
1554    elevation: f64,
1555
1556    /// The target background color.
1557    color: Color,
1558
1559    /// The target shadow color.
1560    shadow_color: Color,
1561
1562    /// The target surface tint color.
1563    surface_tint_color: Option<Color>,
1564}
1565
1566impl MaterialInterior {
1567    /// Creates a const instance of [`MaterialInterior`].
1568    ///
1569    /// The [`elevation`](Self::elevation) must be specified and greater than or equal to zero.
1570    fn new(
1571        child: WidgetRef,
1572        shape: ShapeBorderRef,
1573        elevation: f64,
1574        color: Color,
1575        shadow_color: Color,
1576        surface_tint_color: Option<Color>,
1577        duration: Duration,
1578    ) -> MaterialInterior {
1579        debug_assert!(elevation >= 0.0);
1580        MaterialInterior {
1581            implicitly_animated_widget: ImplicitlyAnimatedWidgetData::new(duration),
1582            child,
1583            shape,
1584            border_on_foreground: true,
1585            clip_behavior: Clip::None,
1586            elevation,
1587            color,
1588            shadow_color,
1589            surface_tint_color,
1590        }
1591    }
1592
1593    fn curve(mut self, curve: Rc<dyn waft_animation::Curve>) -> MaterialInterior {
1594        self.implicitly_animated_widget.curve = curve;
1595        self
1596    }
1597}
1598
1599impl ImplicitlyAnimatedWidget for MaterialInterior {
1600    waft_widgets::implicitly_animated_widget_accessors!();
1601}
1602
1603impl StatefulWidget for MaterialInterior {
1604    type State = MaterialInteriorState;
1605
1606    fn key(&self) -> Option<&KeyRef> {
1607        self.implicitly_animated_widget.key.as_ref()
1608    }
1609
1610    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
1611        ImplicitlyAnimatedWidgetData::debug_fill_properties(
1612            &self.implicitly_animated_widget,
1613            properties,
1614        );
1615        properties.add(DiagnosticsProperty::<ShapeBorderRef>::new(
1616            "shape",
1617            self.shape.clone(),
1618        ));
1619        properties.add(DoubleProperty::new("elevation", self.elevation));
1620        properties.add(ColorProperty::new("color", self.color));
1621        properties.add(ColorProperty::new("shadowColor", self.shadow_color));
1622    }
1623
1624    fn create_state(&self) -> MaterialInteriorState {
1625        MaterialInteriorState {
1626            state: StateData::new(),
1627            single_ticker_provider: SingleTickerProviderStateMixinData::new(),
1628            implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData::new(),
1629            elevation: None,
1630            surface_tint_color: None,
1631            shadow_color: None,
1632            border: None,
1633        }
1634    }
1635}
1636
1637/// Dart's `_MaterialInteriorState`.
1638struct MaterialInteriorState {
1639    state: StateData<MaterialInterior>,
1640    single_ticker_provider: SingleTickerProviderStateMixinData,
1641    implicitly_animated_widget_state: ImplicitlyAnimatedWidgetStateData,
1642    elevation: Option<Ref<Tween<f64>>>,
1643    surface_tint_color: Option<Ref<ColorTween>>,
1644    shadow_color: Option<Ref<ColorTween>>,
1645    border: Option<ShapeBorderTween>,
1646}
1647
1648impl SingleTickerProviderStateMixin for MaterialInteriorState {
1649    fn single_ticker_provider_data(
1650        self: Handle<Self>,
1651        app: &App,
1652    ) -> &SingleTickerProviderStateMixinData {
1653        &app.get(self).single_ticker_provider
1654    }
1655
1656    fn single_ticker_provider_data_mut(
1657        self: Handle<Self>,
1658        app: &mut App,
1659    ) -> &mut SingleTickerProviderStateMixinData {
1660        &mut app.get_mut(self).single_ticker_provider
1661    }
1662}
1663
1664impl TickerProviderObject for MaterialInteriorState {
1665    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1666        SingleTickerProviderStateMixin::create_ticker(self, app, on_tick)
1667    }
1668}
1669
1670impl ImplicitlyAnimatedWidgetState for MaterialInteriorState {
1671    waft_widgets::implicitly_animated_widget_state_accessors!();
1672
1673    fn for_each_tween<V: TweenVisitor>(self: Handle<Self>, app: &mut App, visitor: &mut V) {
1674        let tween = app.get(self).elevation.clone();
1675        let target = Some(self.widget(app).elevation);
1676        app.get_mut(self).elevation = visitor.visit(app, tween, target, |app, value| {
1677            Tween::new(app, Some(*value), None)
1678        });
1679        let tween = app.get(self).shadow_color.clone();
1680        let target = Some(Some(self.widget(app).shadow_color));
1681        app.get_mut(self).shadow_color = visitor.visit(app, tween, target, |app, value| {
1682            ColorTween::new(app, *value, None)
1683        });
1684        let surface_tint_color = self.widget(app).surface_tint_color;
1685        app.get_mut(self).surface_tint_color = if surface_tint_color.is_some() {
1686            let tween = app.get(self).surface_tint_color.clone();
1687            visitor.visit(app, tween, Some(surface_tint_color), |app, value| {
1688                ColorTween::new(app, *value, None)
1689            })
1690        } else {
1691            None
1692        };
1693        let tween = app.get(self).border.clone();
1694        let target = Some(Some(self.widget(app).shape.clone()));
1695        app.get_mut(self).border = visitor.visit(app, tween, target, |_app, value| {
1696            ShapeBorderTween::new(value.clone(), None)
1697        });
1698    }
1699}
1700
1701impl AnimatedWidgetBaseState for MaterialInteriorState {}
1702
1703impl State for MaterialInteriorState {
1704    type Widget = MaterialInterior;
1705    waft_widgets::state_accessors!();
1706
1707    fn init_state(self: Handle<Self>, app: &mut App) {
1708        AnimatedWidgetBaseState::init_state(self, app);
1709    }
1710
1711    fn activate(self: Handle<Self>, app: &mut App) {
1712        SingleTickerProviderStateMixin::activate(self, app);
1713    }
1714
1715    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &MaterialInterior) {
1716        ImplicitlyAnimatedWidgetState::did_update_widget(self, app, old_widget);
1717    }
1718
1719    fn dispose(self: Handle<Self>, app: &mut App) {
1720        ImplicitlyAnimatedWidgetState::dispose(self, app);
1721    }
1722
1723    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1724        let animation = self.animation(app);
1725        let state = app.get(self);
1726        let border = state.border.clone().expect("for_each_tween made the tween");
1727        let elevation_tween = state
1728            .elevation
1729            .clone()
1730            .expect("for_each_tween made the tween");
1731        let surface_tint_color = state.surface_tint_color.clone();
1732        let shadow_color_tween = state
1733            .shadow_color
1734            .clone()
1735            .expect("for_each_tween made the tween");
1736        let shape = border
1737            .evaluate(app, animation)
1738            .expect("the shape tween has a shape");
1739        let elevation = elevation_tween.evaluate(app, animation);
1740        let widget_color = self.widget(app).color;
1741        let color = if Theme::of(app, context).use_material3 {
1742            let surface_tint_color =
1743                surface_tint_color.and_then(|tween| tween.evaluate(app, animation));
1744            ElevationOverlay::apply_surface_tint(widget_color, surface_tint_color, elevation)
1745        } else {
1746            ElevationOverlay::apply_overlay(app, context, widget_color, elevation)
1747        };
1748        let shadow_color = shadow_color_tween
1749            .evaluate(app, animation)
1750            .expect("the shadow color tween has a color");
1751
1752        let widget = self.widget(app);
1753        let clip_behavior = widget.clip_behavior;
1754        let border_on_foreground = widget.border_on_foreground;
1755        let child = widget.child.clone();
1756        let text_direction = Directionality::maybe_of(app, context);
1757        let clipper: Rc<dyn CustomClipper<Path>> =
1758            Rc::new(ShapeBorderClipper::new(shape.clone(), text_direction));
1759        PhysicalShape::new(clipper, color)
1760            .clip_behavior(clip_behavior)
1761            .elevation(elevation)
1762            .shadow_color(shadow_color)
1763            .child(ShapeBorderPaint::new(child, shape).border_on_foreground(border_on_foreground))
1764            .into_widget()
1765    }
1766}
1767
1768/// Dart's `_ShapeBorderPaint`.
1769#[derive(Debug)]
1770struct ShapeBorderPaint {
1771    child: WidgetRef,
1772    shape: ShapeBorderRef,
1773    border_on_foreground: bool,
1774}
1775
1776impl ShapeBorderPaint {
1777    fn new(child: WidgetRef, shape: ShapeBorderRef) -> ShapeBorderPaint {
1778        ShapeBorderPaint {
1779            child,
1780            shape,
1781            border_on_foreground: true,
1782        }
1783    }
1784
1785    fn border_on_foreground(mut self, border_on_foreground: bool) -> ShapeBorderPaint {
1786        self.border_on_foreground = border_on_foreground;
1787        self
1788    }
1789}
1790
1791impl StatelessWidget for ShapeBorderPaint {
1792    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
1793        let painter =
1794            ShapeBorderPainter::new(self.shape.clone(), Directionality::maybe_of(app, context));
1795        let paint = CustomPaint::new().child(self.child.clone());
1796        if self.border_on_foreground {
1797            paint.foreground_painter(painter)
1798        } else {
1799            paint.painter(painter)
1800        }
1801        .into_widget()
1802    }
1803}
1804
1805/// Dart's `_ShapeBorderPainter`.
1806struct ShapeBorderPainter {
1807    border: ShapeBorderRef,
1808    text_direction: Option<TextDirection>,
1809}
1810
1811impl ShapeBorderPainter {
1812    fn new(border: ShapeBorderRef, text_direction: Option<TextDirection>) -> ShapeBorderPainter {
1813        ShapeBorderPainter {
1814            border,
1815            text_direction,
1816        }
1817    }
1818}
1819
1820impl CustomPainter for ShapeBorderPainter {
1821    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
1822        self.border
1823            .paint(canvas, Offset::ZERO & size, self.text_direction);
1824    }
1825
1826    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
1827        let old_delegate = old_delegate
1828            .as_any()
1829            .downcast_ref::<ShapeBorderPainter>()
1830            .expect("compared with a painter of its own type");
1831        old_delegate.border != self.border
1832    }
1833
1834    fn as_any(&self) -> &dyn Any {
1835        self
1836    }
1837}
1838
1839#[cfg(test)]
1840mod tests {
1841    use std::cell::{Cell, RefCell};
1842    use waft_painting::ShapeBorder;
1843
1844    use waft_embedder::{Paint, TargetPlatform, TextDirection, ViewId, ViewRef};
1845    use waft_foundation::AppCell;
1846    use waft_painting::StadiumBorder;
1847    use waft_rendering::{
1848        RenderClipPath, RenderCustomClip, RenderCustomPaint, RenderPhysicalModel,
1849        RenderPhysicalModelBase, RenderPhysicalShape,
1850    };
1851    use waft_test::{TestPlatform, TestView};
1852    use waft_widgets::{
1853        Builder, Center, Column, Container, Expanded, ListView, Notification, Offstage,
1854        PlainLayoutChangedNotification, SizedBox, Stack, View, ViewAnchor,
1855    };
1856
1857    use waft_widgets::testing::{TestPointer, WidgetTester, test_widgets};
1858
1859    use super::*;
1860    use crate::color_scheme::ColorScheme;
1861    use crate::colors::Colors;
1862    use crate::ink_well::InkWell;
1863    use crate::test_support::{build, test_view};
1864    use crate::theme_data::ThemeData;
1865
1866    /// Dart's `buildMaterial`.
1867    fn build_material(
1868        elevation: f64,
1869        shadow_color: Color,
1870        surface_tint_color: Option<Color>,
1871        color: Color,
1872    ) -> Material {
1873        let mut material = Material::new()
1874            .color(color)
1875            .shadow_color(shadow_color)
1876            .elevation(elevation)
1877            .shape(CircleBorder::default());
1878        material.surface_tint_color = surface_tint_color;
1879        material
1880    }
1881
1882    fn centered(material: Material) -> WidgetRef {
1883        Center::new()
1884            .child(SizedBox::square(Some(100.0)).child(material))
1885            .into_widget()
1886    }
1887
1888    const GREEN: Color = Color::new(0xFF00FF00);
1889    const BLUE: Color = Color::new(0xFF0000FF);
1890
1891    fn default_material(elevation: f64) -> WidgetRef {
1892        centered(build_material(elevation, GREEN, None, BLUE))
1893    }
1894
1895    fn themed(
1896        tester: &WidgetTester,
1897        theme: impl FnOnce(&App) -> ThemeData,
1898        child: WidgetRef,
1899    ) -> WidgetRef {
1900        let data = theme(&tester.cell.borrow());
1901        Theme::new(data, child).into_widget()
1902    }
1903
1904    fn model(tester: &WidgetTester) -> RenderHandle<RenderPhysicalShape> {
1905        tester.first::<RenderPhysicalShape>()
1906    }
1907
1908    fn shape_of(tester: &WidgetTester) -> ShapeBorderRef {
1909        let model = model(tester);
1910        let app = tester.cell.borrow();
1911        let clipper = RenderCustomClip::clipper(model, &app).expect("a shape clipper");
1912        clipper
1913            .as_any()
1914            .downcast_ref::<ShapeBorderClipper>()
1915            .expect("a ShapeBorderClipper")
1916            .shape
1917            .clone()
1918    }
1919
1920    // Regression test for https://github.com/flutter/flutter/issues/81504
1921    #[test]
1922    fn shadow_color_defaults() {
1923        test_widgets(|tester| {
1924            let build_with_shadow = |shadow_color: Option<Color>| {
1925                let mut material = Material::new()
1926                    .elevation(10.0)
1927                    .shape(CircleBorder::default());
1928                material.shadow_color = shadow_color;
1929                centered(material)
1930            };
1931
1932            // Default M2 shadow color
1933            let widget = themed(
1934                tester,
1935                |app| ThemeData::builder().use_material3(false).build(app),
1936                build_with_shadow(None),
1937            );
1938            tester.pump_widget(widget);
1939            tester.pump_and_settle();
1940            let expected = ThemeData::new(&tester.cell.borrow()).shadow_color;
1941            assert_eq!(model(tester).shadow_color(&tester.cell.borrow()), expected);
1942
1943            // Default M3 shadow color
1944            let widget = themed(tester, ThemeData::new, build_with_shadow(None));
1945            tester.pump_widget(widget);
1946            tester.pump_and_settle();
1947            let expected = ThemeData::new(&tester.cell.borrow()).color_scheme.shadow();
1948            assert_eq!(model(tester).shadow_color(&tester.cell.borrow()), expected);
1949
1950            // Drop shadow can be turned off with a transparent color.
1951            let widget = themed(
1952                tester,
1953                ThemeData::new,
1954                build_with_shadow(Some(Colors::TRANSPARENT)),
1955            );
1956            tester.pump_widget(widget);
1957            tester.pump_and_settle();
1958            assert_eq!(
1959                model(tester).shadow_color(&tester.cell.borrow()),
1960                Colors::TRANSPARENT
1961            );
1962        });
1963    }
1964
1965    #[test]
1966    fn shadows_animate_smoothly() {
1967        // This code verifies that the PhysicalModel's elevation animates over
1968        // a kThemeChangeDuration time interval.
1969        test_widgets(|tester| {
1970            tester.pump_widget(default_material(0.0));
1971            assert_eq!(model(tester).elevation(&tester.cell.borrow()), 0.0);
1972
1973            tester.pump_widget(default_material(9.0));
1974            assert_eq!(model(tester).elevation(&tester.cell.borrow()), 0.0);
1975
1976            tester.pump_by(Duration::from_millis(1));
1977            waft_widgets::testing::assert_more_or_less_equals_within(
1978                model(tester).elevation(&tester.cell.borrow()),
1979                0.0,
1980                0.001,
1981            );
1982
1983            tester.pump_by(K_THEME_CHANGE_DURATION / 2);
1984            assert!(model(tester).elevation(&tester.cell.borrow()).abs() >= 0.001);
1985
1986            tester.pump_by(K_THEME_CHANGE_DURATION);
1987            assert_eq!(model(tester).elevation(&tester.cell.borrow()), 9.0);
1988        });
1989    }
1990
1991    /// A shape with Dart's default `==`, identity, as a user's own border has.
1992    #[derive(Clone, Copy, Debug)]
1993    struct IdentityShape;
1994
1995    impl ShapeBorder for IdentityShape {
1996        fn dimensions(&self) -> waft_painting::EdgeInsetsGeometry {
1997            waft_painting::EdgeInsetsGeometry::ZERO
1998        }
1999
2000        fn scale(&self, _t: f64) -> ShapeBorderRef {
2001            ShapeBorderRef::new(*self)
2002        }
2003
2004        fn get_outer_path(
2005            &self,
2006            rect: waft_embedder::Rect,
2007            _text_direction: Option<TextDirection>,
2008        ) -> waft_embedder::Path {
2009            let mut path = waft_embedder::PathBuilder::new();
2010            path.rect(rect.into());
2011            waft_embedder::Path::new(path.build())
2012        }
2013
2014        fn get_inner_path(
2015            &self,
2016            rect: waft_embedder::Rect,
2017            text_direction: Option<TextDirection>,
2018        ) -> waft_embedder::Path {
2019            self.get_outer_path(rect, text_direction)
2020        }
2021
2022        fn paint(
2023            &self,
2024            _canvas: &mut waft_embedder::Canvas,
2025            _rect: waft_embedder::Rect,
2026            _text_direction: Option<TextDirection>,
2027        ) {
2028        }
2029
2030        fn as_any(&self) -> &dyn Any {
2031            self
2032        }
2033    }
2034
2035    // ---- not in material_test.dart: a shape compared by identity ----
2036
2037    #[test]
2038    fn a_material_given_its_own_shape_again_does_not_animate_its_shape() {
2039        test_widgets(|tester| {
2040            let shaped = |shape: &ShapeBorderRef| {
2041                centered(Material::new().color(GREEN).shape(shape.clone()))
2042            };
2043            let transient_callbacks = |tester: &WidgetTester| {
2044                waft_scheduler::SchedulerBinding::transient_callback_count(
2045                    &mut tester.cell.borrow_mut(),
2046                )
2047            };
2048            let shape = ShapeBorderRef::new(IdentityShape);
2049            tester.pump_widget(shaped(&shape));
2050            tester.pump_by(K_THEME_CHANGE_DURATION);
2051
2052            tester.pump_widget(shaped(&shape));
2053            assert_eq!(
2054                transient_callbacks(tester),
2055                0,
2056                "the same shape is no new target"
2057            );
2058            assert_eq!(shape_of(tester), shape);
2059
2060            tester.pump_widget(shaped(&ShapeBorderRef::new(IdentityShape)));
2061            assert_eq!(
2062                transient_callbacks(tester),
2063                1,
2064                "another shape of the same type is, as Dart's identity `==` makes it"
2065            );
2066        });
2067    }
2068
2069    /// Dart's `isSameColorAs` matcher, with its default threshold.
2070    fn is_same_color_as(a: Color, b: Color) -> bool {
2071        const THRESHOLD: f64 = 0.004;
2072        (a.a - b.a).abs() <= THRESHOLD
2073            && (a.r - b.r).abs() <= THRESHOLD
2074            && (a.g - b.g).abs() <= THRESHOLD
2075            && (a.b - b.b).abs() <= THRESHOLD
2076    }
2077
2078    fn within_one(a: Color, b: Color) -> bool {
2079        let channels = |color: Color| [color.a, color.r, color.g, color.b].map(|c| c * 255.0);
2080        channels(a)
2081            .iter()
2082            .zip(channels(b))
2083            .all(|(a, b)| (a - b).abs() <= 1.0)
2084    }
2085
2086    #[test]
2087    fn shadow_colors_animate_smoothly() {
2088        // This code verifies that the PhysicalModel's shadowColor animates over
2089        // a kThemeChangeDuration time interval.
2090        test_widgets(|tester| {
2091            let red = Color::new(0xFFFF0000);
2092            tester.pump_widget(default_material(0.0));
2093            assert_eq!(model(tester).shadow_color(&tester.cell.borrow()), GREEN);
2094
2095            tester.pump_widget(centered(build_material(0.0, red, None, BLUE)));
2096            assert_eq!(model(tester).shadow_color(&tester.cell.borrow()), GREEN);
2097
2098            tester.pump_by(Duration::from_millis(1));
2099            assert!(within_one(
2100                model(tester).shadow_color(&tester.cell.borrow()),
2101                GREEN
2102            ));
2103
2104            tester.pump_by(K_THEME_CHANGE_DURATION / 2);
2105            assert!(!within_one(
2106                model(tester).shadow_color(&tester.cell.borrow()),
2107                GREEN
2108            ));
2109
2110            tester.pump_by(K_THEME_CHANGE_DURATION);
2111            assert_eq!(model(tester).shadow_color(&tester.cell.borrow()), red);
2112        });
2113    }
2114
2115    #[test]
2116    fn apply_elevation_overlay_color_does_not_effect_anything_with_use_material3_set_to_true() {
2117        test_widgets(|tester| {
2118            let surface_color = Color::new(0xFF121212);
2119            let widget = themed(
2120                tester,
2121                |app| {
2122                    ThemeData::builder()
2123                        .apply_elevation_overlay_color(true)
2124                        .color_scheme(ColorScheme::dark().with_surface(surface_color))
2125                        .build(app)
2126                },
2127                centered(build_material(8.0, GREEN, None, surface_color)),
2128            );
2129            tester.pump_widget(widget);
2130            assert_eq!(model(tester).color(&tester.cell.borrow()), surface_color);
2131        });
2132    }
2133
2134    #[test]
2135    fn surface_tint_color_is_used_to_as_an_overlay_to_indicate_elevation() {
2136        test_widgets(|tester| {
2137            let base_color = Color::new(0xFF121212);
2138            let surface_tint_color = Color::new(0xff44ccff);
2139
2140            // With no surfaceTintColor specified, it should not apply an overlay
2141            let widget = themed(
2142                tester,
2143                ThemeData::new,
2144                centered(build_material(12.0, GREEN, None, base_color)),
2145            );
2146            tester.pump_widget(widget);
2147            tester.pump_and_settle();
2148            assert_eq!(model(tester).color(&tester.cell.borrow()), base_color);
2149
2150            // With transparent surfaceTintColor, it should not apply an overlay
2151            let widget = themed(
2152                tester,
2153                ThemeData::new,
2154                centered(build_material(
2155                    12.0,
2156                    GREEN,
2157                    Some(Colors::TRANSPARENT),
2158                    base_color,
2159                )),
2160            );
2161            tester.pump_widget(widget);
2162            tester.pump_and_settle();
2163            assert_eq!(model(tester).color(&tester.cell.borrow()), base_color);
2164
2165            // With surfaceTintColor specified, it should not apply an overlay based
2166            // on the elevation.
2167            let widget = themed(
2168                tester,
2169                ThemeData::new,
2170                centered(build_material(
2171                    12.0,
2172                    GREEN,
2173                    Some(surface_tint_color),
2174                    base_color,
2175                )),
2176            );
2177            tester.pump_widget(widget);
2178            tester.pump_and_settle();
2179
2180            // Final color should be the base with a tint of 0.14 opacity or 0xff192c33
2181            assert!(is_same_color_as(
2182                model(tester).color(&tester.cell.borrow()),
2183                Color::new(0xff192c33)
2184            ));
2185        });
2186    }
2187
2188    #[test]
2189    fn apply_elevation_overlay_color_set_to_false_does_not_change_surface_color() {
2190        test_widgets(|tester| {
2191            let surface_color = Color::new(0xFF121212);
2192            let widget = themed(
2193                tester,
2194                |app| {
2195                    ThemeData::builder()
2196                        .use_material3(false)
2197                        .apply_elevation_overlay_color(false)
2198                        .color_scheme(ColorScheme::dark().with_surface(surface_color))
2199                        .build(app)
2200                },
2201                centered(build_material(8.0, GREEN, None, surface_color)),
2202            );
2203            tester.pump_widget(widget);
2204            assert_eq!(model(tester).color(&tester.cell.borrow()), surface_color);
2205        });
2206    }
2207
2208    #[test]
2209    fn apply_elevation_overlay_color_set_to_true_applies_a_semi_transparent_on_surface_color() {
2210        test_widgets(|tester| {
2211            let surface_color = Color::new(0xFF121212);
2212            let on_surface_color = Colors::GREEN_ACCENT.primary();
2213
2214            // The colors we should get with a base surface color of 0xFF121212 for
2215            // and a given elevation
2216            let elevation_colors = [
2217                (0.0, 0xFF121212),
2218                (1.0, 0xFF161D19),
2219                (2.0, 0xFF18211D),
2220                (3.0, 0xFF19241E),
2221                (4.0, 0xFF1A2620),
2222                (6.0, 0xFF1B2922),
2223                (8.0, 0xFF1C2C24),
2224                (12.0, 0xFF1D3027),
2225                (16.0, 0xFF1E3329),
2226                (24.0, 0xFF20362B),
2227            ];
2228
2229            for (elevation, color) in elevation_colors {
2230                let widget = themed(
2231                    tester,
2232                    |app| {
2233                        ThemeData::builder()
2234                            .use_material3(false)
2235                            .apply_elevation_overlay_color(true)
2236                            .color_scheme(
2237                                ColorScheme::dark()
2238                                    .with_surface(surface_color)
2239                                    .with_on_surface(on_surface_color),
2240                            )
2241                            .build(app)
2242                    },
2243                    centered(build_material(elevation, GREEN, None, surface_color)),
2244                );
2245                tester.pump_widget(widget);
2246                tester.pump_and_settle(); // wait for the elevation animation to finish
2247                let actual = model(tester).color(&tester.cell.borrow());
2248                assert!(
2249                    is_same_color_as(actual, Color::new(color)),
2250                    "elevation {elevation}: {actual:?}"
2251                );
2252            }
2253        });
2254    }
2255
2256    fn keyed(material: Material) -> (GlobalKey, WidgetRef) {
2257        let key = GlobalKey::new();
2258        let widget = material
2259            .key(key.clone().into())
2260            .child(SizedBox::new().width(100.0).height(100.0))
2261            .into_widget();
2262        (key, widget)
2263    }
2264
2265    #[test]
2266    fn transparency_clipping_no_clip_by_default() {
2267        test_widgets(|tester| {
2268            let (_key, widget) = keyed(Material::new().r#type(MaterialType::Transparency));
2269            tester.pump_widget(widget);
2270            let clip = tester.first::<RenderClipPath>();
2271            assert_eq!(
2272                RenderCustomClip::clip_behavior(clip, &tester.cell.borrow()),
2273                Clip::None
2274            );
2275        });
2276    }
2277
2278    fn clip_shape(tester: &WidgetTester) -> (Clip, ShapeBorderRef) {
2279        let clip = tester.first::<RenderClipPath>();
2280        let app = tester.cell.borrow();
2281        let clipper = RenderCustomClip::clipper(clip, &app).expect("a shape clipper");
2282        let shape = clipper
2283            .as_any()
2284            .downcast_ref::<ShapeBorderClipper>()
2285            .expect("a ShapeBorderClipper")
2286            .shape
2287            .clone();
2288        (RenderCustomClip::clip_behavior(clip, &app), shape)
2289    }
2290
2291    #[test]
2292    fn transparency_clipping_clips_to_bounding_rect_by_default_given_clip_anti_alias() {
2293        test_widgets(|tester| {
2294            let (_key, widget) = keyed(
2295                Material::new()
2296                    .r#type(MaterialType::Transparency)
2297                    .clip_behavior(Clip::AntiAlias),
2298            );
2299            tester.pump_widget(widget);
2300            let (clip_behavior, shape) = clip_shape(tester);
2301            assert_eq!(clip_behavior, Clip::AntiAlias);
2302            assert!(shape.eq_shape(&RoundedRectangleBorder::default()));
2303        });
2304    }
2305
2306    #[test]
2307    fn transparency_clipping_clips_to_rounded_rect_when_border_radius_provided() {
2308        test_widgets(|tester| {
2309            let radius = BorderRadius::all(Radius::circular(10.0));
2310            let (_key, widget) = keyed(
2311                Material::new()
2312                    .r#type(MaterialType::Transparency)
2313                    .border_radius(radius)
2314                    .clip_behavior(Clip::AntiAlias),
2315            );
2316            tester.pump_widget(widget);
2317            let (_, shape) = clip_shape(tester);
2318            assert!(shape.eq_shape(&RoundedRectangleBorder::new(
2319                BorderSide::NONE,
2320                radius.into()
2321            )));
2322        });
2323    }
2324
2325    #[test]
2326    fn transparency_clipping_clips_to_shape_when_provided() {
2327        test_widgets(|tester| {
2328            let (_key, widget) = keyed(
2329                Material::new()
2330                    .r#type(MaterialType::Transparency)
2331                    .shape(StadiumBorder::default())
2332                    .clip_behavior(Clip::AntiAlias),
2333            );
2334            tester.pump_widget(widget);
2335            let (_, shape) = clip_shape(tester);
2336            assert!(shape.eq_shape(&StadiumBorder::default()));
2337        });
2338    }
2339
2340    #[test]
2341    fn physical_models_canvas() {
2342        test_widgets(|tester| {
2343            let (_key, widget) = keyed(Material::new());
2344            tester.pump_widget(widget);
2345            let model = tester.first::<RenderPhysicalModel>();
2346            let app = tester.cell.borrow();
2347            assert_eq!(model.shape(&app), waft_painting::BoxShape::Rectangle);
2348            assert!(
2349                model
2350                    .border_radius(&app)
2351                    .is_none_or(|radius| radius == BorderRadius::ZERO)
2352            );
2353            assert_eq!(model.elevation(&app), 0.0);
2354        });
2355    }
2356
2357    fn assert_physical_shape(
2358        tester: &mut WidgetTester,
2359        material: Material,
2360        expected: impl ShapeBorder + 'static,
2361        elevation: f64,
2362    ) {
2363        let (_key, widget) = keyed(material);
2364        tester.pump_widget(widget);
2365        assert!(
2366            shape_of(tester).eq_shape(&expected),
2367            "{:?}",
2368            shape_of(tester)
2369        );
2370        assert_eq!(model(tester).elevation(&tester.cell.borrow()), elevation);
2371    }
2372
2373    fn rounded(radius: f64) -> RoundedRectangleBorder {
2374        RoundedRectangleBorder::new(
2375            BorderSide::NONE,
2376            BorderRadius::all(Radius::circular(radius)).into(),
2377        )
2378    }
2379
2380    #[test]
2381    fn physical_models_canvas_with_border_radius_and_elevation() {
2382        test_widgets(|tester| {
2383            assert_physical_shape(
2384                tester,
2385                Material::new()
2386                    .border_radius(BorderRadius::all(Radius::circular(5.0)))
2387                    .elevation(1.0),
2388                rounded(5.0),
2389                1.0,
2390            );
2391        });
2392    }
2393
2394    #[test]
2395    fn physical_models_canvas_with_shape_and_elevation() {
2396        test_widgets(|tester| {
2397            assert_physical_shape(
2398                tester,
2399                Material::new()
2400                    .shape(StadiumBorder::default())
2401                    .elevation(1.0),
2402                StadiumBorder::default(),
2403                1.0,
2404            );
2405        });
2406    }
2407
2408    #[test]
2409    fn physical_models_card() {
2410        test_widgets(|tester| {
2411            assert_physical_shape(
2412                tester,
2413                Material::new().r#type(MaterialType::Card),
2414                rounded(2.0),
2415                0.0,
2416            );
2417        });
2418    }
2419
2420    #[test]
2421    fn physical_models_card_with_border_radius_and_elevation() {
2422        test_widgets(|tester| {
2423            assert_physical_shape(
2424                tester,
2425                Material::new()
2426                    .r#type(MaterialType::Card)
2427                    .border_radius(BorderRadius::all(Radius::circular(5.0)))
2428                    .elevation(5.0),
2429                rounded(5.0),
2430                5.0,
2431            );
2432        });
2433    }
2434
2435    #[test]
2436    fn physical_models_card_with_shape_and_elevation() {
2437        test_widgets(|tester| {
2438            assert_physical_shape(
2439                tester,
2440                Material::new()
2441                    .r#type(MaterialType::Card)
2442                    .shape(StadiumBorder::default())
2443                    .elevation(5.0),
2444                StadiumBorder::default(),
2445                5.0,
2446            );
2447        });
2448    }
2449
2450    #[test]
2451    fn physical_models_circle() {
2452        test_widgets(|tester| {
2453            assert_physical_shape(
2454                tester,
2455                Material::new()
2456                    .r#type(MaterialType::Circle)
2457                    .color(Color::new(0xFF0000FF)),
2458                CircleBorder::default(),
2459                0.0,
2460            );
2461        });
2462    }
2463
2464    #[test]
2465    fn physical_models_button() {
2466        test_widgets(|tester| {
2467            assert_physical_shape(
2468                tester,
2469                Material::new()
2470                    .r#type(MaterialType::Button)
2471                    .color(Color::new(0xFF0000FF)),
2472                rounded(2.0),
2473                0.0,
2474            );
2475        });
2476    }
2477
2478    #[test]
2479    fn physical_models_button_with_elevation_and_border_radius() {
2480        test_widgets(|tester| {
2481            assert_physical_shape(
2482                tester,
2483                Material::new()
2484                    .r#type(MaterialType::Button)
2485                    .color(Color::new(0xFF0000FF))
2486                    .border_radius(BorderRadius::all(Radius::circular(6.0)))
2487                    .elevation(4.0),
2488                rounded(6.0),
2489                4.0,
2490            );
2491        });
2492    }
2493
2494    #[test]
2495    fn physical_models_button_with_elevation_and_shape() {
2496        test_widgets(|tester| {
2497            assert_physical_shape(
2498                tester,
2499                Material::new()
2500                    .r#type(MaterialType::Button)
2501                    .color(Color::new(0xFF0000FF))
2502                    .shape(StadiumBorder::default())
2503                    .elevation(4.0),
2504                StadiumBorder::default(),
2505                4.0,
2506            );
2507        });
2508    }
2509
2510    /// What the border painter of the material draws.
2511    fn border_draws(tester: &WidgetTester) -> (bool, Vec<waft_rendering::testing::RecordedCall>) {
2512        let paint = tester.first::<RenderCustomPaint>();
2513        let mut app = tester.cell.borrow_mut();
2514        let (foreground, painter) = match paint.foreground_painter(&app) {
2515            Some(painter) => (true, painter),
2516            None => (false, paint.painter(&app).expect("a border painter")),
2517        };
2518        let size = paint.size(&app);
2519        let mut canvas = Canvas::new();
2520        painter.paint(&mut app, &mut canvas, size);
2521        (
2522            foreground,
2523            crate::test_support::draw_calls(canvas.build().ops()),
2524        )
2525    }
2526
2527    fn circle_with_side() -> CircleBorder {
2528        CircleBorder::new(
2529            BorderSide::new(
2530                Color::new(0xFF0000FF),
2531                2.0,
2532                waft_painting::BorderStyle::Solid,
2533                BorderSide::STROKE_ALIGN_INSIDE,
2534            ),
2535            0.0,
2536        )
2537    }
2538
2539    #[test]
2540    fn border_is_painted_on_physical_layers() {
2541        test_widgets(|tester| {
2542            let (_key, widget) = keyed(
2543                Material::new()
2544                    .r#type(MaterialType::Button)
2545                    .color(Color::new(0xFF0000FF))
2546                    .shape(circle_with_side()),
2547            );
2548            tester.pump_widget(widget);
2549            let (foreground, draws) = border_draws(tester);
2550            assert!(foreground);
2551            assert_eq!(draws.len(), 1, "{draws:?}");
2552        });
2553    }
2554
2555    #[test]
2556    fn border_is_painted_for_transparent_material() {
2557        test_widgets(|tester| {
2558            let (_key, widget) = keyed(
2559                Material::new()
2560                    .r#type(MaterialType::Transparency)
2561                    .shape(circle_with_side()),
2562            );
2563            tester.pump_widget(widget);
2564            let (_, draws) = border_draws(tester);
2565            assert_eq!(draws.len(), 1, "{draws:?}");
2566        });
2567    }
2568
2569    #[test]
2570    fn border_is_not_painted_for_when_border_side_is_none() {
2571        test_widgets(|tester| {
2572            let (_key, widget) = keyed(
2573                Material::new()
2574                    .r#type(MaterialType::Transparency)
2575                    .shape(CircleBorder::default()),
2576            );
2577            tester.pump_widget(widget);
2578            let (_, draws) = border_draws(tester);
2579            assert!(draws.is_empty(), "{draws:?}");
2580        });
2581    }
2582
2583    /// The structure behind the `border_paint_above` and `border_paint_below` goldens.
2584    #[test]
2585    fn border_is_painted_above_the_child_by_default_and_below_when_specified() {
2586        test_widgets(|tester| {
2587            let (_key, widget) = keyed(Material::new().shape(rounded(8.0)));
2588            tester.pump_widget(widget);
2589            assert!(border_draws(tester).0, "a foreground painter");
2590
2591            let (_key, widget) = keyed(
2592                Material::new()
2593                    .shape(rounded(8.0))
2594                    .border_on_foreground(false),
2595            );
2596            tester.pump_widget(widget);
2597            assert!(!border_draws(tester).0, "a background painter");
2598        });
2599    }
2600
2601    /// Dart's `TrackPaintInkFeature`.
2602    struct TrackPaintInkFeature {
2603        ink_feature: InkFeatureData,
2604        paint_count: Rc<Cell<u32>>,
2605    }
2606
2607    impl InkFeatureLeafData for TrackPaintInkFeature {
2608        fn ink_feature(&self) -> &InkFeatureData {
2609            &self.ink_feature
2610        }
2611
2612        fn ink_feature_mut(&mut self) -> &mut InkFeatureData {
2613            &mut self.ink_feature
2614        }
2615    }
2616
2617    impl InkFeatureLeaf for TrackPaintInkFeature {
2618        fn paint_feature(
2619            self: Handle<Self>,
2620            app: &mut App,
2621            _canvas: &mut Canvas,
2622            _transform: &Matrix4,
2623        ) {
2624            let count = &app.get(self).paint_count;
2625            count.set(count.get() + 1);
2626        }
2627    }
2628
2629    fn offstage_material(
2630        material_key: &GlobalKey,
2631        sized_box_key: &GlobalKey,
2632        offstage: bool,
2633    ) -> WidgetRef {
2634        Material::new()
2635            .key(material_key.clone().into())
2636            .child(
2637                Offstage::new().offstage(offstage).child(
2638                    SizedBox::new()
2639                        .key(sized_box_key.clone().into())
2640                        .width(20.0)
2641                        .height(20.0),
2642                ),
2643            )
2644            .into_widget()
2645    }
2646
2647    fn ink_features_under(tester: &WidgetTester) -> RenderHandle<RenderInkFeatures> {
2648        tester.first::<RenderInkFeatures>()
2649    }
2650
2651    /// Paints the material's ink features as its `paint` does, onto a fresh canvas.
2652    fn repaint(tester: &WidgetTester) {
2653        let render = ink_features_under(tester);
2654        let mut canvas = Canvas::new();
2655        render.paint_ink_features(&mut tester.cell.borrow_mut(), &mut canvas, Offset::ZERO);
2656    }
2657
2658    #[test]
2659    fn ink_feature_skips_painting_if_intermediate_node_skips() {
2660        test_widgets(|tester| {
2661            let sized_box_key = GlobalKey::new();
2662            let material_key = GlobalKey::new();
2663            tester.pump_widget(offstage_material(&material_key, &sized_box_key, true));
2664            let paint_count = Rc::new(Cell::new(0));
2665            {
2666                let mut app = tester.cell.borrow_mut();
2667                let context = sized_box_key.current_context(&app).expect("mounted");
2668                let controller = Material::of(&app, context);
2669                let reference_box = context
2670                    .find_render_object(&app)
2671                    .and_then(|render_object| render_object.as_box())
2672                    .expect("a box");
2673                let ink_feature = InkFeatureData::new(&app, controller, reference_box, None);
2674                let tracker = app.create(TrackPaintInkFeature {
2675                    ink_feature,
2676                    paint_count: Rc::clone(&paint_count),
2677                });
2678                controller.add_ink_feature(&mut app, tracker.erase());
2679            }
2680            assert_eq!(paint_count.get(), 0);
2681
2682            // Force a repaint. Since it's offstage, the ink feature should not get painted.
2683            repaint(tester);
2684            assert_eq!(paint_count.get(), 0);
2685
2686            tester.pump_widget(offstage_material(&material_key, &sized_box_key, false));
2687            // Gets a paint because the global keys have reused the elements and it is
2688            // now onstage.
2689            assert_eq!(paint_count.get(), 1);
2690
2691            // Force a repaint again. This time, it gets repainted because it is onstage.
2692            repaint(tester);
2693            assert_eq!(paint_count.get(), 2);
2694
2695            let feature = ink_features_under(tester)
2696                .debug_ink_features(&tester.cell.borrow())
2697                .expect("added")[0];
2698            feature.dispose(&mut tester.cell.borrow_mut());
2699            assert!(
2700                ink_features_under(tester)
2701                    .debug_ink_features(&tester.cell.borrow())
2702                    .expect("added")
2703                    .is_empty()
2704            );
2705        });
2706    }
2707
2708    #[test]
2709    fn layout_changed_notification_test() {
2710        test_widgets(|tester| {
2711            tester.pump_widget(
2712                Material::new()
2713                    .child(Builder::new(|app, context| {
2714                        PlainLayoutChangedNotification.dispatch(app, Some(context));
2715                        SizedBox::shrink().into_widget()
2716                    }))
2717                    .into_widget(),
2718            );
2719        });
2720    }
2721
2722    #[test]
2723    fn lookup_boundary_hides_material_from_material_maybe_of() {
2724        test_widgets(|tester| {
2725            let material: Rc<Cell<Option<Option<AnyMaterialInkController>>>> = Rc::default();
2726            tester.pump_widget(
2727                Material::new()
2728                    .child(LookupBoundary::new(Builder::new({
2729                        let material = Rc::clone(&material);
2730                        move |app, context| {
2731                            material.set(Some(Material::maybe_of(app, context)));
2732                            SizedBox::shrink().into_widget()
2733                        }
2734                    })))
2735                    .into_widget(),
2736            );
2737            assert_eq!(material.get(), Some(None));
2738        });
2739    }
2740
2741    #[test]
2742    fn lookup_boundary_hides_material_from_material_of() {
2743        test_widgets(|tester| {
2744            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2745                tester.pump_widget(
2746                    Material::new()
2747                        .child(LookupBoundary::new(Builder::new(|app, context| {
2748                            Material::of(app, context);
2749                            SizedBox::shrink().into_widget()
2750                        })))
2751                        .into_widget(),
2752                );
2753            }));
2754            let panic = outcome.expect_err("the boundary hides the Material");
2755            let message = panic.downcast_ref::<String>().cloned().unwrap_or_default();
2756            assert!(
2757                message.starts_with(
2758                    "Material.of() was called with a context that does not have access to a \
2759                 Material widget.\nThe context provided to Material.of() does have a \
2760                 Material widget ancestor, but it is hidden by a LookupBoundary. This can \
2761                 happen because you are using a widget that looks for a Material ancestor, \
2762                 but no such ancestor exists within the closest LookupBoundary.\nThe \
2763                 context used was:\n  "
2764                ),
2765                "{message}"
2766            );
2767        });
2768    }
2769
2770    /// Dart's `PaintRecorder`: logs the size of every paint.
2771    struct PaintRecorder {
2772        log: Rc<RefCell<Vec<Size>>>,
2773    }
2774
2775    impl CustomPainter for PaintRecorder {
2776        fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
2777            self.log.borrow_mut().push(size);
2778            canvas.draw_rect(Offset::ZERO & size, &Paint::from_color(BLUE.into()));
2779        }
2780
2781        fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
2782            false
2783        }
2784
2785        fn as_any(&self) -> &dyn Any {
2786            self
2787        }
2788    }
2789
2790    /// Dart's tree for "ListView scroll does not repaint": a recorder above a `Material` that
2791    /// holds a 2000-pixel list and a second recorder; `list_child` keys the list's child.
2792    fn scrolled_material(log: &Rc<RefCell<Vec<Size>>>, list_child: &GlobalKey) -> WidgetRef {
2793        let recorder = |dimension: f64| {
2794            SizedBox::square(Some(dimension))
2795                .child(CustomPaint::new().painter(PaintRecorder {
2796                    log: Rc::clone(log),
2797                }))
2798                .into_widget()
2799        };
2800        Directionality::new(
2801            TextDirection::Ltr,
2802            Column::new().children([
2803                SizedBox::new()
2804                    .width(150.0)
2805                    .height(150.0)
2806                    .child(CustomPaint::new().painter(PaintRecorder {
2807                        log: Rc::clone(log),
2808                    }))
2809                    .into_widget(),
2810                Expanded::new(
2811                    Material::new().child(
2812                        Column::new().children([
2813                            Expanded::new(
2814                                ListView::new().children([Container::new()
2815                                    .key(list_child.clone().into())
2816                                    .height(2000.0)
2817                                    .color(Color::new(0xFF00FF00))
2818                                    .into_widget()]),
2819                            )
2820                            .into_widget(),
2821                            recorder(100.0),
2822                        ]),
2823                    ),
2824                )
2825                .into_widget(),
2826            ]),
2827        )
2828        .into_widget()
2829    }
2830
2831    /// Dart's `tester.drag(find.byType(ListView), offset)`: a touch down on the list, a move by
2832    /// `offset` and an up.
2833    fn drag_list(tester: &mut WidgetTester, list_child: &GlobalKey, offset: Offset) {
2834        let start = tester.center_of(list_child);
2835        let start = Offset::new(start.dx(), 300.0);
2836        let mut pointer = TestPointer::touch(1);
2837        tester.down(&mut pointer, start);
2838        tester.move_to(&mut pointer, start + offset, true);
2839        tester.up(&pointer);
2840    }
2841
2842    #[test]
2843    fn list_view_scroll_does_not_repaint() {
2844        test_widgets(|tester| {
2845            let log: Rc<RefCell<Vec<Size>>> = Rc::default();
2846            let list_child = GlobalKey::new();
2847            tester.pump_widget(scrolled_material(&log, &list_child));
2848
2849            // We paint twice because we have two CustomPaint widgets in the tree above
2850            // to test repainting both inside and outside the Material widget.
2851            assert_eq!(
2852                *log.borrow(),
2853                [Size::new(150.0, 150.0), Size::new(100.0, 100.0)]
2854            );
2855            log.borrow_mut().clear();
2856
2857            drag_list(tester, &list_child, Offset::new(0.0, -300.0));
2858            tester.pump();
2859
2860            assert!(log.borrow().is_empty(), "{:?}", log.borrow());
2861        });
2862    }
2863
2864    // The ink half of "ListView scroll does not repaint": a scroll notification is a
2865    // `LayoutChangedNotification`, so a Material that holds ink repaints when its list scrolls.
2866    #[test]
2867    fn list_view_scroll_repaints_the_ink_of_its_material() {
2868        test_widgets(|tester| {
2869            let log: Rc<RefCell<Vec<Size>>> = Rc::default();
2870            let list_child = GlobalKey::new();
2871            tester.pump_widget(scrolled_material(&log, &list_child));
2872            let paint_count = Rc::new(Cell::new(0));
2873            {
2874                let mut app = tester.cell.borrow_mut();
2875                let context = list_child.current_context(&app).expect("mounted");
2876                let controller = Material::of(&app, context);
2877                let reference_box = context
2878                    .find_render_object(&app)
2879                    .and_then(|render_object| render_object.as_box())
2880                    .expect("a box");
2881                let ink_feature = InkFeatureData::new(&app, controller, reference_box, None);
2882                let tracker = app.create(TrackPaintInkFeature {
2883                    ink_feature,
2884                    paint_count: Rc::clone(&paint_count),
2885                });
2886                controller.add_ink_feature(&mut app, tracker.erase());
2887            }
2888            tester.pump();
2889            assert_eq!(paint_count.get(), 1);
2890
2891            drag_list(tester, &list_child, Offset::new(0.0, -300.0));
2892            tester.pump();
2893
2894            assert_eq!(paint_count.get(), 2, "the ink repaints with the scroll");
2895        });
2896    }
2897
2898    #[test]
2899    fn transparent_material_widget_does_not_absorb_hit_test() {
2900        // This is a regression test for https://github.com/flutter/flutter/issues/58665.
2901        test_widgets(|tester| {
2902            let pressed = Rc::new(Cell::new(false));
2903            let button = GlobalKey::new();
2904            let widget = Directionality::new(
2905                TextDirection::Ltr,
2906                Stack::new().children([
2907                    Material::new()
2908                        .child(
2909                            InkWell::new()
2910                                .key(button.clone().into())
2911                                .on_tap(Listener::new({
2912                                    let pressed = Rc::clone(&pressed);
2913                                    move |_app| pressed.set(true)
2914                                }))
2915                                .child(SizedBox::new().width(88.0).height(36.0)),
2916                        )
2917                        .into_widget(),
2918                    Material::new()
2919                        .r#type(MaterialType::Transparency)
2920                        .child(SizedBox::new().width(400.0).height(500.0))
2921                        .into_widget(),
2922                ]),
2923            )
2924            .into_widget();
2925            tester.pump_widget(widget);
2926            let center = tester.get_center(&button);
2927            tester.tap_at(center, 1);
2928            assert!(pressed.get());
2929        });
2930    }
2931
2932    #[test]
2933    fn overlay_will_not_apply_to_materials_using_a_non_surface_color() {
2934        test_widgets(|tester| {
2935            let widget = themed(
2936                tester,
2937                |app| {
2938                    ThemeData::builder()
2939                        .use_material3(false)
2940                        .apply_elevation_overlay_color(true)
2941                        .color_scheme(ColorScheme::dark())
2942                        .build(app)
2943                },
2944                centered(build_material(8.0, GREEN, None, Colors::CYAN.primary())),
2945            );
2946            tester.pump_widget(widget);
2947            // Shouldn't change, as it is not using a ColorScheme.surface color
2948            assert_eq!(
2949                model(tester).color(&tester.cell.borrow()),
2950                Colors::CYAN.primary()
2951            );
2952        });
2953    }
2954
2955    #[test]
2956    fn overlay_will_not_apply_to_materials_using_a_light_theme() {
2957        test_widgets(|tester| {
2958            let widget = themed(
2959                tester,
2960                |app| {
2961                    ThemeData::builder()
2962                        .use_material3(false)
2963                        .apply_elevation_overlay_color(true)
2964                        .color_scheme(ColorScheme::light())
2965                        .build(app)
2966                },
2967                centered(build_material(8.0, GREEN, None, Colors::CYAN.primary())),
2968            );
2969            tester.pump_widget(widget);
2970            // Shouldn't change, as it was under a light color scheme.
2971            assert_eq!(
2972                model(tester).color(&tester.cell.borrow()),
2973                Colors::CYAN.primary()
2974            );
2975        });
2976    }
2977
2978    #[test]
2979    #[allow(deprecated)]
2980    fn overlay_will_apply_to_materials_with_a_non_opaque_surface_color() {
2981        test_widgets(|tester| {
2982            let surface_color = Color::new(0xFF121212);
2983            let surface_color_with_overlay = Color::new(0xC6353535);
2984            let widget = themed(
2985                tester,
2986                |app| {
2987                    ThemeData::builder()
2988                        .use_material3(false)
2989                        .apply_elevation_overlay_color(true)
2990                        .color_scheme(ColorScheme::dark())
2991                        .build(app)
2992                },
2993                centered(build_material(
2994                    8.0,
2995                    GREEN,
2996                    None,
2997                    surface_color.with_opacity(0.75),
2998                )),
2999            );
3000            tester.pump_widget(widget);
3001            let color = model(tester).color(&tester.cell.borrow());
3002            assert!(
3003                is_same_color_as(color, surface_color_with_overlay),
3004                "{color:?}"
3005            );
3006            assert!(!is_same_color_as(color, surface_color), "{color:?}");
3007        });
3008    }
3009
3010    #[test]
3011    fn expected_overlay_color_can_be_computed_using_color_with_overlay() {
3012        test_widgets(|tester| {
3013            let surface_color = Color::new(0xFF123456);
3014            let on_surface_color = Color::new(0xFF654321);
3015            let elevation = 8.0;
3016
3017            let surface_color_with_overlay =
3018                ElevationOverlay::color_with_overlay(surface_color, on_surface_color, elevation);
3019
3020            let widget = themed(
3021                tester,
3022                |app| {
3023                    ThemeData::builder()
3024                        .use_material3(false)
3025                        .apply_elevation_overlay_color(true)
3026                        .color_scheme(
3027                            ColorScheme::dark()
3028                                .with_surface(surface_color)
3029                                .with_on_surface(on_surface_color),
3030                        )
3031                        .build(app)
3032                },
3033                centered(build_material(elevation, GREEN, None, surface_color)),
3034            );
3035            tester.pump_widget(widget);
3036            let color = model(tester).color(&tester.cell.borrow());
3037            assert_eq!(color, surface_color_with_overlay);
3038            assert_ne!(color, surface_color);
3039        });
3040    }
3041
3042    #[test]
3043    fn material_is_not_visible_from_sub_views() {
3044        test_widgets(|_| {
3045            let fake_view: ViewRef =
3046                Rc::new(TestView::with_pixel_ratio(1600.0, 1200.0, 2.0).with_id(ViewId(100)));
3047            let platform = TestPlatform::new()
3048                .on(TargetPlatform::Android)
3049                .with_view(test_view())
3050                .with_view(Rc::clone(&fake_view));
3051            let cell = AppCell::with_platform(Rc::new(platform));
3052            type Seen = Rc<Cell<Option<Option<AnyMaterialInkController>>>>;
3053            let outside_view: Seen = Rc::default();
3054            let inside_view: Seen = Rc::default();
3055            let outside_view_anchor: Seen = Rc::default();
3056            let seeing = |seen: &Seen, child: WidgetRef| {
3057                let seen = Rc::clone(seen);
3058                Builder::new(move |app, context| {
3059                    seen.set(Some(Material::maybe_of(app, context)));
3060                    child.clone()
3061                })
3062                .into_widget()
3063            };
3064            let tree = Material::new()
3065                .child(seeing(
3066                    &outside_view_anchor,
3067                    ViewAnchor::new(SizedBox::new())
3068                        .view(seeing(
3069                            &outside_view,
3070                            View::new(
3071                                fake_view,
3072                                seeing(&inside_view, SizedBox::new().into_widget()),
3073                            )
3074                            .into_widget(),
3075                        ))
3076                        .into_widget(),
3077                ))
3078                .into_widget();
3079            build(&cell, tree);
3080
3081            assert!(matches!(outside_view_anchor.get(), Some(Some(_))));
3082            assert_eq!(outside_view.get(), Some(None));
3083            assert_eq!(inside_view.get(), Some(None));
3084        });
3085    }
3086
3087    #[test]
3088    fn a_surface_tint_tween_is_freed_when_the_tint_goes_away() {
3089        test_widgets(|tester| {
3090            let tinted = |surface_tint_color: Option<Color>| {
3091                centered(
3092                    build_material(4.0, GREEN, surface_tint_color, BLUE).r#type(MaterialType::Card),
3093                )
3094            };
3095            tester.pump_widget(tinted(Some(Color::new(0xFF44CCFF))));
3096            let elements = tester.elements();
3097            let app = tester.cell.borrow();
3098            let state = elements
3099                .into_iter()
3100                .find_map(|element| element.state_handle::<MaterialInteriorState>(&app))
3101                .expect("a material interior");
3102            let tween = app
3103                .get(state)
3104                .surface_tint_color
3105                .as_ref()
3106                .expect("a tint tween")
3107                .handle();
3108            drop(app);
3109            tester.pump_widget(tinted(None));
3110            assert!(tester.cell.borrow().get(state).surface_tint_color.is_none());
3111            assert!(!tester.cell.borrow().contains(tween));
3112        });
3113    }
3114
3115    /// `material_test.dart`, "default Material debugFillProperties".
3116    #[test]
3117    fn a_default_material_describes_its_type() {
3118        use waft_foundation::DiagnosticPropertiesBuilder;
3119
3120        let material = Material::new();
3121        let cell = waft_foundation::AppCell::new();
3122        let app = cell.borrow();
3123        let description: Vec<String> = waft_widgets::testing::describe_properties(
3124            |properties: &mut DiagnosticPropertiesBuilder| {
3125                material.debug_fill_properties(&app, properties)
3126            },
3127        );
3128        assert_eq!(description, ["type: canvas"]);
3129    }
3130
3131    /// `material_test.dart`, "Material implements debugFillProperties".
3132    #[test]
3133    fn a_material_describes_its_other_properties() {
3134        use waft_embedder::Color;
3135        use waft_foundation::DiagnosticPropertiesBuilder;
3136        use waft_painting::BorderRadiusDirectional;
3137
3138        let white = Color::new(0xFFFFFFFF);
3139        let red = Color::new(0xFFFF0000);
3140        let blue = Color::new(0xFF0000FF);
3141        let green = Color::new(0xFF00FF00);
3142        let material = Material::new()
3143            .color(white)
3144            .shadow_color(red)
3145            .surface_tint_color(blue)
3146            .text_style(TextStyle::new().color(green))
3147            .border_radius(BorderRadiusDirectional::all(Radius::circular(10.0)));
3148        let cell = waft_foundation::AppCell::new();
3149        let app = cell.borrow();
3150        let description: Vec<String> = waft_widgets::testing::describe_properties(
3151            |properties: &mut DiagnosticPropertiesBuilder| {
3152                material.debug_fill_properties(&app, properties)
3153            },
3154        );
3155        assert_eq!(
3156            description,
3157            [
3158                "type: canvas".to_string(),
3159                format!("color: {white}"),
3160                format!("shadowColor: {red}"),
3161                format!("surfaceTintColor: {blue}"),
3162                "textStyle.inherit: true".to_string(),
3163                format!("textStyle.color: {green}"),
3164                "borderRadius: BorderRadiusDirectional.circular(10.0)".to_string(),
3165            ]
3166        );
3167    }
3168
3169    #[test]
3170    fn material_does_not_crash_at_zero_area() {
3171        test_widgets(|tester| {
3172            let key = GlobalKey::new();
3173            tester.pump_widget(
3174                Center::new()
3175                    .child(SizedBox::new().child(Material::new().key(key.clone().into())))
3176                    .into_widget(),
3177            );
3178            let size = tester
3179                .render_object(&key)
3180                .as_box()
3181                .expect("a box")
3182                .size(&tester.cell.borrow());
3183            assert_eq!(size, Size::ZERO);
3184        });
3185    }
3186}