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    FontStyle,
16    Paint,
17    PaintStyle,
18    ParagraphBuilder,
19    ParagraphStyle,
20    RectHeightStyle,
21    RectWidthStyle,
22    SkParagraph,
23    SkRect,
24    TextStyle,
25};
26use rustc_hash::FxHashMap;
27use torin::prelude::Size2D;
28
29use crate::{
30    data::{
31        AccessibilityData,
32        CursorStyleData,
33        EffectData,
34        LayoutData,
35        StyleState,
36        TextStyleData,
37        TextStyleState,
38    },
39    diff_key::DiffKey,
40    element::{
41        Element,
42        ElementExt,
43        EventHandlerType,
44        LayoutContext,
45        RenderContext,
46    },
47    events::name::EventName,
48    layers::Layer,
49    prelude::{
50        AccessibilityExt,
51        Color,
52        ContainerExt,
53        EventHandlersExt,
54        KeyExt,
55        LayerExt,
56        LayoutExt,
57        MaybeExt,
58        TextAlign,
59        TextStyleExt,
60        VerticalAlign,
61    },
62    style::cursor::{
63        CursorMode,
64        CursorStyle,
65    },
66    text_cache::CachedParagraph,
67    tree::DiffModifies,
68};
69
70/// [paragraph()] makes it possible to render rich text with different styles. Its a more customizable API than [crate::elements::label].
71///
72/// See the available methods in [Paragraph].
73///
74/// ```rust
75/// # use freya::prelude::*;
76/// fn app() -> impl IntoElement {
77///     paragraph()
78///         .span(Span::new("Hello").font_size(24.0))
79///         .span(Span::new("World").font_size(16.0))
80/// }
81/// ```
82pub fn paragraph() -> Paragraph {
83    Paragraph {
84        key: DiffKey::None,
85        element: ParagraphElement::default(),
86    }
87}
88
89pub struct ParagraphHolderInner {
90    pub paragraph: Rc<SkParagraph>,
91    pub scale_factor: f64,
92}
93
94#[derive(Clone)]
95pub struct ParagraphHolder(pub Rc<RefCell<Option<ParagraphHolderInner>>>);
96
97impl PartialEq for ParagraphHolder {
98    fn eq(&self, other: &Self) -> bool {
99        Rc::ptr_eq(&self.0, &other.0)
100    }
101}
102
103impl Debug for ParagraphHolder {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        f.write_str("ParagraphHolder")
106    }
107}
108
109impl Default for ParagraphHolder {
110    fn default() -> Self {
111        Self(Rc::new(RefCell::new(None)))
112    }
113}
114
115#[derive(PartialEq, Clone)]
116pub struct ParagraphElement {
117    pub layout: LayoutData,
118    pub spans: Vec<Span<'static>>,
119    pub accessibility: AccessibilityData,
120    pub text_style_data: TextStyleData,
121    pub cursor_style_data: CursorStyleData,
122    pub event_handlers: FxHashMap<EventName, EventHandlerType>,
123    pub sk_paragraph: ParagraphHolder,
124    pub cursor_index: Option<usize>,
125    pub highlights: Vec<(usize, usize)>,
126    pub max_lines: Option<usize>,
127    pub line_height: Option<f32>,
128    pub relative_layer: Layer,
129    pub cursor_style: CursorStyle,
130    pub cursor_mode: CursorMode,
131    pub vertical_align: VerticalAlign,
132}
133
134impl Default for ParagraphElement {
135    fn default() -> Self {
136        let mut accessibility = AccessibilityData::default();
137        accessibility.builder.set_role(accesskit::Role::Paragraph);
138        Self {
139            layout: Default::default(),
140            spans: Default::default(),
141            accessibility,
142            text_style_data: Default::default(),
143            cursor_style_data: Default::default(),
144            event_handlers: Default::default(),
145            sk_paragraph: Default::default(),
146            cursor_index: Default::default(),
147            highlights: Default::default(),
148            max_lines: Default::default(),
149            line_height: Default::default(),
150            relative_layer: Default::default(),
151            cursor_style: CursorStyle::default(),
152            cursor_mode: CursorMode::default(),
153            vertical_align: VerticalAlign::default(),
154        }
155    }
156}
157
158impl Display for ParagraphElement {
159    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        f.write_str(
161            &self
162                .spans
163                .iter()
164                .map(|s| s.text.clone())
165                .collect::<Vec<_>>()
166                .join("\n"),
167        )
168    }
169}
170
171impl ElementExt for ParagraphElement {
172    fn changed(&self, other: &Rc<dyn ElementExt>) -> bool {
173        let Some(paragraph) = (other.as_ref() as &dyn Any).downcast_ref::<ParagraphElement>()
174        else {
175            return false;
176        };
177        self != paragraph
178    }
179
180    fn diff(&self, other: &Rc<dyn ElementExt>) -> DiffModifies {
181        let Some(paragraph) = (other.as_ref() as &dyn Any).downcast_ref::<ParagraphElement>()
182        else {
183            return DiffModifies::all();
184        };
185
186        let mut diff = DiffModifies::empty();
187
188        if self.spans != paragraph.spans {
189            diff.insert(DiffModifies::STYLE);
190            diff.insert(DiffModifies::LAYOUT);
191        }
192
193        if self.accessibility != paragraph.accessibility {
194            diff.insert(DiffModifies::ACCESSIBILITY);
195        }
196
197        if self.relative_layer != paragraph.relative_layer {
198            diff.insert(DiffModifies::LAYER);
199        }
200
201        if self.text_style_data != paragraph.text_style_data {
202            diff.insert(DiffModifies::STYLE);
203        }
204
205        if self.event_handlers != paragraph.event_handlers {
206            diff.insert(DiffModifies::EVENT_HANDLERS);
207        }
208
209        if self.cursor_index != paragraph.cursor_index
210            || self.highlights != paragraph.highlights
211            || self.cursor_mode != paragraph.cursor_mode
212            || self.vertical_align != paragraph.vertical_align
213        {
214            diff.insert(DiffModifies::STYLE);
215        }
216
217        if self.text_style_data != paragraph.text_style_data
218            || self.line_height != paragraph.line_height
219            || self.max_lines != paragraph.max_lines
220        {
221            diff.insert(DiffModifies::TEXT_STYLE);
222            diff.insert(DiffModifies::LAYOUT);
223        }
224
225        if self.layout != paragraph.layout {
226            diff.insert(DiffModifies::STYLE);
227            diff.insert(DiffModifies::LAYOUT);
228        }
229
230        diff
231    }
232
233    fn layout(&'_ self) -> Cow<'_, LayoutData> {
234        Cow::Borrowed(&self.layout)
235    }
236    fn effect(&'_ self) -> Option<Cow<'_, EffectData>> {
237        None
238    }
239
240    fn style(&'_ self) -> Cow<'_, StyleState> {
241        Cow::Owned(StyleState::default())
242    }
243
244    fn text_style(&'_ self) -> Cow<'_, TextStyleData> {
245        Cow::Borrowed(&self.text_style_data)
246    }
247
248    fn accessibility(&'_ self) -> Cow<'_, AccessibilityData> {
249        Cow::Borrowed(&self.accessibility)
250    }
251
252    fn layer(&self) -> Layer {
253        self.relative_layer
254    }
255
256    fn measure(&self, context: LayoutContext) -> Option<(Size2D, Rc<dyn Any>)> {
257        let cached_paragraph = CachedParagraph {
258            text_style_state: context.text_style_state,
259            spans: &self.spans,
260            max_lines: self.max_lines,
261            line_height: self.line_height,
262            width: context.area_size.width,
263        };
264        let paragraph = context
265            .text_cache
266            .utilize(context.node_id, &cached_paragraph)
267            .unwrap_or_else(|| {
268                let mut paragraph_style = ParagraphStyle::default();
269                let mut text_style = TextStyle::default();
270
271                let mut font_families = context.text_style_state.font_families.clone();
272                font_families.extend_from_slice(context.fallback_fonts);
273
274                text_style.set_color(context.text_style_state.color);
275                text_style.set_font_size(
276                    f32::from(context.text_style_state.font_size) * context.scale_factor as f32,
277                );
278                text_style.set_font_families(&font_families);
279                text_style.set_font_style(FontStyle::new(
280                    context.text_style_state.font_weight.into(),
281                    context.text_style_state.font_width.into(),
282                    context.text_style_state.font_slant.into(),
283                ));
284
285                if context.text_style_state.text_height.needs_custom_height() {
286                    text_style.set_height_override(true);
287                    text_style.set_half_leading(true);
288                }
289
290                if let Some(line_height) = self.line_height {
291                    text_style.set_height_override(true).set_height(line_height);
292                }
293
294                for text_shadow in context.text_style_state.text_shadows.iter() {
295                    text_style.add_shadow((*text_shadow).into());
296                }
297
298                if let Some(ellipsis) = context.text_style_state.text_overflow.get_ellipsis() {
299                    paragraph_style.set_ellipsis(ellipsis);
300                }
301
302                paragraph_style.set_text_style(&text_style);
303                paragraph_style.set_max_lines(self.max_lines);
304                paragraph_style.set_text_align(context.text_style_state.text_align.into());
305
306                let mut paragraph_builder =
307                    ParagraphBuilder::new(&paragraph_style, &*context.font_collection);
308
309                for span in &self.spans {
310                    let text_style_state =
311                        TextStyleState::from_data(context.text_style_state, &span.text_style_data);
312                    let mut text_style = TextStyle::new();
313                    let mut font_families = context.text_style_state.font_families.clone();
314                    font_families.extend_from_slice(context.fallback_fonts);
315
316                    for text_shadow in text_style_state.text_shadows.iter() {
317                        text_style.add_shadow((*text_shadow).into());
318                    }
319
320                    text_style.set_color(text_style_state.color);
321                    text_style.set_font_size(
322                        f32::from(text_style_state.font_size) * context.scale_factor as f32,
323                    );
324                    text_style.set_font_families(&font_families);
325                    text_style.set_decoration_type(text_style_state.text_decoration.into());
326                    paragraph_builder.push_style(&text_style);
327                    paragraph_builder.add_text(&span.text);
328                }
329
330                let mut paragraph = paragraph_builder.build();
331                paragraph.layout(
332                    if self.max_lines == Some(1)
333                        && context.text_style_state.text_align == TextAlign::default()
334                        && !paragraph_style.ellipsized()
335                    {
336                        f32::MAX
337                    } else {
338                        context.area_size.width + 1.0
339                    },
340                );
341                context
342                    .text_cache
343                    .insert(context.node_id, &cached_paragraph, paragraph)
344            });
345
346        let size = Size2D::new(paragraph.longest_line(), paragraph.height());
347
348        self.sk_paragraph
349            .0
350            .borrow_mut()
351            .replace(ParagraphHolderInner {
352                paragraph,
353                scale_factor: context.scale_factor,
354            });
355
356        Some((size, Rc::new(())))
357    }
358
359    fn should_hook_measurement(&self) -> bool {
360        true
361    }
362
363    fn should_measure_inner_children(&self) -> bool {
364        false
365    }
366
367    fn events_handlers(&'_ self) -> Option<Cow<'_, FxHashMap<EventName, EventHandlerType>>> {
368        Some(Cow::Borrowed(&self.event_handlers))
369    }
370
371    fn render(&self, context: RenderContext) {
372        let paragraph = self.sk_paragraph.0.borrow();
373        let ParagraphHolderInner { paragraph, .. } = paragraph.as_ref().unwrap();
374        let visible_area = context.layout_node.visible_area();
375
376        let cursor_area = match self.cursor_mode {
377            CursorMode::Fit => visible_area,
378            CursorMode::Expanded => context.layout_node.area,
379        };
380
381        let paragraph_height = paragraph.height();
382        let area_height = visible_area.height();
383        let vertical_offset = match self.vertical_align {
384            VerticalAlign::Start => 0.0,
385            VerticalAlign::Center => (area_height - paragraph_height).max(0.0) / 2.0,
386        };
387
388        let cursor_vertical_offset = match self.cursor_mode {
389            CursorMode::Fit => vertical_offset,
390            CursorMode::Expanded => 0.0,
391        };
392        let cursor_vertical_size_offset = match self.cursor_mode {
393            CursorMode::Fit => 0.,
394            CursorMode::Expanded => vertical_offset * 2.,
395        };
396
397        // Draw highlights
398        for (from, to) in self.highlights.iter() {
399            if from == to {
400                continue;
401            }
402            let (from, to) = { if from < to { (from, to) } else { (to, from) } };
403            let rects = paragraph.get_rects_for_range(
404                *from..*to,
405                RectHeightStyle::Tight,
406                RectWidthStyle::Tight,
407            );
408
409            let mut highlights_paint = Paint::default();
410            highlights_paint.set_anti_alias(true);
411            highlights_paint.set_style(PaintStyle::Fill);
412            highlights_paint.set_color(self.cursor_style_data.highlight_color);
413
414            if rects.is_empty() && *from == 0 {
415                let avg_line_height =
416                    paragraph.height() / paragraph.get_line_metrics().len().max(1) as f32;
417                let rect = SkRect::new(
418                    cursor_area.min_x(),
419                    cursor_area.min_y() + cursor_vertical_offset,
420                    cursor_area.min_x() + 6.,
421                    cursor_area.min_y() + avg_line_height + cursor_vertical_size_offset,
422                );
423
424                context.canvas.draw_rect(rect, &highlights_paint);
425            }
426
427            for rect in rects {
428                let rect = SkRect::new(
429                    cursor_area.min_x() + rect.rect.left,
430                    cursor_area.min_y() + rect.rect.top + cursor_vertical_offset,
431                    cursor_area.min_x() + rect.rect.right.max(6.),
432                    cursor_area.min_y() + rect.rect.bottom + cursor_vertical_size_offset,
433                );
434                context.canvas.draw_rect(rect, &highlights_paint);
435            }
436        }
437
438        // We exclude those highlights that on the same start and end (e.g the user just started dragging)
439        let visible_highlights = self
440            .highlights
441            .iter()
442            .filter(|highlight| highlight.0 != highlight.1)
443            .count()
444            > 0;
445
446        // Draw block cursor behind text if needed
447        if let Some(cursor_index) = self.cursor_index
448            && self.cursor_style == CursorStyle::Block
449            && let Some(cursor_rect) = paragraph
450                .get_rects_for_range(
451                    cursor_index..cursor_index + 1,
452                    RectHeightStyle::Tight,
453                    RectWidthStyle::Tight,
454                )
455                .first()
456                .map(|text| text.rect)
457                .or_else(|| {
458                    // Show the cursor at the end of the text if possible
459                    let text_len = paragraph
460                        .get_glyph_position_at_coordinate((f32::MAX, f32::MAX))
461                        .position as usize;
462                    let last_rects = paragraph.get_rects_for_range(
463                        text_len.saturating_sub(1)..text_len,
464                        RectHeightStyle::Tight,
465                        RectWidthStyle::Tight,
466                    );
467
468                    if let Some(last_rect) = last_rects.first() {
469                        let mut caret = last_rect.rect;
470                        caret.left = caret.right;
471                        Some(caret)
472                    } else {
473                        let avg_line_height =
474                            paragraph.height() / paragraph.get_line_metrics().len().max(1) as f32;
475                        Some(SkRect::new(0., 0., 6., avg_line_height))
476                    }
477                })
478        {
479            let width = (cursor_rect.right - cursor_rect.left).max(6.0);
480            let cursor_rect = SkRect::new(
481                cursor_area.min_x() + cursor_rect.left,
482                cursor_area.min_y() + cursor_rect.top + cursor_vertical_offset,
483                cursor_area.min_x() + cursor_rect.left + width,
484                cursor_area.min_y() + cursor_rect.bottom + cursor_vertical_size_offset,
485            );
486
487            let mut paint = Paint::default();
488            paint.set_anti_alias(true);
489            paint.set_style(PaintStyle::Fill);
490            paint.set_color(self.cursor_style_data.color);
491
492            context.canvas.draw_rect(cursor_rect, &paint);
493        }
494
495        // Draw text (always uses visible_area with vertical_offset)
496        paragraph.paint(
497            context.canvas,
498            (visible_area.min_x(), visible_area.min_y() + vertical_offset),
499        );
500
501        // Draw cursor
502        if let Some(cursor_index) = self.cursor_index
503            && !visible_highlights
504        {
505            let cursor_rects = paragraph.get_rects_for_range(
506                cursor_index..cursor_index + 1,
507                RectHeightStyle::Tight,
508                RectWidthStyle::Tight,
509            );
510            if let Some(cursor_rect) = cursor_rects.first().map(|text| text.rect).or_else(|| {
511                // Show the cursor at the end of the text if possible
512                let text_len = paragraph
513                    .get_glyph_position_at_coordinate((f32::MAX, f32::MAX))
514                    .position as usize;
515                let last_rects = paragraph.get_rects_for_range(
516                    text_len.saturating_sub(1)..text_len,
517                    RectHeightStyle::Tight,
518                    RectWidthStyle::Tight,
519                );
520
521                if let Some(last_rect) = last_rects.first() {
522                    let mut caret = last_rect.rect;
523                    caret.left = caret.right;
524                    Some(caret)
525                } else {
526                    None
527                }
528            }) {
529                let paint_color = self.cursor_style_data.color;
530                match self.cursor_style {
531                    CursorStyle::Underline => {
532                        let thickness = 2.0;
533                        let underline_rect = SkRect::new(
534                            cursor_area.min_x() + cursor_rect.left,
535                            cursor_area.min_y() + cursor_rect.bottom - thickness
536                                + cursor_vertical_offset,
537                            cursor_area.min_x() + cursor_rect.right,
538                            cursor_area.min_y() + cursor_rect.bottom + cursor_vertical_size_offset,
539                        );
540
541                        let mut paint = Paint::default();
542                        paint.set_anti_alias(true);
543                        paint.set_style(PaintStyle::Fill);
544                        paint.set_color(paint_color);
545
546                        context.canvas.draw_rect(underline_rect, &paint);
547                    }
548                    CursorStyle::Line => {
549                        let cursor_rect = SkRect::new(
550                            cursor_area.min_x() + cursor_rect.left,
551                            cursor_area.min_y() + cursor_rect.top + cursor_vertical_offset,
552                            cursor_area.min_x() + cursor_rect.left + 2.,
553                            cursor_area.min_y() + cursor_rect.bottom + cursor_vertical_size_offset,
554                        );
555
556                        let mut paint = Paint::default();
557                        paint.set_anti_alias(true);
558                        paint.set_style(PaintStyle::Fill);
559                        paint.set_color(paint_color);
560
561                        context.canvas.draw_rect(cursor_rect, &paint);
562                    }
563                    _ => {}
564                }
565            }
566        }
567    }
568}
569
570impl From<Paragraph> for Element {
571    fn from(value: Paragraph) -> Self {
572        Element::Element {
573            key: value.key,
574            element: Rc::new(value.element),
575            elements: vec![],
576        }
577    }
578}
579
580impl KeyExt for Paragraph {
581    fn write_key(&mut self) -> &mut DiffKey {
582        &mut self.key
583    }
584}
585
586impl EventHandlersExt for Paragraph {
587    fn get_event_handlers(&mut self) -> &mut FxHashMap<EventName, EventHandlerType> {
588        &mut self.element.event_handlers
589    }
590}
591
592impl MaybeExt for Paragraph {}
593
594impl LayerExt for Paragraph {
595    fn get_layer(&mut self) -> &mut Layer {
596        &mut self.element.relative_layer
597    }
598}
599
600pub struct Paragraph {
601    key: DiffKey,
602    element: ParagraphElement,
603}
604
605impl LayoutExt for Paragraph {
606    fn get_layout(&mut self) -> &mut LayoutData {
607        &mut self.element.layout
608    }
609}
610
611impl ContainerExt for Paragraph {}
612
613impl AccessibilityExt for Paragraph {
614    fn get_accessibility_data(&mut self) -> &mut AccessibilityData {
615        &mut self.element.accessibility
616    }
617}
618
619impl TextStyleExt for Paragraph {
620    fn get_text_style_data(&mut self) -> &mut TextStyleData {
621        &mut self.element.text_style_data
622    }
623}
624
625impl Paragraph {
626    pub fn try_downcast(element: &dyn ElementExt) -> Option<ParagraphElement> {
627        (element as &dyn Any)
628            .downcast_ref::<ParagraphElement>()
629            .cloned()
630    }
631
632    pub fn spans_iter(mut self, spans: impl Iterator<Item = Span<'static>>) -> Self {
633        let spans = spans.collect::<Vec<Span>>();
634        // TODO: Accessible paragraphs
635        // self.element.accessibility.builder.set_value(text.clone());
636        self.element.spans.extend(spans);
637        self
638    }
639
640    pub fn span(mut self, span: impl Into<Span<'static>>) -> Self {
641        let span = span.into();
642        // TODO: Accessible paragraphs
643        // self.element.accessibility.builder.set_value(text.clone());
644        self.element.spans.push(span);
645        self
646    }
647
648    pub fn cursor_color(mut self, cursor_color: impl Into<Color>) -> Self {
649        self.element.cursor_style_data.color = cursor_color.into();
650        self
651    }
652
653    pub fn highlight_color(mut self, highlight_color: impl Into<Color>) -> Self {
654        self.element.cursor_style_data.highlight_color = highlight_color.into();
655        self
656    }
657
658    pub fn cursor_style(mut self, cursor_style: impl Into<CursorStyle>) -> Self {
659        self.element.cursor_style = cursor_style.into();
660        self
661    }
662
663    pub fn holder(mut self, holder: ParagraphHolder) -> Self {
664        self.element.sk_paragraph = holder;
665        self
666    }
667
668    pub fn cursor_index(mut self, cursor_index: impl Into<Option<usize>>) -> Self {
669        self.element.cursor_index = cursor_index.into();
670        self
671    }
672
673    pub fn highlights(mut self, highlights: impl Into<Option<Vec<(usize, usize)>>>) -> Self {
674        if let Some(highlights) = highlights.into() {
675            self.element.highlights = highlights;
676        }
677        self
678    }
679
680    pub fn max_lines(mut self, max_lines: impl Into<Option<usize>>) -> Self {
681        self.element.max_lines = max_lines.into();
682        self
683    }
684
685    pub fn line_height(mut self, line_height: impl Into<Option<f32>>) -> Self {
686        self.element.line_height = line_height.into();
687        self
688    }
689
690    /// Set the cursor mode for the paragraph.
691    /// - `CursorMode::Fit`: cursor/highlights use the paragraph's visible_area. VerticalAlign affects cursor positions.
692    /// - `CursorMode::Expanded`: cursor/highlights use the paragraph's inner_area. VerticalAlign does NOT affect cursor positions.
693    pub fn cursor_mode(mut self, cursor_mode: impl Into<CursorMode>) -> Self {
694        self.element.cursor_mode = cursor_mode.into();
695        self
696    }
697
698    /// Set the vertical alignment for the paragraph text.
699    /// This affects how the text is rendered within the paragraph area, but cursor/highlight behavior
700    /// depends on the `cursor_mode` setting.
701    pub fn vertical_align(mut self, vertical_align: impl Into<VerticalAlign>) -> Self {
702        self.element.vertical_align = vertical_align.into();
703        self
704    }
705}
706
707#[derive(Clone, PartialEq, Hash)]
708pub struct Span<'a> {
709    pub text_style_data: TextStyleData,
710    pub text: Cow<'a, str>,
711}
712
713impl From<&'static str> for Span<'static> {
714    fn from(text: &'static str) -> Self {
715        Span {
716            text_style_data: TextStyleData::default(),
717            text: text.into(),
718        }
719    }
720}
721
722impl From<String> for Span<'static> {
723    fn from(text: String) -> Self {
724        Span {
725            text_style_data: TextStyleData::default(),
726            text: text.into(),
727        }
728    }
729}
730
731impl<'a> Span<'a> {
732    pub fn new(text: impl Into<Cow<'a, str>>) -> Self {
733        Self {
734            text: text.into(),
735            text_style_data: TextStyleData::default(),
736        }
737    }
738}
739
740impl<'a> TextStyleExt for Span<'a> {
741    fn get_text_style_data(&mut self) -> &mut TextStyleData {
742        &mut self.text_style_data
743    }
744}