iced_graphics/text/
paragraph.rs

1//! Draw paragraphs.
2use crate::core;
3use crate::core::alignment;
4use crate::core::text::{Hit, Shaping, Span, Text, Wrapping};
5use crate::core::{Font, Point, Rectangle, Size};
6use crate::text;
7
8use std::fmt;
9use std::sync::{self, Arc};
10
11/// A bunch of text.
12#[derive(Clone, PartialEq)]
13pub struct Paragraph(Arc<Internal>);
14
15#[derive(Clone)]
16struct Internal {
17    buffer: cosmic_text::Buffer,
18    font: Font,
19    shaping: Shaping,
20    wrapping: Wrapping,
21    horizontal_alignment: alignment::Horizontal,
22    vertical_alignment: alignment::Vertical,
23    bounds: Size,
24    min_bounds: Size,
25    version: text::Version,
26}
27
28impl Paragraph {
29    /// Creates a new empty [`Paragraph`].
30    pub fn new() -> Self {
31        Self::default()
32    }
33
34    /// Returns the buffer of the [`Paragraph`].
35    pub fn buffer(&self) -> &cosmic_text::Buffer {
36        &self.internal().buffer
37    }
38
39    /// Creates a [`Weak`] reference to the [`Paragraph`].
40    ///
41    /// This is useful to avoid cloning the [`Paragraph`] when
42    /// referential guarantees are unnecessary. For instance,
43    /// when creating a rendering tree.
44    pub fn downgrade(&self) -> Weak {
45        let paragraph = self.internal();
46
47        Weak {
48            raw: Arc::downgrade(paragraph),
49            min_bounds: paragraph.min_bounds,
50            horizontal_alignment: paragraph.horizontal_alignment,
51            vertical_alignment: paragraph.vertical_alignment,
52        }
53    }
54
55    fn internal(&self) -> &Arc<Internal> {
56        &self.0
57    }
58}
59
60impl core::text::Paragraph for Paragraph {
61    type Font = Font;
62
63    fn with_text(text: Text<&str>) -> Self {
64        log::trace!("Allocating plain paragraph: {}", text.content);
65
66        let mut font_system =
67            text::font_system().write().expect("Write font system");
68
69        let mut buffer = cosmic_text::Buffer::new(
70            font_system.raw(),
71            cosmic_text::Metrics::new(
72                text.size.into(),
73                text.line_height.to_absolute(text.size).into(),
74            ),
75        );
76
77        buffer.set_size(
78            font_system.raw(),
79            Some(text.bounds.width),
80            Some(text.bounds.height),
81        );
82
83        buffer.set_wrap(font_system.raw(), text::to_wrap(text.wrapping));
84
85        buffer.set_text(
86            font_system.raw(),
87            text.content,
88            &text::to_attributes(text.font),
89            text::to_shaping(text.shaping),
90            None,
91        );
92
93        let min_bounds = text::measure(&buffer);
94
95        Self(Arc::new(Internal {
96            buffer,
97            font: text.font,
98            horizontal_alignment: text.horizontal_alignment,
99            vertical_alignment: text.vertical_alignment,
100            shaping: text.shaping,
101            wrapping: text.wrapping,
102            bounds: text.bounds,
103            min_bounds,
104            version: font_system.version(),
105        }))
106    }
107
108    fn with_spans<Link>(text: Text<&[Span<'_, Link>]>) -> Self {
109        log::trace!("Allocating rich paragraph: {} spans", text.content.len());
110
111        let mut font_system =
112            text::font_system().write().expect("Write font system");
113
114        let mut buffer = cosmic_text::Buffer::new(
115            font_system.raw(),
116            cosmic_text::Metrics::new(
117                text.size.into(),
118                text.line_height.to_absolute(text.size).into(),
119            ),
120        );
121
122        buffer.set_size(
123            font_system.raw(),
124            Some(text.bounds.width),
125            Some(text.bounds.height),
126        );
127
128        buffer.set_rich_text(
129            font_system.raw(),
130            text.content.iter().enumerate().map(|(i, span)| {
131                let attrs = text::to_attributes(span.font.unwrap_or(text.font));
132
133                let attrs = match (span.size, span.line_height) {
134                    (None, None) => attrs,
135                    _ => {
136                        let size = span.size.unwrap_or(text.size);
137
138                        attrs.metrics(cosmic_text::Metrics::new(
139                            size.into(),
140                            span.line_height
141                                .unwrap_or(text.line_height)
142                                .to_absolute(size)
143                                .into(),
144                        ))
145                    }
146                };
147
148                let attrs = if let Some(color) = span.color {
149                    attrs.color(text::to_color(color))
150                } else {
151                    attrs
152                };
153
154                (span.text.as_ref(), attrs.metadata(i))
155            }),
156            &text::to_attributes(text.font),
157            text::to_shaping(text.shaping),
158            Some(match text.horizontal_alignment {
159                alignment::Horizontal::Left => cosmic_text::Align::Left,
160                alignment::Horizontal::Center => cosmic_text::Align::Center,
161                alignment::Horizontal::Right => cosmic_text::Align::Right,
162            }),
163        );
164
165        let min_bounds = text::measure(&buffer);
166
167        Self(Arc::new(Internal {
168            buffer,
169            font: text.font,
170            horizontal_alignment: text.horizontal_alignment,
171            vertical_alignment: text.vertical_alignment,
172            shaping: text.shaping,
173            wrapping: text.wrapping,
174            bounds: text.bounds,
175            min_bounds,
176            version: font_system.version(),
177        }))
178    }
179
180    fn resize(&mut self, new_bounds: Size) {
181        let paragraph = Arc::make_mut(&mut self.0);
182
183        let mut font_system =
184            text::font_system().write().expect("Write font system");
185
186        paragraph.buffer.set_size(
187            font_system.raw(),
188            Some(new_bounds.width),
189            Some(new_bounds.height),
190        );
191
192        paragraph.bounds = new_bounds;
193        paragraph.min_bounds = text::measure(&paragraph.buffer);
194    }
195
196    fn compare(&self, text: Text<()>) -> core::text::Difference {
197        let font_system = text::font_system().read().expect("Read font system");
198        let paragraph = self.internal();
199        let metrics = paragraph.buffer.metrics();
200
201        if paragraph.version != font_system.version
202            || metrics.font_size != text.size.0
203            || metrics.line_height != text.line_height.to_absolute(text.size).0
204            || paragraph.font != text.font
205            || paragraph.shaping != text.shaping
206            || paragraph.wrapping != text.wrapping
207            || paragraph.horizontal_alignment != text.horizontal_alignment
208            || paragraph.vertical_alignment != text.vertical_alignment
209        {
210            core::text::Difference::Shape
211        } else if paragraph.bounds != text.bounds {
212            core::text::Difference::Bounds
213        } else {
214            core::text::Difference::None
215        }
216    }
217
218    fn horizontal_alignment(&self) -> alignment::Horizontal {
219        self.internal().horizontal_alignment
220    }
221
222    fn vertical_alignment(&self) -> alignment::Vertical {
223        self.internal().vertical_alignment
224    }
225
226    fn min_bounds(&self) -> Size {
227        self.internal().min_bounds
228    }
229
230    fn hit_test(&self, point: Point) -> Option<Hit> {
231        let cursor = self.internal().buffer.hit(point.x, point.y)?;
232
233        Some(Hit::CharOffset(cursor.index))
234    }
235
236    fn hit_span(&self, point: Point) -> Option<usize> {
237        let internal = self.internal();
238
239        let cursor = internal.buffer.hit(point.x, point.y)?;
240        let line = internal.buffer.lines.get(cursor.line)?;
241
242        let mut last_glyph = None;
243        let mut glyphs = line
244            .layout_opt()
245            .as_ref()?
246            .iter()
247            .flat_map(|line| line.glyphs.iter())
248            .peekable();
249
250        while let Some(glyph) = glyphs.peek() {
251            if glyph.start <= cursor.index && cursor.index < glyph.end {
252                break;
253            }
254
255            last_glyph = glyphs.next();
256        }
257
258        let glyph = match cursor.affinity {
259            cosmic_text::Affinity::Before => last_glyph,
260            cosmic_text::Affinity::After => glyphs.next(),
261        }?;
262
263        Some(glyph.metadata)
264    }
265
266    fn span_bounds(&self, index: usize) -> Vec<Rectangle> {
267        let internal = self.internal();
268
269        let mut bounds = Vec::new();
270        let mut current_bounds = None;
271
272        let glyphs = internal
273            .buffer
274            .layout_runs()
275            .flat_map(|run| {
276                let line_top = run.line_top;
277                let line_height = run.line_height;
278
279                run.glyphs
280                    .iter()
281                    .map(move |glyph| (line_top, line_height, glyph))
282            })
283            .skip_while(|(_, _, glyph)| glyph.metadata != index)
284            .take_while(|(_, _, glyph)| glyph.metadata == index);
285
286        for (line_top, line_height, glyph) in glyphs {
287            let y = line_top + glyph.y;
288
289            let new_bounds = || {
290                Rectangle::new(
291                    Point::new(glyph.x, y),
292                    Size::new(
293                        glyph.w,
294                        glyph.line_height_opt.unwrap_or(line_height),
295                    ),
296                )
297            };
298
299            match current_bounds.as_mut() {
300                None => {
301                    current_bounds = Some(new_bounds());
302                }
303                Some(current_bounds) if y != current_bounds.y => {
304                    bounds.push(*current_bounds);
305                    *current_bounds = new_bounds();
306                }
307                Some(current_bounds) => {
308                    current_bounds.width += glyph.w;
309                }
310            }
311        }
312
313        bounds.extend(current_bounds);
314        bounds
315    }
316
317    fn grapheme_position(&self, line: usize, index: usize) -> Option<Point> {
318        use unicode_segmentation::UnicodeSegmentation;
319
320        let run = self.internal().buffer.layout_runs().nth(line)?;
321
322        // index represents a grapheme, not a glyph
323        // Let's find the first glyph for the given grapheme cluster
324        let mut last_start = None;
325        let mut last_grapheme_count = 0;
326        let mut graphemes_seen = 0;
327
328        let glyph = run
329            .glyphs
330            .iter()
331            .find(|glyph| {
332                if Some(glyph.start) != last_start {
333                    last_grapheme_count = run.text[glyph.start..glyph.end]
334                        .graphemes(false)
335                        .count();
336                    last_start = Some(glyph.start);
337                    graphemes_seen += last_grapheme_count;
338                }
339
340                graphemes_seen >= index
341            })
342            .or_else(|| run.glyphs.last())?;
343
344        let advance = if index == 0 {
345            0.0
346        } else {
347            glyph.w
348                * (1.0
349                    - graphemes_seen.saturating_sub(index) as f32
350                        / last_grapheme_count.max(1) as f32)
351        };
352
353        Some(Point::new(
354            glyph.x + glyph.x_offset * glyph.font_size + advance,
355            glyph.y - glyph.y_offset * glyph.font_size,
356        ))
357    }
358}
359
360impl Default for Paragraph {
361    fn default() -> Self {
362        Self(Arc::new(Internal::default()))
363    }
364}
365
366impl fmt::Debug for Paragraph {
367    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
368        let paragraph = self.internal();
369
370        f.debug_struct("Paragraph")
371            .field("font", &paragraph.font)
372            .field("shaping", &paragraph.shaping)
373            .field("horizontal_alignment", &paragraph.horizontal_alignment)
374            .field("vertical_alignment", &paragraph.vertical_alignment)
375            .field("bounds", &paragraph.bounds)
376            .field("min_bounds", &paragraph.min_bounds)
377            .finish()
378    }
379}
380
381impl PartialEq for Internal {
382    fn eq(&self, other: &Self) -> bool {
383        self.font == other.font
384            && self.shaping == other.shaping
385            && self.horizontal_alignment == other.horizontal_alignment
386            && self.vertical_alignment == other.vertical_alignment
387            && self.bounds == other.bounds
388            && self.min_bounds == other.min_bounds
389            && self.buffer.metrics() == other.buffer.metrics()
390    }
391}
392
393impl Default for Internal {
394    fn default() -> Self {
395        Self {
396            buffer: cosmic_text::Buffer::new_empty(cosmic_text::Metrics {
397                font_size: 1.0,
398                line_height: 1.0,
399            }),
400            font: Font::default(),
401            shaping: Shaping::default(),
402            wrapping: Wrapping::default(),
403            horizontal_alignment: alignment::Horizontal::Left,
404            vertical_alignment: alignment::Vertical::Top,
405            bounds: Size::ZERO,
406            min_bounds: Size::ZERO,
407            version: text::Version::default(),
408        }
409    }
410}
411
412/// A weak reference to a [`Paragraph`].
413#[derive(Debug, Clone)]
414pub struct Weak {
415    raw: sync::Weak<Internal>,
416    /// The minimum bounds of the [`Paragraph`].
417    pub min_bounds: Size,
418    /// The horizontal alignment of the [`Paragraph`].
419    pub horizontal_alignment: alignment::Horizontal,
420    /// The vertical alignment of the [`Paragraph`].
421    pub vertical_alignment: alignment::Vertical,
422}
423
424impl Weak {
425    /// Tries to update the reference into a [`Paragraph`].
426    pub fn upgrade(&self) -> Option<Paragraph> {
427        self.raw.upgrade().map(Paragraph)
428    }
429}
430
431impl PartialEq for Weak {
432    fn eq(&self, other: &Self) -> bool {
433        match (self.raw.upgrade(), other.raw.upgrade()) {
434            (Some(p1), Some(p2)) => p1 == p2,
435            _ => false,
436        }
437    }
438}