Skip to main content

freya_core/elements/
paragraph.rs

1//! [paragraph()] makes it possible to render rich text with different styles. Its a more customizable API than [crate::elements::label].
2
3use std::{
4    any::Any,
5    borrow::Cow,
6    cell::RefCell,
7    fmt::{
8        Debug,
9        Display,
10    },
11    rc::Rc,
12};
13
14use freya_engine::prelude::{
15    Canvas,
16    FontCollection,
17    FontStyle,
18    Paint,
19    PaintStyle,
20    ParagraphBuilder,
21    ParagraphStyle,
22    PlaceholderAlignment,
23    PlaceholderStyle,
24    RectHeightStyle,
25    RectWidthStyle,
26    SkParagraph,
27    SkRect,
28    TextBaseline,
29    TextStyle,
30};
31use torin::prelude::{
32    Area,
33    CursorPoint,
34    Gaps,
35    Length,
36    Point2D,
37    Position,
38    PostMeasure,
39    Size2D,
40    SizeModel,
41};
42use unicode_segmentation::UnicodeSegmentation;
43
44use crate::{
45    data::{
46        AccessibilityData,
47        CursorStyleData,
48        EffectData,
49        LayoutData,
50        StyleState,
51        TextStyleData,
52        TextStyleState,
53    },
54    diff_key::DiffKey,
55    element::{
56        Element,
57        ElementExt,
58        EventHandlers,
59        IntoElement,
60        LayoutContext,
61        PostMeasureContext,
62        RenderContext,
63    },
64    elements::rect::rect,
65    layers::Layer,
66    node_id::NodeId,
67    prelude::{
68        AccessibilityExt,
69        ChildrenExt,
70        Color,
71        ContainerExt,
72        ContainerPositionExt,
73        EffectExt,
74        EventHandlersExt,
75        KeyExt,
76        LayerExt,
77        LayoutExt,
78        MaybeExt,
79        TextAlign,
80        TextOverflowExt,
81        TextStyleExt,
82        VerticalAlign,
83    },
84    style::cursor::{
85        CursorMode,
86        CursorStyle,
87    },
88    text_cache::CachedParagraph,
89    tree::DiffModifies,
90};
91
92/// [paragraph()] makes it possible to render rich text with different styles. Its a more customizable API than [crate::elements::label].
93///
94/// See the available methods in [Paragraph].
95///
96/// ```rust
97/// # use freya::prelude::*;
98/// fn app() -> impl IntoElement {
99///     paragraph()
100///         .span(Span::new("Hello").font_size(24.0))
101///         .span(Span::new("World").font_size(16.0))
102/// }
103/// ```
104pub fn paragraph() -> Paragraph {
105    Paragraph::default()
106}
107
108pub struct ParagraphHolderInner {
109    pub paragraph: Rc<SkParagraph>,
110    pub scale_factor: f64,
111    pub padding: Gaps,
112}
113
114/// A shared slot that receives the laid-out paragraph, so callers can hit-test and measure
115/// text after layout. Pass it to a [`paragraph()`] with [`Paragraph::holder`].
116#[derive(Clone)]
117pub struct ParagraphHolder(pub Rc<RefCell<Option<ParagraphHolderInner>>>);
118
119impl PartialEq for ParagraphHolder {
120    fn eq(&self, other: &Self) -> bool {
121        Rc::ptr_eq(&self.0, &other.0)
122    }
123}
124
125impl Debug for ParagraphHolder {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        f.write_str("ParagraphHolder")
128    }
129}
130
131impl Default for ParagraphHolder {
132    fn default() -> Self {
133        Self(Rc::new(RefCell::new(None)))
134    }
135}
136
137impl ParagraphHolder {
138    pub fn visible_location(&self, location: CursorPoint) -> CursorPoint {
139        let holder_data = self.0.borrow();
140        let Some(holder) = holder_data.as_ref() else {
141            return location;
142        };
143
144        CursorPoint::new(
145            location.x - f64::from(holder.padding.left()) / holder.scale_factor,
146            location.y - f64::from(holder.padding.top()) / holder.scale_factor,
147        )
148    }
149}
150
151/// Marks the order of a [Paragraph]'s content.
152#[derive(PartialEq, Clone)]
153pub enum ParagraphContent {
154    Span,
155    Element,
156}
157
158#[derive(PartialEq, Clone)]
159pub struct ParagraphElement {
160    pub layout: LayoutData,
161    pub spans: Vec<Span<'static>>,
162    pub contents: Vec<ParagraphContent>,
163    pub accessibility: AccessibilityData,
164    pub text_style_data: TextStyleData,
165    pub cursor_style_data: CursorStyleData,
166    pub event_handlers: EventHandlers,
167    pub sk_paragraph: ParagraphHolder,
168    pub cursor_index: Option<usize>,
169    pub highlights: Vec<(usize, usize)>,
170    pub max_lines: Option<usize>,
171    pub line_height: Option<f32>,
172    pub relative_layer: Layer,
173    pub cursor_style: CursorStyle,
174    pub cursor_mode: CursorMode,
175    pub vertical_align: VerticalAlign,
176    pub effect: Option<EffectData>,
177}
178
179impl Default for ParagraphElement {
180    fn default() -> Self {
181        let mut accessibility = AccessibilityData::default();
182        accessibility.builder.set_role(accesskit::Role::Paragraph);
183        Self {
184            layout: Default::default(),
185            spans: Default::default(),
186            contents: Default::default(),
187            accessibility,
188            text_style_data: Default::default(),
189            cursor_style_data: Default::default(),
190            event_handlers: Default::default(),
191            sk_paragraph: Default::default(),
192            cursor_index: Default::default(),
193            highlights: Default::default(),
194            max_lines: Default::default(),
195            line_height: Default::default(),
196            relative_layer: Default::default(),
197            cursor_style: CursorStyle::default(),
198            cursor_mode: CursorMode::default(),
199            vertical_align: VerticalAlign::default(),
200            effect: None,
201        }
202    }
203}
204
205impl Display for ParagraphElement {
206    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207        f.write_str(
208            &self
209                .spans
210                .iter()
211                .map(|s| s.text.clone())
212                .collect::<Vec<_>>()
213                .join("\n"),
214        )
215    }
216}
217
218impl ElementExt for ParagraphElement {
219    fn changed(&self, other: &Rc<dyn ElementExt>) -> bool {
220        let Some(paragraph) = (other.as_ref() as &dyn Any).downcast_ref::<ParagraphElement>()
221        else {
222            return false;
223        };
224        self != paragraph
225    }
226
227    fn diff(&self, other: &Rc<dyn ElementExt>) -> DiffModifies {
228        let Some(paragraph) = (other.as_ref() as &dyn Any).downcast_ref::<ParagraphElement>()
229        else {
230            return DiffModifies::all();
231        };
232
233        let mut diff = DiffModifies::empty();
234
235        if self.spans != paragraph.spans || self.contents != paragraph.contents {
236            diff.insert(DiffModifies::STYLE);
237            diff.insert(DiffModifies::LAYOUT);
238            diff.insert(DiffModifies::ACCESSIBILITY);
239        }
240
241        if self.accessibility != paragraph.accessibility {
242            diff.insert(DiffModifies::ACCESSIBILITY);
243        }
244
245        if self.relative_layer != paragraph.relative_layer {
246            diff.insert(DiffModifies::LAYER);
247        }
248
249        if self.effect != paragraph.effect {
250            diff.insert(DiffModifies::EFFECT);
251        }
252
253        if self.text_style_data != paragraph.text_style_data {
254            diff.insert(DiffModifies::STYLE);
255        }
256
257        if self.event_handlers != paragraph.event_handlers {
258            diff.insert(DiffModifies::EVENT_HANDLERS);
259        }
260
261        if self.cursor_index != paragraph.cursor_index
262            || self.highlights != paragraph.highlights
263            || self.cursor_mode != paragraph.cursor_mode
264            || self.cursor_style != paragraph.cursor_style
265            || self.cursor_style_data != paragraph.cursor_style_data
266            || self.vertical_align != paragraph.vertical_align
267        {
268            diff.insert(DiffModifies::STYLE);
269        }
270
271        if self.text_style_data != paragraph.text_style_data
272            || self.line_height != paragraph.line_height
273            || self.max_lines != paragraph.max_lines
274        {
275            diff.insert(DiffModifies::TEXT_STYLE);
276            diff.insert(DiffModifies::LAYOUT);
277        }
278
279        if self.layout != paragraph.layout {
280            diff.insert(DiffModifies::STYLE);
281            diff.insert(DiffModifies::LAYOUT);
282        }
283
284        // If holder is different and there is a change,  rerun layout
285        if !diff.is_empty() && self.sk_paragraph != paragraph.sk_paragraph {
286            diff.insert(DiffModifies::LAYOUT);
287        }
288
289        diff
290    }
291
292    fn layout(&'_ self) -> Cow<'_, LayoutData> {
293        Cow::Borrowed(&self.layout)
294    }
295    fn effect(&'_ self) -> Option<Cow<'_, EffectData>> {
296        self.effect.as_ref().map(Cow::Borrowed)
297    }
298
299    fn style(&'_ self) -> Cow<'_, StyleState> {
300        Cow::Owned(StyleState::default())
301    }
302
303    fn is_transparent(&self) -> bool {
304        false
305    }
306
307    fn text_style(&'_ self) -> Cow<'_, TextStyleData> {
308        Cow::Borrowed(&self.text_style_data)
309    }
310
311    fn accessibility(&'_ self) -> Cow<'_, AccessibilityData> {
312        Cow::Borrowed(&self.accessibility)
313    }
314
315    fn finish_accessibility(&self, builder: &mut accesskit::Node) {
316        builder.set_value(
317            self.spans
318                .iter()
319                .map(|span| span.text.as_ref())
320                .collect::<String>(),
321        );
322    }
323
324    fn layer(&self) -> Layer {
325        self.relative_layer
326    }
327
328    fn measure(&self, context: LayoutContext) -> Option<(Size2D, Rc<dyn Any>)> {
329        let content_area_size =
330            (*context.area_size - context.torin_node.padding.into()).max(Size2D::zero());
331        let cached_paragraph = CachedParagraph {
332            text_style_state: context.text_style_state,
333            spans: &self.spans,
334            max_lines: self.max_lines,
335            line_height: self.line_height,
336            width: content_area_size.width,
337        };
338        let paragraph = context
339            .text_cache
340            .utilize(context.node_id, &cached_paragraph)
341            .unwrap_or_else(|| {
342                let width = if self.max_lines == Some(1)
343                    && context.text_style_state.text_align == TextAlign::default()
344                    && context
345                        .text_style_state
346                        .text_overflow
347                        .get_ellipsis()
348                        .is_none()
349                {
350                    f32::MAX
351                } else {
352                    content_area_size.width + 1.0
353                };
354
355                let paragraph = self.build_paragraph(
356                    context.text_style_state,
357                    context.fallback_fonts,
358                    context.scale_factor,
359                    context.font_collection,
360                    width,
361                    &[],
362                );
363                context
364                    .text_cache
365                    .insert(context.node_id, &cached_paragraph, paragraph)
366            });
367
368        let size = Size2D::new(paragraph.longest_line(), paragraph.height())
369            .max(Size2D::zero())
370            .with_gaps(&context.torin_node.padding);
371
372        self.sk_paragraph
373            .0
374            .borrow_mut()
375            .replace(ParagraphHolderInner {
376                paragraph,
377                scale_factor: context.scale_factor,
378                padding: context.torin_node.padding,
379            });
380
381        Some((size, Rc::new(())))
382    }
383
384    fn should_hook_measurement(&self) -> bool {
385        true
386    }
387
388    fn should_measure_inner_children(&self) -> bool {
389        self.has_inline_content()
390    }
391
392    fn needs_post_measure(&self) -> bool {
393        self.has_inline_content()
394    }
395
396    fn post_measure(&self, context: PostMeasureContext) -> PostMeasure<NodeId> {
397        if context.children.is_empty() {
398            return PostMeasure::default();
399        }
400
401        let placeholders: Vec<Size2D> = context
402            .children
403            .iter()
404            .map(|child| {
405                context
406                    .layout
407                    .get(child)
408                    .map(|node| node.area.size)
409                    .unwrap()
410            })
411            .collect();
412
413        let width = self
414            .sk_paragraph
415            .0
416            .borrow()
417            .as_ref()
418            .map(|holder| holder.paragraph.max_width())
419            .unwrap();
420
421        let paragraph = self.build_paragraph(
422            context.text_style_state,
423            context.fallback_fonts,
424            context.scale_factor,
425            context.font_collection,
426            width,
427            &placeholders,
428        );
429        let rects = paragraph.get_rects_for_placeholders();
430        let paragraph_height = paragraph.height();
431        // The size with the placeholders in place, so the node is sized around the inline children.
432        let content_size = Size2D::new(paragraph.longest_line(), paragraph_height);
433
434        self.sk_paragraph
435            .0
436            .borrow_mut()
437            .replace(ParagraphHolderInner {
438                paragraph: Rc::new(paragraph),
439                scale_factor: context.scale_factor,
440                padding: self.layout.layout.padding,
441            });
442
443        let inner_area = context.node_layout.inner_area;
444        let vertical_offset = match self.vertical_align {
445            VerticalAlign::Start => 0.0,
446            VerticalAlign::Center => (inner_area.height() - paragraph_height).max(0.0) / 2.0,
447        };
448        let origin = inner_area.origin;
449
450        let mut offsets = Vec::new();
451        let mut hidden_children = Vec::new();
452        for (index, child_id) in context.children.iter().enumerate() {
453            let Some(current) = context.layout.get(child_id).map(|node| node.area.origin) else {
454                continue;
455            };
456            match rects.get(index) {
457                Some(rect) => {
458                    let offset_x = origin.x + rect.rect.left - current.x;
459                    let offset_y = origin.y + vertical_offset + rect.rect.top - current.y;
460                    offsets.push((*child_id, Length::new(offset_x), Length::new(offset_y)));
461                }
462                // Children whose placeholder got cut off by max_lines or ellipsis are hidden.
463                None => hidden_children.push(*child_id),
464            }
465        }
466
467        PostMeasure {
468            content_size: Some(content_size),
469            offsets,
470            hidden_children,
471        }
472    }
473
474    fn events_handlers(&'_ self) -> Option<Cow<'_, EventHandlers>> {
475        Some(Cow::Borrowed(&self.event_handlers))
476    }
477
478    fn render(&self, context: RenderContext) {
479        let paragraph = self.sk_paragraph.0.borrow();
480        let ParagraphHolderInner { paragraph, .. } = paragraph
481            .as_ref()
482            .expect("Paragraph has not been measured yet");
483        let inner_area = context.layout_node.inner_area;
484
485        let cursor_area = match self.cursor_mode {
486            CursorMode::Fit => inner_area.cast_unit(),
487            CursorMode::Expanded => context.layout_node.area,
488        };
489
490        let paragraph_height = paragraph.height();
491        let area_height = inner_area.height();
492        let vertical_offset = match self.vertical_align {
493            VerticalAlign::Start => 0.0,
494            VerticalAlign::Center => (area_height - paragraph_height).max(0.0) / 2.0,
495        };
496
497        let cursor_vertical_offset = match self.cursor_mode {
498            CursorMode::Fit => vertical_offset,
499            CursorMode::Expanded => 0.0,
500        };
501        let cursor_vertical_size_offset = match self.cursor_mode {
502            CursorMode::Fit => 0.,
503            CursorMode::Expanded => vertical_offset * 2.,
504        };
505
506        let to_cursor_area = |rect: SkRect| {
507            SkRect::new(
508                cursor_area.min_x() + rect.left,
509                cursor_area.min_y() + rect.top + cursor_vertical_offset,
510                cursor_area.min_x() + rect.right,
511                cursor_area.min_y() + rect.bottom + cursor_vertical_size_offset,
512            )
513        };
514
515        // Draw highlights
516        for (from, to) in self.highlights.iter() {
517            if from == to {
518                continue;
519            }
520            let (from, to) = { if from < to { (from, to) } else { (to, from) } };
521            let rects = paragraph.get_rects_for_range(
522                *from..*to,
523                RectHeightStyle::Tight,
524                RectWidthStyle::Tight,
525            );
526
527            let mut highlights_paint = Paint::default();
528            highlights_paint.set_anti_alias(true);
529            highlights_paint.set_style(PaintStyle::Fill);
530            highlights_paint.set_color(self.cursor_style_data.highlight_color);
531
532            if rects.is_empty() && *from == 0 {
533                let caret_rect =
534                    paragraph.cursor_rect(&self.text(), *from, context.text_style_state.text_align);
535                context
536                    .canvas
537                    .draw_rect(to_cursor_area(caret_rect), &highlights_paint);
538            }
539
540            for rect in rects {
541                let mut rect = rect.rect;
542                rect.right = rect.right.max(6.);
543                context
544                    .canvas
545                    .draw_rect(to_cursor_area(rect), &highlights_paint);
546            }
547        }
548
549        let visible_highlights = self
550            .highlights
551            .iter()
552            .any(|highlight| highlight.0 != highlight.1);
553
554        let mut cursor_paint = Paint::default();
555        cursor_paint.set_anti_alias(true);
556        cursor_paint.set_style(PaintStyle::Fill);
557        cursor_paint.set_color(self.cursor_style_data.color);
558
559        // Draw block cursor
560        if let Some(cursor_index) = self.cursor_index
561            && self.cursor_style == CursorStyle::Block
562        {
563            let mut cursor_rect = paragraph.cursor_rect(
564                &self.text(),
565                cursor_index,
566                context.text_style_state.text_align,
567            );
568            let width = (cursor_rect.right - cursor_rect.left).max(6.0);
569            cursor_rect.right = cursor_rect.left + width;
570            context
571                .canvas
572                .draw_rect(to_cursor_area(cursor_rect), &cursor_paint);
573        }
574
575        // Draw text
576        let origin = Point2D::new(inner_area.min_x(), inner_area.min_y() + vertical_offset);
577        paragraph.paint_at(context.canvas, origin.cast_unit());
578
579        // Draw cursor
580        if let Some(cursor_index) = self.cursor_index
581            && !visible_highlights
582            && self.cursor_style != CursorStyle::Block
583        {
584            let mut cursor_rect = paragraph.cursor_rect(
585                &self.text(),
586                cursor_index,
587                context.text_style_state.text_align,
588            );
589            match self.cursor_style {
590                CursorStyle::Underline => cursor_rect.top = cursor_rect.bottom - 2.,
591                _ => cursor_rect.right = cursor_rect.left + 2.,
592            }
593            context
594                .canvas
595                .draw_rect(to_cursor_area(cursor_rect), &cursor_paint);
596        }
597    }
598}
599
600impl ParagraphElement {
601    fn has_inline_content(&self) -> bool {
602        self.contents
603            .iter()
604            .any(|content| matches!(content, ParagraphContent::Element))
605    }
606
607    /// The paragraph text as Skia indexes it, with inline children as placeholder characters.
608    fn text(&self) -> String {
609        let mut text = String::new();
610        let mut spans = self.spans.iter();
611        for content in &self.contents {
612            match content {
613                ParagraphContent::Span => {
614                    if let Some(span) = spans.next() {
615                        text.push_str(&span.text);
616                    }
617                }
618                ParagraphContent::Element => text.push('\u{FFFC}'),
619            }
620        }
621        text
622    }
623
624    fn has_shader_fill(&self, text_style_state: &TextStyleState) -> bool {
625        text_style_state.color.as_color().is_none()
626            || self.spans.iter().any(|span| {
627                span.text_style_data
628                    .color
629                    .as_ref()
630                    .is_some_and(|color| color.as_color().is_none())
631            })
632    }
633
634    /// Builds the Skia paragraph from the content.
635    fn build_paragraph(
636        &self,
637        text_style_state: &TextStyleState,
638        fallback_fonts: &[Cow<'static, str>],
639        scale_factor: f64,
640        font_collection: &FontCollection,
641        width: f32,
642        placeholders: &[Size2D],
643    ) -> SkParagraph {
644        let build = |fill_area: Area| {
645            let mut paragraph_style = ParagraphStyle::default();
646
647            if let Some(ellipsis) = text_style_state.text_overflow.get_ellipsis() {
648                paragraph_style.set_ellipsis(ellipsis);
649            }
650
651            paragraph_style.set_text_style(&text_style_state.to_text_style(
652                fallback_fonts,
653                scale_factor,
654                self.line_height,
655                fill_area,
656            ));
657            paragraph_style.set_max_lines(self.max_lines);
658            paragraph_style.set_text_align(text_style_state.text_align.into());
659
660            let mut paragraph_builder = ParagraphBuilder::new(&paragraph_style, font_collection);
661
662            let mut spans = self.spans.iter();
663            let mut placeholders = placeholders.iter();
664            for content in &self.contents {
665                match content {
666                    ParagraphContent::Span => {
667                        let Some(span) = spans.next() else { continue };
668                        paragraph_builder.push_style(&span.to_text_style(
669                            text_style_state,
670                            fallback_fonts,
671                            scale_factor,
672                            self.line_height,
673                            fill_area,
674                        ));
675                        paragraph_builder.add_text(&span.text);
676                    }
677                    ParagraphContent::Element => {
678                        let Some(size) = placeholders.next() else {
679                            continue;
680                        };
681                        paragraph_builder.add_placeholder(&PlaceholderStyle::new(
682                            size.width,
683                            size.height,
684                            PlaceholderAlignment::Middle,
685                            TextBaseline::Alphabetic,
686                            0.0,
687                        ));
688                    }
689                }
690            }
691
692            let mut paragraph = paragraph_builder.build();
693            paragraph.layout(width);
694            paragraph
695        };
696
697        let paragraph = build(Area::default());
698
699        // Paragraphs that contain even one shader must be
700        // rebuilt so that we can pass the correct area to the shaders
701        if self.has_shader_fill(text_style_state) {
702            return build(paragraph.fill_area());
703        }
704
705        paragraph
706    }
707}
708
709pub trait ParagraphCursorExt {
710    /// Area of the character at `cursor_index`, if there is any.
711    fn measured_cursor_rect(&self, text: &str, cursor_index: usize) -> Option<SkRect>;
712
713    /// Area of the character at `cursor_index`.
714    fn cursor_rect(&self, text: &str, cursor_index: usize, text_align: TextAlign) -> SkRect;
715
716    /// Cursor position at the given point.
717    fn cursor_index_at_point(&self, point: (f64, f64)) -> usize;
718}
719
720impl ParagraphCursorExt for SkParagraph {
721    fn measured_cursor_rect(&self, text: &str, cursor_index: usize) -> Option<SkRect> {
722        let mut cluster = 0..0;
723        let mut cluster_byte_index = 0;
724        for (byte_index, grapheme) in text.grapheme_indices(true) {
725            cluster = cluster.end..cluster.end + grapheme.encode_utf16().count();
726            cluster_byte_index = byte_index;
727            if cluster.end > cursor_index {
728                break;
729            }
730        }
731
732        if !cluster.is_empty() {
733            if cluster.end <= cursor_index
734                && let Some(cluster_line) = self.get_line_number_at(cluster_byte_index)
735                && let Some(line) = self.get_line_metrics_at(cluster_line + 1)
736            {
737                let left = line.left as f32;
738                let top = (line.baseline - line.ascent) as f32;
739                let bottom = (line.baseline + line.descent) as f32;
740                return Some(SkRect::new(left, top, left, bottom));
741            }
742
743            let rects = self.get_rects_for_range(
744                cluster.clone(),
745                RectHeightStyle::Tight,
746                RectWidthStyle::Tight,
747            );
748            if let Some(rect) = rects.first() {
749                let mut rect = rect.rect;
750                if cluster.end <= cursor_index {
751                    rect.left = rect.right;
752                }
753                return Some(rect);
754            }
755        }
756
757        let line = self.get_line_metrics_at(0)?;
758        let left = line.left as f32;
759
760        Some(SkRect::new(left, 0., left + 6., line.height as f32))
761    }
762
763    fn cursor_rect(&self, text: &str, cursor_index: usize, text_align: TextAlign) -> SkRect {
764        if let Some(rect) = self.measured_cursor_rect(text, cursor_index) {
765            return rect;
766        }
767
768        // In case of no rect we just center the cursor
769        let left = match text_align {
770            TextAlign::Center => self.max_width() / 2.,
771            TextAlign::Right | TextAlign::End => self.max_width() - 6.,
772            _ => 0.,
773        };
774
775        SkRect::new(left, 0., left + 6., self.height())
776    }
777
778    fn cursor_index_at_point(&self, point: (f64, f64)) -> usize {
779        let (horizontal_position, vertical_position) = point;
780        let mut horizontal_position = horizontal_position as i32;
781        if let Some(line) = self
782            .get_line_metrics()
783            .into_iter()
784            .find(|line| vertical_position < line.baseline + line.descent)
785            && !line.hard_break
786        {
787            // Clamp to the end of soft wrapped lines
788            horizontal_position = horizontal_position.min((line.left + line.width) as i32 - 1);
789        }
790
791        self.get_glyph_position_at_coordinate((horizontal_position, vertical_position as i32))
792            .position
793            .max(0) as usize
794    }
795}
796
797impl From<Paragraph> for Element {
798    fn from(value: Paragraph) -> Self {
799        let elements = value
800            .children
801            .into_iter()
802            .map(|child| {
803                rect()
804                    .position(Position::new_absolute())
805                    .child(child)
806                    .into_element()
807            })
808            .collect();
809
810        Element::Element {
811            key: value.key,
812            element: Rc::new(value.element),
813            elements,
814        }
815    }
816}
817
818impl TextStyleState {
819    /// Builds the Skia [TextStyle], anchoring non-color [Fill]s to `fill_area`.
820    pub(crate) fn to_text_style(
821        &self,
822        fallback_fonts: &[Cow<'static, str>],
823        scale_factor: f64,
824        line_height: Option<f32>,
825        fill_area: Area,
826    ) -> TextStyle {
827        let mut text_style = TextStyle::default();
828
829        let mut font_families = self.font_families.clone();
830        font_families.extend_from_slice(fallback_fonts);
831
832        self.color
833            .apply_to_text_style(&mut text_style, fill_area, self, scale_factor);
834        text_style.set_font_size(f32::from(self.font_size) * scale_factor as f32);
835        text_style.set_font_families(&font_families);
836        text_style.set_font_style(FontStyle::new(
837            self.font_weight.into(),
838            self.font_width.into(),
839            self.font_slant.into(),
840        ));
841        text_style.set_letter_spacing(f32::from(self.letter_spacing) * scale_factor as f32);
842        text_style.set_decoration_type(self.text_decoration.into());
843
844        for font_feature in self.font_features.iter() {
845            text_style.add_font_feature(&font_feature.name, font_feature.value);
846        }
847
848        if self.text_height.needs_custom_height() {
849            text_style.set_height_override(true);
850            text_style.set_half_leading(true);
851        }
852
853        if let Some(line_height) = line_height {
854            text_style.set_height_override(true);
855            text_style.set_height(line_height);
856        }
857
858        for text_shadow in self.text_shadows.iter() {
859            text_style.add_shadow((*text_shadow).into());
860        }
861
862        text_style
863    }
864}
865
866impl Span<'_> {
867    /// Builds the Skia [TextStyle] for this span.
868    fn to_text_style(
869        &self,
870        text_style_state: &TextStyleState,
871        fallback_fonts: &[Cow<'static, str>],
872        scale_factor: f64,
873        line_height: Option<f32>,
874        fill_area: Area,
875    ) -> TextStyle {
876        let span_style = TextStyleState::from_data(text_style_state, &self.text_style_data);
877        let mut text_style = TextStyle::new();
878
879        let mut font_families = span_style.font_families.clone();
880        font_families.extend_from_slice(fallback_fonts);
881
882        span_style
883            .color
884            .apply_to_text_style(&mut text_style, fill_area, &span_style, scale_factor);
885        text_style.set_font_size(f32::from(span_style.font_size) * scale_factor as f32);
886        text_style.set_font_families(&font_families);
887        text_style.set_font_style(FontStyle::new(
888            span_style.font_weight.into(),
889            span_style.font_width.into(),
890            span_style.font_slant.into(),
891        ));
892        text_style.set_decoration_type(span_style.text_decoration.into());
893        text_style.set_letter_spacing(f32::from(span_style.letter_spacing) * scale_factor as f32);
894
895        for font_feature in span_style.font_features.iter() {
896            text_style.add_font_feature(&font_feature.name, font_feature.value);
897        }
898
899        if let Some(line_height) = line_height {
900            text_style.set_height_override(true);
901            text_style.set_height(line_height);
902        }
903
904        for text_shadow in span_style.text_shadows.iter() {
905            text_style.add_shadow((*text_shadow).into());
906        }
907
908        text_style
909    }
910}
911
912pub(crate) trait ParagraphPaintExt {
913    /// Paints at `origin` by translating the canvas, so text shaders follow the paragraph.
914    fn paint_at(&self, canvas: &Canvas, origin: Point2D);
915
916    /// The box that non-color [Fill]s anchor to, in paragraph coordinates.
917    fn fill_area(&self) -> Area;
918}
919
920impl ParagraphPaintExt for SkParagraph {
921    fn paint_at(&self, canvas: &Canvas, origin: Point2D) {
922        let layer = canvas.save();
923        canvas.translate(origin.to_tuple());
924        self.paint(canvas, (0., 0.));
925        canvas.restore_to_count(layer);
926    }
927
928    fn fill_area(&self) -> Area {
929        let (left, right) = self
930            .get_line_metrics()
931            .into_iter()
932            .filter(|line| line.width > 0.0)
933            .map(|line| (line.left as f32, (line.left + line.width) as f32))
934            .reduce(|(left, right), (line_left, line_right)| {
935                (left.min(line_left), right.max(line_right))
936            })
937            .unwrap_or((0.0, self.longest_line()));
938
939        Area::new(
940            Point2D::new(left, 0.0),
941            Size2D::new(right - left, self.height()),
942        )
943    }
944}
945
946impl KeyExt for Paragraph {
947    fn key_mut(&mut self) -> &mut DiffKey {
948        &mut self.key
949    }
950}
951
952impl EventHandlersExt for Paragraph {
953    fn event_handlers_mut(&mut self) -> &mut EventHandlers {
954        &mut self.element.event_handlers
955    }
956}
957
958impl MaybeExt for Paragraph {}
959
960impl LayerExt for Paragraph {
961    fn layer_mut(&mut self) -> &mut Layer {
962        &mut self.element.relative_layer
963    }
964}
965
966#[derive(Default, Clone)]
967pub struct Paragraph {
968    key: DiffKey,
969    element: ParagraphElement,
970    children: Vec<Element>,
971}
972
973impl LayoutExt for Paragraph {
974    fn layout_mut(&mut self) -> &mut LayoutData {
975        &mut self.element.layout
976    }
977}
978
979impl ContainerExt for Paragraph {}
980
981/// Children added to a [Paragraph] flow inline at the point they were added, each laid out at
982/// its own measured size, so give them an explicit `width` and `height`.
983impl ChildrenExt for Paragraph {
984    fn children_mut(&mut self) -> &mut Vec<Element> {
985        &mut self.children
986    }
987
988    fn child<C: IntoElement>(mut self, child: C) -> Self {
989        self.element.contents.push(ParagraphContent::Element);
990        self.children.push(child.into_element());
991        self
992    }
993
994    fn children(self, children: impl IntoIterator<Item = impl IntoElement>) -> Self {
995        children
996            .into_iter()
997            .fold(self, |paragraph, child| paragraph.child(child))
998    }
999
1000    fn maybe_child<C: IntoElement>(self, child: Option<C>) -> Self {
1001        match child {
1002            Some(child) => self.child(child),
1003            None => self,
1004        }
1005    }
1006}
1007
1008impl AccessibilityExt for Paragraph {
1009    fn accessibility_data_mut(&mut self) -> &mut AccessibilityData {
1010        &mut self.element.accessibility
1011    }
1012}
1013
1014impl TextOverflowExt for Paragraph {}
1015
1016impl TextStyleExt for Paragraph {
1017    fn text_style_data_mut(&mut self) -> &mut TextStyleData {
1018        &mut self.element.text_style_data
1019    }
1020}
1021
1022impl EffectExt for Paragraph {
1023    fn effect_mut(&mut self) -> &mut EffectData {
1024        self.element.effect.get_or_insert_with(EffectData::default)
1025    }
1026}
1027
1028impl Paragraph {
1029    pub fn try_downcast(element: &dyn ElementExt) -> Option<ParagraphElement> {
1030        (element as &dyn Any)
1031            .downcast_ref::<ParagraphElement>()
1032            .cloned()
1033    }
1034
1035    /// Append every [`Span`] yielded by the iterator to the paragraph.
1036    pub fn spans_iter(mut self, spans: impl Iterator<Item = Span<'static>>) -> Self {
1037        for span in spans {
1038            self.push_span(span);
1039        }
1040        self
1041    }
1042
1043    /// Append a single [`Span`] of styled text to the paragraph.
1044    pub fn span(mut self, span: impl Into<Span<'static>>) -> Self {
1045        self.push_span(span.into());
1046        self
1047    }
1048
1049    fn push_span(&mut self, span: Span<'static>) {
1050        self.element.contents.push(ParagraphContent::Span);
1051        self.element.spans.push(span);
1052    }
1053
1054    /// Replace all of the paragraph's cursor style data at once. See [`CursorStyleData`].
1055    pub fn cursor_style_data(mut self, cursor_style_data: CursorStyleData) -> Self {
1056        self.element.cursor_style_data = cursor_style_data;
1057        self
1058    }
1059
1060    /// Set the color of the text cursor. See [`Color`].
1061    pub fn cursor_color(mut self, cursor_color: impl Into<Color>) -> Self {
1062        self.element.cursor_style_data.color = cursor_color.into();
1063        self
1064    }
1065
1066    /// Set the color used to highlight selected text. See [`Color`].
1067    pub fn highlight_color(mut self, highlight_color: impl Into<Color>) -> Self {
1068        self.element.cursor_style_data.highlight_color = highlight_color.into();
1069        self
1070    }
1071
1072    /// Set the shape of the text cursor. See [`CursorStyle`].
1073    pub fn cursor_style(mut self, cursor_style: impl Into<CursorStyle>) -> Self {
1074        self.element.cursor_style = cursor_style.into();
1075        self
1076    }
1077
1078    /// Attach a [`ParagraphHolder`] that receives the laid-out paragraph for hit-testing and measurement.
1079    pub fn holder(mut self, holder: ParagraphHolder) -> Self {
1080        self.element.sk_paragraph = holder;
1081        self
1082    }
1083
1084    /// Place the text cursor at the given character index. Pass `None` to hide it.
1085    pub fn cursor_index(mut self, cursor_index: impl Into<Option<usize>>) -> Self {
1086        self.element.cursor_index = cursor_index.into();
1087        self
1088    }
1089
1090    /// Highlight the given `(start, end)` character ranges, used for text selection.
1091    pub fn highlights(mut self, highlights: impl Into<Option<Vec<(usize, usize)>>>) -> Self {
1092        if let Some(highlights) = highlights.into() {
1093            self.element.highlights = highlights;
1094        }
1095        self
1096    }
1097
1098    /// Limit the paragraph to at most this many lines, truncating the rest. Pass `None` for no limit.
1099    pub fn max_lines(mut self, max_lines: impl Into<Option<usize>>) -> Self {
1100        self.element.max_lines = max_lines.into();
1101        self
1102    }
1103
1104    /// Override the height of each line as a multiple of the font size. Pass `None` for the default.
1105    pub fn line_height(mut self, line_height: impl Into<Option<f32>>) -> Self {
1106        self.element.line_height = line_height.into();
1107        self
1108    }
1109
1110    /// Set the cursor mode for the paragraph.
1111    /// - `CursorMode::Fit`: cursor/highlights use the paragraph's visible_area. VerticalAlign affects cursor positions.
1112    /// - `CursorMode::Expanded`: cursor/highlights use the paragraph's inner_area. VerticalAlign does NOT affect cursor positions.
1113    pub fn cursor_mode(mut self, cursor_mode: impl Into<CursorMode>) -> Self {
1114        self.element.cursor_mode = cursor_mode.into();
1115        self
1116    }
1117
1118    /// Set the vertical alignment for the paragraph text.
1119    /// This affects how the text is rendered within the paragraph area, but cursor/highlight behavior
1120    /// depends on the `cursor_mode` setting.
1121    pub fn vertical_align(mut self, vertical_align: impl Into<VerticalAlign>) -> Self {
1122        self.element.vertical_align = vertical_align.into();
1123        self
1124    }
1125}
1126
1127/// A run of text with its own style, used to build a [`paragraph()`].
1128///
1129/// Create it with [`Span::new`] (or from a `&str`/`String`) and style it with the
1130/// [`TextStyleExt`] methods such as [`font_size`](TextStyleExt::font_size) and
1131/// [`color`](TextStyleExt::color):
1132///
1133/// ```
1134/// # use freya_core::prelude::*;
1135/// let span = Span::new("Hello").font_size(24.0).color(Color::RED);
1136/// ```
1137#[derive(Clone, PartialEq, Hash)]
1138pub struct Span<'a> {
1139    pub text_style_data: TextStyleData,
1140    pub text: Cow<'a, str>,
1141}
1142
1143impl From<&'static str> for Span<'static> {
1144    fn from(text: &'static str) -> Self {
1145        Span {
1146            text_style_data: TextStyleData::default(),
1147            text: text.into(),
1148        }
1149    }
1150}
1151
1152impl From<String> for Span<'static> {
1153    fn from(text: String) -> Self {
1154        Span {
1155            text_style_data: TextStyleData::default(),
1156            text: text.into(),
1157        }
1158    }
1159}
1160
1161impl<'a> Span<'a> {
1162    /// Create a [`Span`] from the given text, with the default text style.
1163    pub fn new(text: impl Into<Cow<'a, str>>) -> Self {
1164        Self {
1165            text: text.into(),
1166            text_style_data: TextStyleData::default(),
1167        }
1168    }
1169}
1170
1171impl<'a> TextStyleExt for Span<'a> {
1172    fn text_style_data_mut(&mut self) -> &mut TextStyleData {
1173        &mut self.text_style_data
1174    }
1175}