Skip to main content

waft_painting/
inline_span.rs

1//! Flutter counterpart: `painting/inline_span.dart`.
2//!
3//! `InlineSpanSemanticsInformation` and `computeSemanticsInformation` wait with the rest of
4//! accessibility.
5
6use std::any::Any;
7use std::fmt::Debug;
8use std::rc::Rc;
9
10use waft_embedder::{ParagraphBuilder, TextPosition};
11use waft_foundation::{
12    DiagnosticPropertiesBuilder, Diagnosticable, DiagnosticableTreeNode, DiagnosticsNode,
13    DiagnosticsTreeStyle, bare_type_name,
14};
15use waft_gestures::HitTestTarget;
16
17use crate::basic_types::RenderComparison;
18use crate::placeholder_span::PlaceholderSpan;
19use crate::text_painter::PlaceholderDimensions;
20use crate::text_scaler::TextScaler;
21use crate::text_style::TextStyle;
22
23/// Mutable wrapper of an integer that can be passed by reference to track a value across a
24/// recursive stack.
25#[derive(Debug, Default)]
26pub struct Accumulator {
27    value: i32,
28}
29
30impl Accumulator {
31    /// Creates an [`Accumulator`] starting at `value`.
32    pub fn new(value: i32) -> Accumulator {
33        Accumulator { value }
34    }
35
36    /// The integer stored in this [`Accumulator`].
37    pub fn value(&self) -> i32 {
38        self.value
39    }
40
41    /// Increases the [`value`](Self::value) by the `addend`.
42    pub fn increment(&mut self, addend: i32) {
43        debug_assert!(addend >= 0);
44        self.value += addend;
45    }
46}
47
48/// A shared, immutable span (Dart's `InlineSpan` reference).
49pub type InlineSpanRef = Rc<dyn InlineSpan>;
50
51/// An immutable span of inline content which forms part of a paragraph.
52///
53///  * The subclass `TextSpan` specifies text and may contain child [`InlineSpan`]s.
54///  * The subclass [`PlaceholderSpan`] represents a placeholder that may be filled with
55///    non-text content.
56///
57/// Spans are shared as [`InlineSpanRef`]. The walks hand each span to their visitor as the
58/// [`InlineSpanRef`] that holds it, so [`get_span_for_position`](Self::get_span_for_position)
59/// returns the span itself, as Dart returns the same object.
60pub trait InlineSpan: Debug {
61    /// The [`TextStyle`] to apply to this span.
62    ///
63    /// The [`style`](Self::style) is also applied to any child spans when this is an instance
64    /// of `TextSpan`.
65    fn style(&self) -> Option<&TextStyle>;
66
67    /// Apply the properties of this object to the given [`ParagraphBuilder`], from which a
68    /// `Paragraph` can be obtained.
69    ///
70    /// The `text_scaler` parameter specifies a [`TextScaler`] that the text and placeholders
71    /// will be scaled by. The scaling is performed before layout, so the text will be laid
72    /// out with the scaled glyphs and placeholders.
73    ///
74    /// The `dimensions` parameter specifies the sizes of the placeholders. Each
75    /// `PlaceholderSpan` must be paired with a [`PlaceholderDimensions`] in the same order as
76    /// defined in the [`InlineSpan`] tree.
77    ///
78    /// `Paragraph` objects can be drawn on `Canvas` objects.
79    fn build(
80        &self,
81        builder: &mut ParagraphBuilder,
82        text_scaler: &TextScaler,
83        dimensions: Option<&[PlaceholderDimensions]>,
84    );
85
86    /// Walks this [`InlineSpan`] and any descendants in pre-order and calls `visitor` for
87    /// each span that has content.
88    ///
89    /// When `visitor` returns true, the walk will continue. When `visitor` returns false,
90    /// then the walk will end.
91    ///
92    /// It is called through the span's own [`InlineSpanRef`], so it can hand that to
93    /// `visitor`.
94    fn visit_children(self: Rc<Self>, visitor: &mut dyn FnMut(&InlineSpanRef) -> bool) -> bool;
95
96    /// Calls `visitor` for each immediate child of this [`InlineSpan`].
97    ///
98    /// The immediate children are visited in the same order they are added to a
99    /// [`ParagraphBuilder`] in the [`build`](Self::build) method, which is also the logical
100    /// order of the child [`InlineSpan`]s in the text.
101    ///
102    /// The traversal stops when all immediate children are visited, or when `visitor` returns
103    /// false. When `visitor` returns false, the walk will end.
104    fn visit_direct_children(&self, visitor: &mut dyn FnMut(&InlineSpanRef) -> bool) -> bool;
105
106    /// Returns the [`InlineSpan`] that contains the given position in the text.
107    fn get_span_for_position(self: Rc<Self>, position: TextPosition) -> Option<InlineSpanRef> {
108        debug_assert!(self.debug_assert_is_valid());
109        let mut offset = Accumulator::default();
110        let mut result: Option<InlineSpanRef> = None;
111        self.visit_children(&mut |span| {
112            result = span
113                .clone()
114                .get_span_for_position_visitor(position, &mut offset);
115            result.is_none()
116        });
117        result
118    }
119
120    /// Performs the check at each [`InlineSpan`] for if the `position` falls within the
121    /// range.
122    ///
123    /// The `offset` parameter tracks the current index offset in the text buffer formed if
124    /// the contents of the [`InlineSpan`] tree were concatenated together starting from the
125    /// root [`InlineSpan`].
126    ///
127    /// This method should not be directly called. Use [`get_span_for_position`] instead.
128    ///
129    /// [`get_span_for_position`]: Self::get_span_for_position
130    fn get_span_for_position_visitor(
131        self: Rc<Self>,
132        position: TextPosition,
133        offset: &mut Accumulator,
134    ) -> Option<InlineSpanRef>;
135
136    /// Flattens the [`InlineSpan`] tree into a single string.
137    ///
138    /// Styles are not honored in this process. If `include_semantics_labels` is true, then
139    /// the text returned will include the semantics labels over the text. If
140    /// `include_placeholders` is true, then the placeholder character will be included for
141    /// placeholders.
142    fn to_plain_text(&self, include_semantics_labels: bool, include_placeholders: bool) -> String {
143        let mut buffer = String::new();
144        self.compute_to_plain_text(&mut buffer, include_semantics_labels, include_placeholders);
145        buffer
146    }
147
148    /// Walks the [`InlineSpan`] tree and writes the plain text representation to the
149    /// `buffer`.
150    ///
151    /// This method should not be directly called. Use [`to_plain_text`] instead.
152    ///
153    /// [`to_plain_text`]: Self::to_plain_text
154    fn compute_to_plain_text(
155        &self,
156        buffer: &mut String,
157        include_semantics_labels: bool,
158        include_placeholders: bool,
159    );
160
161    /// Returns the UTF-16 code unit at the given `index` in the flattened string.
162    ///
163    /// This only accounts for the `TextSpan.text` values and ignores `PlaceholderSpan`s.
164    ///
165    /// Returns `None` if the `index` is out of bounds.
166    fn code_unit_at(self: Rc<Self>, index: i32) -> Option<u16> {
167        if index < 0 {
168            return None;
169        }
170        let mut offset = Accumulator::default();
171        let mut result = None;
172        self.visit_children(&mut |span| {
173            result = span.code_unit_at_visitor(index, &mut offset);
174            result.is_none()
175        });
176        result
177    }
178
179    /// Performs the check at each [`InlineSpan`] for if the `index` falls within the range
180    /// of the span and returns the corresponding code unit. Returns `None` otherwise.
181    ///
182    /// The `offset` parameter tracks the current index offset in the text buffer formed if
183    /// the contents of the [`InlineSpan`] tree were concatenated together starting from the
184    /// root [`InlineSpan`].
185    ///
186    /// This method should not be directly called. Use [`code_unit_at`] instead.
187    ///
188    /// [`code_unit_at`]: Self::code_unit_at
189    fn code_unit_at_visitor(&self, index: i32, offset: &mut Accumulator) -> Option<u16>;
190
191    /// In debug mode, throws an exception if the object is not in a valid configuration.
192    /// Otherwise, returns true.
193    ///
194    /// This is intended to be used as follows: `debug_assert!(span.debug_assert_is_valid())`.
195    fn debug_assert_is_valid(&self) -> bool {
196        true
197    }
198
199    /// Describe the difference between this span and another, in terms of how much damage
200    /// it will make to the rendering. The comparison is deep.
201    ///
202    /// Comparing [`InlineSpan`] objects of different types, for example, comparing a
203    /// `TextSpan` to a `WidgetSpan`, always results in [`RenderComparison::Layout`].
204    fn compare_to(&self, other: &dyn InlineSpan) -> RenderComparison;
205
206    /// Downcast support for Dart's `runtimeType` and `is` checks.
207    fn as_any(&self) -> &dyn Any;
208
209    /// Dart's `span is PlaceholderSpan`: this span as a [`PlaceholderSpan`], when it is one.
210    fn as_placeholder_span(&self) -> Option<&dyn PlaceholderSpan> {
211        None
212    }
213
214    /// Dart's `span is HitTestTarget`: this span as the target a hit on it adds to a hit test,
215    /// when it is one. `None`, the default, for a span that is not.
216    fn to_hit_test_target(self: Rc<Self>) -> Option<Rc<dyn HitTestTarget>> {
217        None
218    }
219
220    /// Dart's `==`: deep equality on the same span class.
221    fn eq_span(&self, other: &dyn InlineSpan) -> bool;
222
223    /// Dart's `InlineSpan.debugFillProperties`, inherited from `Diagnosticable`: the tree
224    /// style and the span's style.
225    ///
226    /// Dart's `debugFillProperties` lives on `Diagnosticable`, whose `Self: Sized` bound a
227    /// `dyn InlineSpan` cannot meet; a concrete span delegates its own diagnostics here.
228    fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
229        inline_span_debug_fill_properties(self.style(), properties);
230    }
231
232    /// Dart's `InlineSpan.debugDescribeChildren`, inherited from `DiagnosticableTree`.
233    fn debug_describe_children(&self) -> Vec<Rc<dyn DiagnosticsNode>> {
234        Vec::new()
235    }
236
237    /// Dart's `InlineSpan.toDiagnosticsNode(name:, style:)`, inherited from
238    /// `Diagnosticable`; a `dyn InlineSpan` answers through this method.
239    fn diagnostics_node(
240        &self,
241        name: Option<String>,
242        style: Option<DiagnosticsTreeStyle>,
243    ) -> DiagnosticableTreeNode {
244        let mut builder = DiagnosticPropertiesBuilder::new();
245        self.debug_fill_properties(&mut builder);
246        let mut node = DiagnosticableTreeNode::from_parts(
247            name,
248            self.to_string_short(),
249            builder,
250            self.debug_describe_children(),
251        );
252        if let Some(style) = style {
253            node = node.with_style(style);
254        }
255        node
256    }
257
258    /// Dart's `Diagnosticable.toStringShort` for this span: the type name, as Dart prints
259    /// `runtimeType`.
260    fn to_string_short(&self) -> String {
261        bare_type_name(std::any::type_name::<Self>()).to_string()
262    }
263}
264
265/// Dart's `InlineSpan.debugFillProperties`: the whitespace tree style, then the properties of
266/// the span's `style`. A span that adds its own calls this first, as Dart's `super` does.
267pub fn inline_span_debug_fill_properties(
268    style: Option<&TextStyle>,
269    properties: &mut DiagnosticPropertiesBuilder,
270) {
271    properties.default_diagnostics_tree_style = DiagnosticsTreeStyle::Whitespace;
272    if let Some(style) = style {
273        Diagnosticable::debug_fill_properties(style, properties);
274    }
275}
276
277impl PartialEq for dyn InlineSpan {
278    fn eq(&self, other: &dyn InlineSpan) -> bool {
279        self.eq_span(other)
280    }
281}
282
283/// Dart's `identical(a, b)` on two span references.
284pub fn same_span(a: &dyn InlineSpan, b: &dyn InlineSpan) -> bool {
285    std::ptr::addr_eq(a as *const dyn InlineSpan, b as *const dyn InlineSpan)
286}
287
288/// The number of UTF-16 code units in `text` (Dart's `String.length`).
289pub(crate) fn utf16_len(text: &str) -> i32 {
290    text.encode_utf16().count() as i32
291}