Skip to main content

waft_widgets/widgets/
widget_span.rs

1//! Flutter counterpart: `widgets/widget_span.dart`.
2//!
3//! The `Semantics` wrapper that tags each inline widget with its placeholder index waits with
4//! the rest of semantics.
5
6use std::any::Any;
7use std::fmt;
8use std::rc::Rc;
9
10use waft_embedder::{
11    Matrix4, Offset, ParagraphBuilder, PlaceholderAlignment, Size, TextBaseline, TextPosition,
12};
13use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty};
14use waft_painting::{
15    Accumulator, InlineSpan, InlineSpanRef, K_DEFAULT_FONT_SIZE, PLACEHOLDER_CODE_UNIT,
16    PlaceholderDimensions, PlaceholderSpan, RenderComparison, TextScaler, TextStyle,
17    inline_span_debug_fill_properties, placeholder_span_debug_fill_properties, same_span,
18};
19use waft_rendering::{
20    AnyRenderBox, AnyRenderObject, BoxConstraints, BoxHitTestResult, ContainerLayer,
21    PaintingContext, RenderBox, RenderBoxData, RenderHandle, RenderObject, RenderObjectData,
22    RenderObjectWithChildData, RenderObjectWithChildMixin, TextParentData, TransformLayer,
23};
24
25use crate::framework::{
26    BuildContext, IntoWidget, KeyRef, ParentDataWidget, RenderObjectWidget,
27    SingleChildRenderObjectWidget, WidgetRef,
28};
29
30/// An immutable widget that is embedded inline within text.
31///
32/// The [`child`](Self::child) property is the widget that will be embedded. Children are
33/// constrained by the width of the paragraph.
34///
35/// The [`child`](Self::child) property may contain its own `Widget` children (if applicable),
36/// including `Text` and `RichText` widgets which may include additional [`WidgetSpan`]s.
37/// Child `Text` and `RichText` widgets will be laid out independently and occupy a rectangular
38/// space in the parent text layout.
39///
40/// [`WidgetSpan`]s will be ignored when passed into a [`TextPainter`](waft_painting::TextPainter)
41/// directly. To properly layout and paint the [`WidgetSpan`], [`WidgetSpan`] should be passed
42/// into a `Text::rich` widget.
43///
44/// ```text
45/// Text::rich(
46///     TextSpan::new()
47///         .children(vec![
48///             TextSpan::new().text("Flutter is").into_span(),
49///             WidgetSpan::new(SizedBox::new().width(120.0).height(50.0).child(Card::new(...)))
50///                 .into_span(),
51///             TextSpan::new().text("the best!").into_span(),
52///         ])
53///         .into_span(),
54/// )
55/// ```
56///
57/// [`WidgetSpan`] contributes the semantics of the [`WidgetSpan::child`] to the semantics
58/// tree.
59///
60/// See also:
61///
62///  * `TextSpan`, a node that represents text in an [`InlineSpan`] tree.
63///  * `Text`, a widget for showing uniformly-styled text.
64///  * `RichText`, a widget for finer control of text rendering.
65///  * [`TextPainter`](waft_painting::TextPainter), a class for painting [`InlineSpan`]
66///    objects on a `Canvas`.
67///
68/// Dart's named constructor arguments are the fluent setters; the constructor's assert runs
69/// in [`into_span`](Self::into_span), once every setter has had its say.
70#[derive(Clone)]
71pub struct WidgetSpan {
72    /// The widget to embed inline within text.
73    pub child: WidgetRef,
74    /// How the placeholder aligns vertically with the text.
75    pub alignment: PlaceholderAlignment,
76    /// The [`TextBaseline`] to align against when using [`PlaceholderAlignment::Baseline`],
77    /// [`PlaceholderAlignment::AboveBaseline`], and [`PlaceholderAlignment::BelowBaseline`].
78    pub baseline: Option<TextBaseline>,
79    /// The [`TextStyle`] to apply to this span; only the decoration, foreground, background,
80    /// and spacing options are used.
81    pub style: Option<TextStyle>,
82}
83
84impl WidgetSpan {
85    /// Creates a [`WidgetSpan`] with the given values.
86    ///
87    /// The [`child`](Self::child) property is the widget that will be embedded. Children are
88    /// constrained by the width of the paragraph.
89    ///
90    /// The [`child`](Self::child) property may contain its own `Widget` children (if
91    /// applicable), including `Text` and `RichText` widgets which may include additional
92    /// [`WidgetSpan`]s. Child `Text` and `RichText` widgets will be laid out independently and
93    /// occupy a rectangular space in the parent text layout.
94    ///
95    /// A [`TextStyle`] may be provided with the [`style`](Self::style) property, but only the
96    /// decoration, foreground, background, and spacing options will be used.
97    #[cfg_attr(debug_assertions, track_caller)]
98    pub fn new<K>(child: impl IntoWidget<K>) -> WidgetSpan {
99        WidgetSpan {
100            child: child.into_widget(),
101            alignment: PlaceholderAlignment::Bottom,
102            baseline: None,
103            style: None,
104        }
105    }
106
107    /// Dart `WidgetSpan(alignment:)`.
108    pub fn alignment(mut self, alignment: PlaceholderAlignment) -> WidgetSpan {
109        self.alignment = alignment;
110        self
111    }
112
113    /// Dart `WidgetSpan(baseline:)`.
114    pub fn baseline(mut self, baseline: TextBaseline) -> WidgetSpan {
115        self.baseline = Some(baseline);
116        self
117    }
118
119    /// Dart `WidgetSpan(style:)`.
120    pub fn style(mut self, style: TextStyle) -> WidgetSpan {
121        self.style = Some(style);
122        self
123    }
124
125    /// The span as a shared [`InlineSpanRef`].
126    ///
127    /// A baseline alignment needs a [`baseline`](Self::baseline).
128    pub fn into_span(self) -> InlineSpanRef {
129        debug_assert!(
130            self.baseline.is_some()
131                || !matches!(
132                    self.alignment,
133                    PlaceholderAlignment::AboveBaseline
134                        | PlaceholderAlignment::BelowBaseline
135                        | PlaceholderAlignment::Baseline
136                )
137        );
138        std::rc::Rc::new(self)
139    }
140
141    /// Helper function for extracting [`WidgetSpan`]s in preorder, from the given
142    /// [`InlineSpan`] as a list of widgets.
143    ///
144    /// The `text_scaler` is the scaling strategy for scaling the content.
145    ///
146    /// This function is used by `EditableText` and `RichText` so calling it directly is rarely
147    /// necessary.
148    pub fn extract_from_inline_span(
149        span: &dyn InlineSpan,
150        text_scaler: &TextScaler,
151    ) -> Vec<WidgetRef> {
152        let mut widgets = Vec::new();
153        // _kEngineDefaultFontSize is the default font size to use when none of the
154        // ancestor spans specifies one.
155        let mut font_size_stack = vec![K_DEFAULT_FONT_SIZE];
156        visit_subtree(span, text_scaler, &mut font_size_stack, &mut widgets);
157        widgets
158    }
159}
160
161/// `extract_from_inline_span`'s `visitSubtree`. This assumes an [`InlineSpan`] tree's logical
162/// order is equivalent to preorder.
163fn visit_subtree(
164    span: &dyn InlineSpan,
165    text_scaler: &TextScaler,
166    font_size_stack: &mut Vec<f64>,
167    widgets: &mut Vec<WidgetRef>,
168) -> bool {
169    let font_size_to_push = span
170        .style()
171        .and_then(|style| style.font_size)
172        .filter(|size| Some(size) != font_size_stack.last());
173    if let Some(size) = font_size_to_push {
174        font_size_stack.push(size);
175    }
176    if let Some(widget_span) = span.as_any().downcast_ref::<WidgetSpan>() {
177        let font_size = *font_size_stack.last().expect("never empty");
178        let text_scale_factor = if font_size == 0.0 {
179            0.0
180        } else {
181            text_scaler.scale(font_size) / font_size
182        };
183        widgets.push(
184            WidgetSpanParentData {
185                span: widget_span.clone(),
186                child: AutoScaleInlineWidget {
187                    span: widget_span.clone(),
188                    text_scale_factor,
189                    child: widget_span.child.clone(),
190                }
191                .into_widget(),
192            }
193            .into_widget(),
194        );
195    }
196    debug_assert!(
197        span.as_any().is::<WidgetSpan>() || span.as_placeholder_span().is_none(),
198        "{span:?} is a PlaceholderSpan but not a WidgetSpan subclass. This is currently not \
199         supported."
200    );
201    span.visit_direct_children(&mut |child| {
202        visit_subtree(&**child, text_scaler, font_size_stack, widgets)
203    });
204    if let Some(pushed) = font_size_to_push {
205        let popped_font_size = font_size_stack.pop();
206        debug_assert!(!font_size_stack.is_empty());
207        debug_assert_eq!(popped_font_size, Some(pushed));
208    }
209    true
210}
211
212impl fmt::Debug for WidgetSpan {
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        let mut s = f.debug_struct("WidgetSpan");
215        if let Some(style) = &self.style {
216            s.field("style", style);
217        }
218        s.field("alignment", &self.alignment)
219            .field("baseline", &self.baseline)
220            .field("widget", &self.child)
221            .finish()
222    }
223}
224
225impl PlaceholderSpan for WidgetSpan {
226    fn alignment(&self) -> PlaceholderAlignment {
227        self.alignment
228    }
229
230    fn baseline(&self) -> Option<TextBaseline> {
231        self.baseline
232    }
233}
234
235impl InlineSpan for WidgetSpan {
236    fn to_string_short(&self) -> String {
237        waft_foundation::describe_identity("WidgetSpan", self as *const WidgetSpan as usize as u64)
238    }
239
240    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
241        inline_span_debug_fill_properties(self.style(), properties);
242        placeholder_span_debug_fill_properties(self, properties);
243        properties.add(DiagnosticsProperty::<String>::new(
244            "widget",
245            Some("Instance of 'Widget'".to_string()),
246        ));
247    }
248
249    fn style(&self) -> Option<&TextStyle> {
250        self.style.as_ref()
251    }
252
253    /// Adds a placeholder box to the paragraph builder if a size has been calculated for the
254    /// widget.
255    ///
256    /// Sizes are provided through `dimensions`, which should contain a 1:1 in-order mapping
257    /// of widget to laid-out dimensions. If no such dimension is provided, the widget will be
258    /// skipped.
259    ///
260    /// The `text_scaler` will be applied to the laid-out size of the widget.
261    fn build(
262        &self,
263        builder: &mut ParagraphBuilder,
264        text_scaler: &TextScaler,
265        dimensions: Option<&[PlaceholderDimensions]>,
266    ) {
267        debug_assert!(InlineSpan::debug_assert_is_valid(self));
268        let dimensions = dimensions.expect("a WidgetSpan is built with its dimensions");
269        let has_style = self.style.is_some();
270        if let Some(style) = &self.style {
271            builder.push_style(style.get_text_style_with(text_scaler));
272        }
273        debug_assert!((builder.placeholder_count() as usize) < dimensions.len());
274        let current_dimensions = dimensions[builder.placeholder_count() as usize];
275        builder.add_placeholder(
276            current_dimensions.size.width(),
277            current_dimensions.size.height(),
278            self.alignment,
279            1.0,
280            current_dimensions.baseline_offset,
281            current_dimensions.baseline,
282        );
283        if has_style {
284            builder.pop();
285        }
286    }
287
288    /// Calls `visitor` on this [`WidgetSpan`]. There are no children spans to walk.
289    fn visit_children(self: Rc<Self>, visitor: &mut dyn FnMut(&InlineSpanRef) -> bool) -> bool {
290        visitor(&(self as InlineSpanRef))
291    }
292
293    fn visit_direct_children(&self, _visitor: &mut dyn FnMut(&InlineSpanRef) -> bool) -> bool {
294        true
295    }
296
297    /// [`WidgetSpan`]s are not hit-test targets: this always returns `None`.
298    fn get_span_for_position(self: Rc<Self>, _position: TextPosition) -> Option<InlineSpanRef> {
299        debug_assert!(InlineSpan::debug_assert_is_valid(&*self));
300        None
301    }
302
303    fn get_span_for_position_visitor(
304        self: Rc<Self>,
305        position: TextPosition,
306        offset: &mut Accumulator,
307    ) -> Option<InlineSpanRef> {
308        if position.offset == offset.value() {
309            return Some(self);
310        }
311        offset.increment(1);
312        None
313    }
314
315    fn compute_to_plain_text(
316        &self,
317        buffer: &mut String,
318        include_semantics_labels: bool,
319        include_placeholders: bool,
320    ) {
321        PlaceholderSpan::compute_to_plain_text(
322            self,
323            buffer,
324            include_semantics_labels,
325            include_placeholders,
326        );
327    }
328
329    fn code_unit_at_visitor(&self, index: i32, offset: &mut Accumulator) -> Option<u16> {
330        let local_offset = index - offset.value();
331        debug_assert!(local_offset >= 0);
332        offset.increment(1);
333        (local_offset == 0).then_some(PLACEHOLDER_CODE_UNIT)
334    }
335
336    /// [`WidgetSpan`]s are always valid as asserts prevent invalid [`WidgetSpan`]s from being
337    /// constructed.
338    fn debug_assert_is_valid(&self) -> bool {
339        true
340    }
341
342    fn compare_to(&self, other: &dyn InlineSpan) -> RenderComparison {
343        if same_span(self, other) {
344            return RenderComparison::Identical;
345        }
346        let Some(typed_other) = other.as_any().downcast_ref::<WidgetSpan>() else {
347            return RenderComparison::Layout;
348        };
349        if self.style.is_none() != typed_other.style.is_none() {
350            return RenderComparison::Layout;
351        }
352        if !std::rc::Rc::ptr_eq(&self.child, &typed_other.child)
353            || self.alignment != typed_other.alignment
354        {
355            return RenderComparison::Layout;
356        }
357        let mut result = RenderComparison::Identical;
358        if let (Some(style), Some(other_style)) = (&self.style, &typed_other.style) {
359            let candidate = style.compare_to(other_style);
360            if candidate > result {
361                result = candidate;
362            }
363            if result == RenderComparison::Layout {
364                return result;
365            }
366        }
367        result
368    }
369
370    fn as_any(&self) -> &dyn Any {
371        self
372    }
373
374    fn as_placeholder_span(&self) -> Option<&dyn PlaceholderSpan> {
375        Some(self)
376    }
377
378    fn eq_span(&self, other: &dyn InlineSpan) -> bool {
379        if same_span(self, other) {
380            return true;
381        }
382        let Some(other) = other.as_any().downcast_ref::<WidgetSpan>() else {
383            return false;
384        };
385        other.style == self.style
386            && std::rc::Rc::ptr_eq(&other.child, &self.child)
387            && other.alignment == self.alignment
388            && other.baseline == self.baseline
389    }
390}
391
392/// A `ParentDataWidget` that sets [`TextParentData::span`].
393#[derive(Debug)]
394struct WidgetSpanParentData {
395    span: WidgetSpan,
396    child: WidgetRef,
397}
398
399impl ParentDataWidget for WidgetSpanParentData {
400    type ParentData = TextParentData;
401
402    fn child(&self) -> &WidgetRef {
403        &self.child
404    }
405
406    fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject) {
407        let parent_data = render_object.parent_data_of_mut::<TextParentData>(app);
408        parent_data.span = Some(std::rc::Rc::new(self.span.clone()));
409    }
410}
411
412// A RenderObjectWidget that automatically applies text scaling on inline
413// widgets.
414//
415// TODO(LongCatIsLooong): this shouldn't happen automatically, at least there
416// should be a way to opt out: https://github.com/flutter/flutter/issues/126962
417#[derive(Debug)]
418struct AutoScaleInlineWidget {
419    span: WidgetSpan,
420    text_scale_factor: f64,
421    child: WidgetRef,
422}
423
424impl RenderObjectWidget for AutoScaleInlineWidget {
425    type RenderObject = RenderScaledInlineWidget;
426
427    fn key(&self) -> Option<&KeyRef> {
428        None
429    }
430
431    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
432        RenderScaledInlineWidget::new(
433            app,
434            self.span.alignment,
435            self.span.baseline,
436            self.text_scale_factor,
437        )
438        .as_object()
439    }
440
441    fn update_render_object(
442        &self,
443        app: &mut App,
444        _context: BuildContext,
445        render_object: RenderHandle<RenderScaledInlineWidget>,
446    ) {
447        render_object.set_alignment(app, self.span.alignment);
448        render_object.set_baseline(app, self.span.baseline);
449        render_object.set_scale(app, self.text_scale_factor);
450    }
451}
452
453impl SingleChildRenderObjectWidget for AutoScaleInlineWidget {
454    fn child(&self) -> Option<&WidgetRef> {
455        Some(&self.child)
456    }
457}
458
459/// The render box of an inline widget: its child laid out at the paragraph's width and
460/// scaled by the text scale factor.
461struct RenderScaledInlineWidget {
462    render_object: RenderObjectData,
463    render_box: RenderBoxData,
464    child: RenderObjectWithChildData<AnyRenderBox>,
465    scale: f64,
466    alignment: PlaceholderAlignment,
467    baseline: Option<TextBaseline>,
468}
469
470impl RenderScaledInlineWidget {
471    fn new(
472        app: &mut App,
473        alignment: PlaceholderAlignment,
474        baseline: Option<TextBaseline>,
475        scale: f64,
476    ) -> RenderHandle<Self> {
477        RenderHandle::new_box(
478            app,
479            RenderScaledInlineWidget {
480                render_object: RenderObjectData::new(),
481                render_box: RenderBoxData::new(),
482                child: RenderObjectWithChildData::new(),
483                scale,
484                alignment,
485                baseline,
486            },
487        )
488    }
489
490    fn scale(self: RenderHandle<Self>, app: &App) -> f64 {
491        self.get(app).scale
492    }
493
494    fn set_scale(self: RenderHandle<Self>, app: &mut App, value: f64) {
495        if value == self.get(app).scale {
496            return;
497        }
498        debug_assert!(value > 0.0);
499        debug_assert!(value.is_finite());
500        self.get_mut(app).scale = value;
501        self.as_object().mark_needs_layout(app);
502    }
503
504    fn set_alignment(self: RenderHandle<Self>, app: &mut App, value: PlaceholderAlignment) {
505        if self.get(app).alignment == value {
506            return;
507        }
508        self.get_mut(app).alignment = value;
509        self.as_object().mark_needs_layout(app);
510    }
511
512    fn set_baseline(self: RenderHandle<Self>, app: &mut App, value: Option<TextBaseline>) {
513        if value == self.get(app).baseline {
514            return;
515        }
516        self.get_mut(app).baseline = value;
517        self.as_object().mark_needs_layout(app);
518    }
519
520    /// `Matrix4.diagonal3Values(scale, scale, 1.0)`.
521    fn scale_matrix(self: RenderHandle<Self>, app: &App) -> Matrix4 {
522        let scale = self.scale(app) as f32;
523        Matrix4::scale(scale, scale)
524    }
525}
526
527impl RenderObjectWithChildMixin for RenderScaledInlineWidget {
528    type ChildType = AnyRenderBox;
529
530    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
531        &self.get(app).child
532    }
533
534    fn child_data_mut(
535        self: RenderHandle<Self>,
536        app: &mut App,
537    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
538        &mut self.get_mut(app).child
539    }
540}
541
542impl RenderObject for RenderScaledInlineWidget {
543    waft_rendering::render_object_accessors!();
544
545    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
546        let Some(child) = self.child(app) else {
547            return;
548        };
549        let constraints = self.constraints(app);
550        debug_assert!(!constraints.has_bounded_height());
551        let scale = self.scale(app);
552        // Only constrain the width to the maximum width of the paragraph.
553        // Leave height unconstrained, which will overflow if expanded past.
554        child.layout(
555            app,
556            BoxConstraints::new().max_width(constraints.max_width / scale),
557            true,
558        );
559        let size = constraints.constrain(child.size(app) * scale);
560        self.set_size(app, size);
561    }
562
563    fn paint(
564        self: RenderHandle<Self>,
565        app: &mut App,
566        context: &mut PaintingContext,
567        offset: Offset,
568    ) {
569        let Some(child) = self.child(app) else {
570            self.as_object().set_layer(app, None);
571            return;
572        };
573        if self.scale(app) == 1.0 {
574            context.paint_child(app, child.as_object(), offset);
575            self.as_object().set_layer(app, None);
576            return;
577        }
578        let old_layer = self.as_object().layer_as::<TransformLayer>(app);
579        let layer = context.push_transform(
580            app,
581            self.as_object().needs_compositing(app),
582            offset,
583            self.scale_matrix(app),
584            |app, context, offset| context.paint_child(app, child.as_object(), offset),
585            old_layer,
586        );
587        self.as_object()
588            .set_layer(app, layer.map(|layer| layer.as_container_layer()));
589    }
590
591    fn visit_children(
592        self: RenderHandle<Self>,
593        app: &App,
594        visitor: &mut dyn FnMut(AnyRenderObject),
595    ) {
596        if let Some(child) = self.child(app) {
597            visitor(child.as_object());
598        }
599    }
600}
601
602impl RenderBox for RenderScaledInlineWidget {
603    waft_rendering::render_box_accessors!();
604
605    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
606        let scale = self.scale(app);
607        self.child(app).map_or(0.0, |child| {
608            child.get_max_intrinsic_height(app, width / scale)
609        }) * scale
610    }
611
612    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
613        let scale = self.scale(app);
614        self.child(app).map_or(0.0, |child| {
615            child.get_max_intrinsic_width(app, height / scale)
616        }) * scale
617    }
618
619    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
620        let scale = self.scale(app);
621        self.child(app).map_or(0.0, |child| {
622            child.get_min_intrinsic_height(app, width / scale)
623        }) * scale
624    }
625
626    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
627        let scale = self.scale(app);
628        self.child(app).map_or(0.0, |child| {
629            child.get_min_intrinsic_width(app, height / scale)
630        }) * scale
631    }
632
633    fn compute_distance_to_actual_baseline(
634        self: RenderHandle<Self>,
635        app: &mut App,
636        baseline: TextBaseline,
637    ) -> Option<f64> {
638        let scale = self.scale(app);
639        self.child(app)
640            .and_then(|child| child.get_distance_to_actual_baseline(app, baseline))
641            .map(|child_baseline| scale * child_baseline)
642    }
643
644    fn compute_dry_baseline(
645        self: RenderHandle<Self>,
646        app: &mut App,
647        constraints: BoxConstraints,
648        baseline: TextBaseline,
649    ) -> Option<f64> {
650        let scale = self.scale(app);
651        let distance = self.child(app)?.get_dry_baseline(
652            app,
653            BoxConstraints::new().max_width(constraints.max_width / scale),
654            baseline,
655        );
656        distance.map(|distance| scale * distance)
657    }
658
659    fn compute_dry_layout(
660        self: RenderHandle<Self>,
661        app: &mut App,
662        constraints: BoxConstraints,
663    ) -> Size {
664        debug_assert!(!constraints.has_bounded_height());
665        let scale = self.scale(app);
666        let unscaled_size = self.child(app).map_or(Size::ZERO, |child| {
667            child.get_dry_layout(
668                app,
669                BoxConstraints::new().max_width(constraints.max_width / scale),
670            )
671        });
672        constraints.constrain(unscaled_size * scale)
673    }
674
675    fn apply_paint_transform(
676        self: RenderHandle<Self>,
677        app: &App,
678        _child: AnyRenderObject,
679        transform: &mut Matrix4,
680    ) {
681        *transform = transform.then(&self.scale_matrix(app));
682    }
683
684    fn hit_test_children(
685        self: RenderHandle<Self>,
686        app: &mut App,
687        result: &mut BoxHitTestResult<'_>,
688        position: Offset,
689    ) -> bool {
690        let Some(child) = self.child(app) else {
691            return false;
692        };
693        let transform = self.scale_matrix(app);
694        result.add_with_paint_transform(Some(transform), position, |result, transformed| {
695            child.hit_test(app, result, transformed)
696        })
697    }
698}
699
700#[cfg(test)]
701mod tests {
702    use waft_embedder::Color;
703    use waft_embedder::{TextDirection, TextLeadingDistribution};
704    use waft_foundation::AppCell;
705    use waft_gestures::HitTestResult;
706    use waft_painting::{PaintingBinding, TextOverflow, TextSpan};
707    use waft_rendering::{RenderColoredBox, RenderIntrinsicHeight, RenderParagraph};
708
709    use super::*;
710    use crate::test_harness::Harness;
711    use crate::widgets::basic::{
712        Center, ColoredBox, Directionality, IntrinsicHeight, Row, SizedBox,
713    };
714    use crate::widgets::text::{RichText, Text};
715
716    /// What the shell does at start-up: the app-wide fonts, here the OS fonts.
717    fn install_fonts(app: &mut App) {
718        let binding = PaintingBinding::instance(app);
719        if !binding.has_fonts(app) {
720            binding.install_fonts(app, |fonts| {
721                fonts.add_source(valo_system_fonts::SystemFonts::load());
722            });
723        }
724    }
725
726    /// Mounts `child` under a left-to-right `Directionality` with fonts installed, and pumps
727    /// the first frame.
728    fn mount(app: &mut App, child: WidgetRef) -> Harness {
729        install_fonts(app);
730        let harness = Harness::mount(
731            app,
732            Directionality::new(TextDirection::Ltr, child).into_widget(),
733        );
734        harness.pump(app);
735        harness
736    }
737
738    /// The only child of `parent` in the render tree.
739    fn only_child(app: &App, parent: AnyRenderObject) -> AnyRenderObject {
740        let mut children = Vec::new();
741        parent.visit_children(app, &mut |child| children.push(child));
742        assert_eq!(children.len(), 1, "one child");
743        children[0]
744    }
745
746    fn paragraph_under(app: &App, harness: &Harness) -> RenderHandle<RenderParagraph> {
747        only_child(app, harness.render_root(app).as_object())
748            .downcast::<RenderParagraph>(app)
749            .expect("a RenderParagraph")
750    }
751
752    fn sized_box(width: f64, height: f64) -> WidgetRef {
753        SizedBox::new().width(width).height(height).into_widget()
754    }
755
756    fn text(text: &str) -> InlineSpanRef {
757        TextSpan::new().text(text).into_span()
758    }
759
760    #[test]
761    fn a_widget_span_lays_its_child_out_between_the_text() {
762        let cell = AppCell::new();
763        let mut app = cell.borrow_mut();
764        let span = TextSpan::new()
765            .children(vec![
766                text("ab"),
767                WidgetSpan::new(sized_box(30.0, 20.0)).into_span(),
768                text("cd"),
769            ])
770            .into_span();
771        let harness = mount(
772            &mut app,
773            Center::new().child(Text::rich(span)).into_widget(),
774        );
775        let paragraph = only_child(&app, harness.render_root(&app).as_object())
776            .downcast::<waft_rendering::RenderPositionedBox>(&app)
777            .map(|center| only_child(&app, center.as_object()))
778            .and_then(|child| child.downcast::<RenderParagraph>(&app))
779            .expect("a RenderParagraph under the Center");
780        assert_eq!(
781            paragraph.text(&app).to_plain_text(true, true),
782            "ab\u{FFFC}cd"
783        );
784        let inline = only_child(&app, paragraph.as_object());
785        let parent_data = inline.parent_data_of::<TextParentData>(&app);
786        assert!(
787            parent_data.span.is_some(),
788            "the parent data widget set the span"
789        );
790        let offset = parent_data.offset().expect("laid out");
791        assert!(offset.dx() > 0.0, "after \"ab\"");
792        let inline = inline.as_box().expect("a box");
793        assert_eq!(inline.size(&app), Size::new(30.0, 20.0));
794        let width = paragraph.size(&app).width();
795        assert!(width > offset.dx() + 30.0, "\"cd\" follows the widget");
796        assert!(paragraph.size(&app).height() >= 20.0);
797    }
798
799    // Regression test for https://github.com/flutter/flutter/issues/35869
800    #[test]
801    fn inline_widgets_works_with_ellipsis() {
802        let cell = AppCell::new();
803        let mut app = cell.borrow_mut();
804        let truncated =
805            RichText::new(text("widget should be truncated")).text_direction(TextDirection::Rtl);
806        let span = TextSpan::new()
807            .children(vec![
808                text("a very very very very very very very very very very long line"),
809                WidgetSpan::new(SizedBox::new().width(20.0).height(40.0).child(truncated))
810                    .into_span(),
811            ])
812            .into_span();
813        let harness = mount(
814            &mut app,
815            Text::rich(span)
816                .max_lines(1)
817                .overflow(TextOverflow::Ellipsis)
818                .into_widget(),
819        );
820        let paragraph = paragraph_under(&app, &harness);
821        let inline = only_child(&app, paragraph.as_object());
822        assert_eq!(
823            inline.parent_data_of::<TextParentData>(&app).offset(),
824            None,
825            "ellipsized away"
826        );
827    }
828
829    #[test]
830    fn a_hit_on_an_inline_widget_reaches_it_and_a_hit_on_the_text_lands_on_its_span() {
831        let cell = AppCell::new();
832        let mut app = cell.borrow_mut();
833        let opaque = ColoredBox::new(Color::from_argb(255, 0, 0, 255)).child(sized_box(30.0, 20.0));
834        let span = TextSpan::new()
835            .children(vec![text("ab"), WidgetSpan::new(opaque).into_span()])
836            .into_span();
837        let harness = mount(
838            &mut app,
839            Center::new().child(Text::rich(span)).into_widget(),
840        );
841        let center = only_child(&app, harness.render_root(&app).as_object());
842        let paragraph = only_child(&app, center)
843            .downcast::<RenderParagraph>(&app)
844            .expect("a RenderParagraph");
845        let inline = only_child(&app, paragraph.as_object());
846        let offset = inline
847            .parent_data_of::<TextParentData>(&app)
848            .offset()
849            .expect("laid out");
850
851        let mut result = HitTestResult::new();
852        let hit = paragraph.as_box().hit_test(
853            &mut app,
854            &mut BoxHitTestResult::wrap(&mut result),
855            offset + Offset::new(15.0, 10.0),
856        );
857        assert!(hit);
858        assert!(
859            only_child(&app, inline)
860                .downcast::<RenderColoredBox>(&app)
861                .is_some()
862        );
863        assert_eq!(
864            result.path().len(),
865            3,
866            "the colored box, the scaled inline box and the paragraph"
867        );
868
869        let mut result = HitTestResult::new();
870        paragraph.as_box().hit_test(
871            &mut app,
872            &mut BoxHitTestResult::wrap(&mut result),
873            Offset::new(1.0, offset.dy() + 10.0),
874        );
875        assert_eq!(result.path().len(), 2, "the span and the paragraph");
876        let target: &dyn std::any::Any = result.path()[0].target();
877        assert_eq!(
878            target
879                .downcast_ref::<TextSpan>()
880                .and_then(|span| span.text.as_deref()),
881            Some("ab")
882        );
883    }
884
885    // Regression test for https://github.com/flutter/flutter/issues/59316
886    #[test]
887    fn inline_widgets_works_with_text_scaler() {
888        let cell = AppCell::new();
889        let mut app = cell.borrow_mut();
890        let rich = |scale: f64| {
891            let span = TextSpan::new()
892                .children(vec![WidgetSpan::new(sized_box(30.0, 20.0)).into_span()])
893                .into_span();
894            Center::new()
895                .child(Text::rich(span).text_scaler(TextScaler::linear(scale)))
896                .into_widget()
897        };
898        let harness = mount(&mut app, rich(1.0));
899        let inline_size = |app: &App| {
900            let center = only_child(app, harness.render_root(app).as_object());
901            let paragraph = only_child(app, center);
902            only_child(app, paragraph)
903                .as_box()
904                .expect("a box")
905                .size(app)
906        };
907        assert_eq!(inline_size(&app), Size::new(30.0, 20.0));
908
909        harness.set_child(
910            &mut app,
911            Directionality::new(TextDirection::Ltr, rich(2.0)).into_widget(),
912        );
913        harness.pump(&mut app);
914        assert_eq!(inline_size(&app), Size::new(60.0, 40.0));
915    }
916
917    #[test]
918    fn widget_span_calculate_correct_intrinsic_heights() {
919        let cell = AppCell::new();
920        let mut app = cell.borrow_mut();
921        let line = TextStyle::new()
922            .height(1.0)
923            .font_size(16.0)
924            .leading_distribution(TextLeadingDistribution::Even);
925        let span = TextSpan::new()
926            .children(vec![
927                TextSpan::new()
928                    .text("Start\n")
929                    .style(line.clone())
930                    .into_span(),
931                WidgetSpan::new(Row::new().children([sized_box(16.0, 16.0)])).into_span(),
932                TextSpan::new().text("End").style(line).into_span(),
933            ])
934            .into_span();
935        let harness = mount(
936            &mut app,
937            Center::new()
938                .child(IntrinsicHeight::new().child(RichText::new(span)))
939                .into_widget(),
940        );
941        let center = only_child(&app, harness.render_root(&app).as_object());
942        let intrinsic = only_child(&app, center)
943            .downcast::<RenderIntrinsicHeight>(&app)
944            .expect("a RenderIntrinsicHeight");
945        assert_eq!(intrinsic.size(&app).height(), 3.0 * 16.0);
946    }
947
948    /// `paragraph_test.dart`'s `TestSelectionRegistrar`.
949    struct TestSelectionRegistrar {
950        selectables: Vec<waft_rendering::AnySelectable>,
951    }
952
953    impl waft_rendering::SelectionRegistrar for TestSelectionRegistrar {
954        fn add(
955            self: waft_foundation::Handle<Self>,
956            app: &mut App,
957            selectable: waft_rendering::AnySelectable,
958        ) {
959            app.get_mut(self).selectables.push(selectable);
960        }
961
962        fn remove(
963            self: waft_foundation::Handle<Self>,
964            app: &mut App,
965            selectable: waft_rendering::AnySelectable,
966        ) {
967            app.get_mut(self).selectables.retain(|s| *s != selectable);
968        }
969    }
970
971    // paragraph_test.dart 'can handle select all when contains widget span': a rendering case,
972    // here because `WidgetSpan` is a widgets type.
973    #[test]
974    fn can_handle_select_all_when_contains_widget_span() {
975        use waft_rendering::{ContainerRenderObjectMixin as _, SelectionEvent, SelectionStatus};
976
977        let cell = AppCell::new();
978        let mut app = cell.borrow_mut();
979        let registrar = app.create(TestSelectionRegistrar {
980            selectables: Vec::new(),
981        });
982        let render_box = RenderParagraph::new(&mut app, text("widget"), TextDirection::Ltr, None);
983        let widget_span = WidgetSpan::new(Text::new("widget"));
984        let paragraph = RenderParagraph::new(
985            &mut app,
986            TextSpan::new()
987                .children(vec![
988                    text("before the span"),
989                    widget_span.clone().into_span(),
990                    text("after the span"),
991                ])
992                .into_span(),
993            TextDirection::Ltr,
994            None,
995        );
996        paragraph.set_registrar(&mut app, Some(registrar.erase()));
997        paragraph.add(&mut app, render_box.as_box());
998        // `_applyParentData`.
999        render_box
1000            .as_object()
1001            .parent_data_of_mut::<TextParentData>(&mut app)
1002            .span = Some(std::rc::Rc::new(widget_span));
1003        waft_rendering::testing::layout(&mut app, paragraph.as_box());
1004        // The widget span will register to the selection container without going
1005        // through the render paragraph.
1006        let selectables = app.get(&registrar).selectables.clone();
1007        assert_eq!(selectables.len(), 2);
1008        for segment in selectables {
1009            segment.dispatch_selection_event(&mut app, &SelectionEvent::SelectAll);
1010            let geometry = segment.value(&app);
1011            assert!(geometry.has_content);
1012            assert_eq!(geometry.status, SelectionStatus::Uncollapsed);
1013        }
1014    }
1015}