1use crate::core;
3use crate::core::alignment;
4use crate::core::text::{
5 Alignment, Ellipsis, Hit, LineHeight, Shaping, Span, Target, Text, Wrapping,
6};
7use crate::core::{Font, Pixels, Point, Rectangle, Size};
8use crate::text;
9
10use std::fmt;
11use std::sync::{self, Arc};
12
13#[derive(Clone, PartialEq)]
15pub struct Paragraph(Arc<Internal>);
16
17#[derive(Clone)]
18struct Internal {
19 buffer: cosmic_text::Buffer,
20 font: Font,
21 shaping: Shaping,
22 wrapping: Wrapping,
23 ellipsis: Ellipsis,
24 align_x: Alignment,
25 align_y: alignment::Vertical,
26 bounds: Size,
27 min_bounds: Size,
28 version: text::Version,
29 hint: bool,
30 hint_factor: f32,
31 selection: Option<Selection>,
32 last_click: Option<Point>,
33}
34
35#[derive(Clone)]
36struct Selection {
37 start: cosmic_text::Cursor,
38 end: cosmic_text::Cursor,
39 regions: Vec<Rectangle>,
40}
41
42impl Paragraph {
43 pub fn new() -> Self {
45 Self::default()
46 }
47
48 pub fn buffer(&self) -> &cosmic_text::Buffer {
50 &self.internal().buffer
51 }
52
53 pub fn downgrade(&self) -> Weak {
59 let paragraph = self.internal();
60
61 Weak {
62 raw: Arc::downgrade(paragraph),
63 min_bounds: paragraph.min_bounds,
64 align_x: paragraph.align_x,
65 align_y: paragraph.align_y,
66 }
67 }
68
69 fn internal(&self) -> &Arc<Internal> {
70 &self.0
71 }
72}
73
74impl core::text::Paragraph for Paragraph {
75 fn with_text(text: Text<&str>) -> Self {
76 log::trace!("Allocating plain paragraph: {}", text.content);
77
78 let mut font_system = text::font_system().write().expect("Write font system");
79
80 let (hint, hint_factor) = match text::hint_factor(text.size, text.hint_factor) {
81 Some(hint_factor) => (true, hint_factor),
82 _ => (false, 1.0),
83 };
84
85 let mut buffer = cosmic_text::Buffer::new(
86 font_system.raw(),
87 cosmic_text::Metrics::new(
88 f32::from(text.size) * hint_factor,
89 f32::from(text.line_height.to_absolute(text.size)) * hint_factor,
90 ),
91 );
92
93 if hint {
94 buffer.set_hinting(cosmic_text::Hinting::Enabled);
95 }
96
97 buffer.set_size(
98 Some(text.bounds.width * hint_factor),
99 Some(text.bounds.height * hint_factor),
100 );
101
102 buffer.set_wrap(text::to_wrap(text.wrapping));
103 buffer.set_ellipsize(text::to_ellipsize(
104 text.ellipsis,
105 text.bounds.height * hint_factor,
106 ));
107
108 buffer.set_text(
109 text.content,
110 &text::to_attributes(text.font),
111 text::to_shaping(text.shaping, text.content),
112 None,
113 );
114 buffer.shape_until_scroll(font_system.raw(), false);
115
116 let min_bounds = text::align(&mut buffer, font_system.raw(), text.align_x) / hint_factor;
117
118 Self(Arc::new(Internal {
119 buffer,
120 hint,
121 hint_factor,
122 font: text.font,
123 align_x: text.align_x,
124 align_y: text.align_y,
125 shaping: text.shaping,
126 wrapping: text.wrapping,
127 ellipsis: text.ellipsis,
128 bounds: text.bounds,
129 min_bounds,
130 version: font_system.version(),
131 selection: None,
132 last_click: None,
133 }))
134 }
135
136 fn with_spans<Link>(text: Text<&[Span<'_, Link>]>) -> Self {
137 log::trace!("Allocating rich paragraph: {} spans", text.content.len());
138
139 let mut font_system = text::font_system().write().expect("Write font system");
140
141 let (hint, hint_factor) = match text::hint_factor(text.size, text.hint_factor) {
142 Some(hint_factor) => (true, hint_factor),
143 _ => (false, 1.0),
144 };
145
146 let mut buffer = cosmic_text::Buffer::new(
147 font_system.raw(),
148 cosmic_text::Metrics::new(
149 f32::from(text.size) * hint_factor,
150 f32::from(text.line_height.to_absolute(text.size)) * hint_factor,
151 ),
152 );
153
154 if hint {
155 buffer.set_hinting(cosmic_text::Hinting::Enabled);
156 }
157
158 buffer.set_size(
159 Some(text.bounds.width * hint_factor),
160 Some(text.bounds.height * hint_factor),
161 );
162
163 buffer.set_wrap(text::to_wrap(text.wrapping));
164
165 buffer.set_rich_text(
166 text.content.iter().enumerate().map(|(i, span)| {
167 let attrs = text::to_attributes(span.font.unwrap_or(text.font));
168
169 let attrs = match (span.size, span.line_height) {
170 (None, None) => attrs,
171 _ => {
172 let size = span.size.unwrap_or(text.size);
173
174 attrs.metrics(cosmic_text::Metrics::new(
175 f32::from(size) * hint_factor,
176 f32::from(
177 span.line_height
178 .unwrap_or(text.line_height)
179 .to_absolute(size),
180 ) * hint_factor,
181 ))
182 }
183 };
184
185 let attrs = if let Some(color) = span.color {
186 attrs.color(text::to_color(color))
187 } else {
188 attrs
189 };
190
191 let attrs = attrs.padding(cosmic_text::SpanPadding {
192 start: span.padding.left,
193 end: span.padding.right,
194 });
195
196 (span.text.as_ref(), attrs.metadata(i))
197 }),
198 &text::to_attributes(text.font),
199 cosmic_text::Shaping::Advanced,
200 None,
201 );
202
203 buffer.shape_until_scroll(font_system.raw(), false);
204
205 let min_bounds = text::align(&mut buffer, font_system.raw(), text.align_x) / hint_factor;
206
207 Self(Arc::new(Internal {
208 buffer,
209 hint,
210 hint_factor,
211 font: text.font,
212 align_x: text.align_x,
213 align_y: text.align_y,
214 shaping: text.shaping,
215 wrapping: text.wrapping,
216 ellipsis: text.ellipsis,
217 bounds: text.bounds,
218 min_bounds,
219 version: font_system.version(),
220 selection: None,
221 last_click: None,
222 }))
223 }
224
225 fn resize(&mut self, new_bounds: Size) {
226 let paragraph = Arc::make_mut(&mut self.0);
227
228 let mut font_system = text::font_system().write().expect("Write font system");
229
230 paragraph.buffer.set_size(
231 Some(new_bounds.width * paragraph.hint_factor),
232 Some(new_bounds.height * paragraph.hint_factor),
233 );
234 paragraph
235 .buffer
236 .shape_until_scroll(font_system.raw(), false);
237
238 let min_bounds = text::align(&mut paragraph.buffer, font_system.raw(), paragraph.align_x)
239 / paragraph.hint_factor;
240
241 paragraph.bounds = new_bounds;
242 paragraph.min_bounds = min_bounds;
243
244 if let Some(Selection { start, end, .. }) = paragraph.selection {
245 paragraph.selection = Some(Selection {
246 start,
247 end,
248 regions: text::regions(¶graph.buffer, start, end),
249 });
250 }
251 }
252
253 fn compare(&self, text: Text<()>) -> core::text::Difference {
254 let font_system = text::font_system().read().expect("Read font system");
255 let paragraph = self.internal();
256 let metrics = paragraph.buffer.metrics();
257
258 if paragraph.version != font_system.version
259 || metrics.font_size != text.size.0 * paragraph.hint_factor
260 || metrics.line_height
261 != text.line_height.to_absolute(text.size).0 * paragraph.hint_factor
262 || paragraph.font != text.font
263 || paragraph.shaping != text.shaping
264 || paragraph.wrapping != text.wrapping
265 || paragraph.ellipsis != text.ellipsis
266 || paragraph.align_x != text.align_x
267 || paragraph.align_y != text.align_y
268 || paragraph.hint.then_some(paragraph.hint_factor)
269 != text::hint_factor(text.size, text.hint_factor)
270 {
271 core::text::Difference::Shape
272 } else if paragraph.bounds != text.bounds {
273 core::text::Difference::Bounds
274 } else {
275 core::text::Difference::None
276 }
277 }
278
279 fn hint_factor(&self) -> Option<f32> {
280 self.0.hint.then_some(self.0.hint_factor)
281 }
282
283 fn size(&self) -> Pixels {
284 Pixels(self.0.buffer.metrics().font_size / self.0.hint_factor)
285 }
286
287 fn font(&self) -> Font {
288 self.0.font
289 }
290
291 fn line_height(&self) -> LineHeight {
292 LineHeight::Absolute(Pixels(
293 self.0.buffer.metrics().line_height / self.0.hint_factor,
294 ))
295 }
296
297 fn align_x(&self) -> Alignment {
298 self.internal().align_x
299 }
300
301 fn align_y(&self) -> alignment::Vertical {
302 self.internal().align_y
303 }
304
305 fn wrapping(&self) -> Wrapping {
306 self.0.wrapping
307 }
308
309 fn ellipsis(&self) -> Ellipsis {
310 self.0.ellipsis
311 }
312
313 fn shaping(&self) -> Shaping {
314 self.0.shaping
315 }
316
317 fn bounds(&self) -> Size {
318 self.0.bounds
319 }
320
321 fn min_bounds(&self) -> Size {
322 self.internal().min_bounds
323 }
324
325 fn hit_test(&self, point: Point) -> Option<Hit> {
326 let cursor = self
327 .internal()
328 .buffer
329 .hit(point.x * self.0.hint_factor, point.y * self.0.hint_factor)?;
330
331 Some(Hit {
332 line: cursor.line,
333 index: cursor.index,
334 })
335 }
336
337 fn hit_glyph(&self, point: Point) -> bool {
338 self.internal().buffer.layout_runs().any(|run| {
339 let line_top = run.line_top;
340 let line_height = run.line_height;
341
342 if line_top > point.y || line_top + line_height < point.y {
343 return false;
344 }
345
346 run.glyphs
347 .iter()
348 .any(|glyph| glyph.x <= point.x && glyph.x + glyph.w >= point.x)
349 })
350 }
351
352 fn hit_span(&self, point: Point) -> Option<usize> {
353 let internal = self.internal();
354
355 let cursor = internal
356 .buffer
357 .hit(point.x * self.0.hint_factor, point.y * self.0.hint_factor)?;
358 let line = internal.buffer.lines.get(cursor.line)?;
359
360 if cursor.index >= line.text().len() {
361 return None;
362 }
363
364 let index = match cursor.affinity {
365 cosmic_text::Affinity::Before => cursor.index.saturating_sub(1),
366 cosmic_text::Affinity::After => cursor.index,
367 };
368
369 let mut hit = None;
370 let glyphs = line
371 .layout_opt()
372 .as_ref()?
373 .iter()
374 .flat_map(|line| line.glyphs.iter());
375
376 for glyph in glyphs {
377 if glyph.start <= index && index < glyph.end {
378 hit = Some(glyph);
379 break;
380 }
381 }
382
383 Some(hit?.metadata)
384 }
385
386 fn span_bounds(&self, index: usize) -> Vec<Rectangle> {
387 let internal = self.internal();
388
389 let scale = 1.0 / internal.hint_factor;
390
391 let mut bounds = Vec::new();
392 let mut current = None;
393 let mut current_baseline = 0.0;
394
395 let mut y = 0.0;
396 let buffer_height = internal.buffer.metrics().line_height;
397 let glyphs = internal
398 .buffer
399 .lines
400 .iter()
401 .filter_map(|paragraph| paragraph.layout_opt().map(Vec::as_slice))
402 .flat_map(|lines| lines.iter())
403 .flat_map(move |line| {
404 let line_height = line.line_height(buffer_height);
405 let ink_height = line.max_ascent + line.max_descent;
406
407 let baseline = y + (line_height - ink_height) / 2.0 + line.max_ascent;
411
412 let glyphs = line.glyphs.iter().map(move |glyph| (baseline, glyph));
413
414 y += line_height;
415
416 glyphs
417 })
418 .skip_while(|(_, glyph)| glyph.metadata != index)
419 .take_while(|(_, glyph)| glyph.metadata == index);
420
421 for (baseline, glyph) in glyphs {
422 let anchor = baseline + glyph.y - glyph.font_size * glyph.y_offset;
425 let ink_top = anchor - glyph.ascender;
426 let ink_bottom = anchor + glyph.descender;
427
428 match current.as_mut() {
429 None => {
430 current_baseline = baseline;
431 current = Some(
432 Rectangle::new(
433 Point::new(glyph.x, ink_top),
434 Size::new(glyph.w, ink_bottom - ink_top),
435 ) * scale,
436 );
437 }
438 Some(current) if baseline != current_baseline => {
439 bounds.push(*current);
440 current_baseline = baseline;
441 *current = Rectangle::new(
442 Point::new(glyph.x, ink_top),
443 Size::new(glyph.w, ink_bottom - ink_top),
444 ) * scale;
445 }
446 Some(current) => {
447 let left = current.x.min(glyph.x * scale);
450 let top = current.y.min(ink_top * scale);
451 let right = (current.x + current.width).max((glyph.x + glyph.w) * scale);
452 let bottom = (current.y + current.height).max(ink_bottom * scale);
453 *current = Rectangle::new(
454 Point::new(left, top),
455 Size::new(right - left, bottom - top),
456 );
457 }
458 }
459 }
460
461 bounds.extend(current);
462 bounds
463 }
464
465 fn select(&mut self, start: Point, end: Point, target: Target) {
466 use cosmic_text::Edit;
467
468 let paragraph = Arc::make_mut(&mut self.0);
469 let mut font_system = text::font_system().write().expect("write font system");
470
471 let mut editor =
473 cosmic_text::Editor::new(cosmic_text::BufferRef::Borrowed(&mut paragraph.buffer));
474
475 if start == end {
476 paragraph.last_click = Some(start);
477 }
478
479 let start = paragraph.last_click.unwrap_or(start);
480
481 editor.action(&mut font_system.raw, {
482 let x = start.x as i32;
483 let y = start.y as i32;
484
485 match target {
486 Target::Character => cosmic_text::Action::Click { x, y },
487 Target::Word => cosmic_text::Action::DoubleClick { x, y },
488 Target::Line => cosmic_text::Action::TripleClick { x, y },
489 }
490 });
491
492 editor.action(
493 &mut font_system.raw,
494 cosmic_text::Action::Drag {
495 x: end.x as i32,
496 y: end.y as i32,
497 },
498 );
499
500 let Some((start, end)) = editor.selection_bounds() else {
501 paragraph.selection = None;
502 return;
503 };
504
505 let cursor = editor.cursor();
506
507 let selection = match editor.selection() {
508 cosmic_text::Selection::None => cursor,
509 cosmic_text::Selection::Normal(selection)
510 | cosmic_text::Selection::Line(selection)
511 | cosmic_text::Selection::Word(selection) => selection,
512 };
513
514 if cursor == selection
517 && ((cursor.line == 0 && cursor.index == 0)
518 || (cursor.line + 1 == paragraph.buffer.lines.len()
519 && cursor.index == paragraph.buffer.lines[cursor.line].text().len()))
520 {
521 paragraph.selection = None;
522 return;
523 }
524
525 paragraph.selection = Some(Selection {
526 start,
527 end,
528 regions: text::regions(¶graph.buffer, start, end),
529 });
530 }
531
532 fn select_all(&mut self) {
533 let paragraph = Arc::make_mut(&mut self.0);
534
535 let start = cosmic_text::Cursor {
536 line: 0,
537 index: 0,
538 affinity: cosmic_text::Affinity::Before,
539 };
540
541 let end = cosmic_text::Cursor {
542 line: paragraph.buffer.lines.len().saturating_sub(1),
543 index: paragraph
544 .buffer
545 .lines
546 .last()
547 .map(|line| line.text().floor_char_boundary(line.text().len()))
548 .unwrap_or_default(),
549 affinity: cosmic_text::Affinity::After,
550 };
551
552 paragraph.selection = Some(Selection {
553 start,
554 end,
555 regions: text::regions(¶graph.buffer, start, end),
556 });
557 }
558
559 fn deselect(&mut self) {
560 let paragraph = Arc::make_mut(&mut self.0);
561 paragraph.selection = None;
562 }
563
564 fn selection(&self) -> &[Rectangle] {
565 self.internal()
566 .selection
567 .as_ref()
568 .map(|selection| selection.regions.as_slice())
569 .unwrap_or_default()
570 }
571
572 fn copy(&mut self) -> Option<String> {
573 use cosmic_text::Edit;
574
575 let paragraph = Arc::make_mut(&mut self.0);
576 let selection = paragraph.selection.as_ref()?;
577
578 let mut editor =
579 cosmic_text::Editor::new(cosmic_text::BufferRef::Borrowed(&mut paragraph.buffer));
580
581 editor.set_selection(cosmic_text::Selection::Normal(selection.start));
582 editor.set_cursor(selection.end);
583 editor.copy_selection()
584 }
585}
586
587impl Default for Paragraph {
588 fn default() -> Self {
589 Self(Arc::new(Internal::default()))
590 }
591}
592
593impl fmt::Debug for Paragraph {
594 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
595 let paragraph = self.internal();
596
597 f.debug_struct("Paragraph")
598 .field("font", ¶graph.font)
599 .field("shaping", ¶graph.shaping)
600 .field("horizontal_alignment", ¶graph.align_x)
601 .field("vertical_alignment", ¶graph.align_y)
602 .field("bounds", ¶graph.bounds)
603 .field("min_bounds", ¶graph.min_bounds)
604 .finish()
605 }
606}
607
608impl PartialEq for Internal {
609 fn eq(&self, other: &Self) -> bool {
610 self.font == other.font
611 && self.shaping == other.shaping
612 && self.align_x == other.align_x
613 && self.align_y == other.align_y
614 && self.bounds == other.bounds
615 && self.min_bounds == other.min_bounds
616 && self.buffer.metrics() == other.buffer.metrics()
617 }
618}
619
620impl Default for Internal {
621 fn default() -> Self {
622 Self {
623 buffer: cosmic_text::Buffer::new_empty(cosmic_text::Metrics {
624 font_size: 1.0,
625 line_height: 1.0,
626 }),
627 font: Font::default(),
628 shaping: Shaping::default(),
629 wrapping: Wrapping::default(),
630 ellipsis: Ellipsis::default(),
631 align_x: Alignment::Default,
632 align_y: alignment::Vertical::Top,
633 bounds: Size::ZERO,
634 min_bounds: Size::ZERO,
635 version: text::Version::default(),
636 hint: false,
637 hint_factor: 1.0,
638 selection: None,
639 last_click: None,
640 }
641 }
642}
643
644#[derive(Debug, Clone)]
646pub struct Weak {
647 raw: sync::Weak<Internal>,
648 pub min_bounds: Size,
650 pub align_x: Alignment,
652 pub align_y: alignment::Vertical,
654}
655
656impl Weak {
657 pub fn upgrade(&self) -> Option<Paragraph> {
659 self.raw.upgrade().map(Paragraph)
660 }
661}
662
663impl PartialEq for Weak {
664 fn eq(&self, other: &Self) -> bool {
665 match (self.raw.upgrade(), other.raw.upgrade()) {
666 (Some(p1), Some(p2)) => p1 == p2,
667 _ => false,
668 }
669 }
670}
671
672#[cfg(test)]
673mod tests {
674 use super::*;
675 use crate::core::text::Paragraph as _;
676
677 fn rich_paragraph(content: &[Span<'_, ()>]) -> Paragraph {
678 let text = Text {
679 content,
680 bounds: Size::new(1000.0, f32::INFINITY),
681 size: Pixels(20.0),
682 line_height: LineHeight::Relative(1.5),
683 font: Font::default(),
684 align_x: Alignment::Default,
685 align_y: alignment::Vertical::Top,
686 shaping: Shaping::default(),
687 wrapping: Wrapping::default(),
688 ellipsis: Ellipsis::default(),
689 hint_factor: None,
690 };
691
692 Paragraph::with_spans(text)
693 }
694
695 #[test]
698 fn span_bounds_cover_ink() {
699 let paragraph = rich_paragraph(&[Span::new("a"), Span::new("a").size(40.0)]);
700
701 let small = paragraph.span_bounds(0);
702 let big = paragraph.span_bounds(1);
703
704 assert_eq!(small.len(), 1);
705 assert_eq!(big.len(), 1);
706
707 let buffer = paragraph.buffer();
708 let line = &buffer.lines[0].layout_opt().unwrap()[0];
709 let line_height = line.line_height(buffer.metrics().line_height);
710 let ink_height = line.max_ascent + line.max_descent;
711 let centering = (line_height - ink_height) / 2.0;
712
713 assert!((big[0].y - centering).abs() < 1e-2);
715 assert!((big[0].height - ink_height).abs() < 1e-2);
716
717 let baseline = centering + line.max_ascent;
719 assert!((small[0].y + line.max_ascent / 2.0 - baseline).abs() < 1e-2);
720 assert!((big[0].y + line.max_ascent - baseline).abs() < 1e-2);
721
722 assert!(small[0].y > centering);
724 assert!(small[0].y + small[0].height < centering + ink_height);
725 assert!((small[0].height - ink_height / 2.0).abs() < 1e-2);
726
727 if ink_height < line_height {
729 assert!(big[0].height < line_height);
730 }
731 }
732
733 #[test]
735 fn span_bounds_cover_width() {
736 let paragraph = rich_paragraph(&[Span::new("Hello"), Span::new(", world!")]);
737
738 let first = paragraph.span_bounds(0);
739 let second = paragraph.span_bounds(1);
740
741 assert_eq!(first.len(), 1);
742 assert_eq!(second.len(), 1);
743
744 let buffer = paragraph.buffer();
745 let line = &buffer.lines[0].layout_opt().unwrap()[0];
746
747 assert!((first[0].x - 0.0).abs() < 1e-2);
750 assert!(first[0].width > 0.0);
751 assert!(first[0].width < line.w);
752
753 assert!((second[0].x - (first[0].x + first[0].width)).abs() < 1e-2);
756 assert!((second[0].x + second[0].width - line.w).abs() < 1e-2);
757 }
758
759 #[test]
761 fn span_bounds_cover_each_line() {
762 let paragraph = rich_paragraph(&[Span::new("ab\ncd")]);
763
764 let bounds = paragraph.span_bounds(0);
765
766 assert_eq!(bounds.len(), 2);
767
768 let buffer = paragraph.buffer();
769 let line_height = buffer.metrics().line_height;
770
771 for bounds in &bounds {
772 assert!((bounds.x - 0.0).abs() < 1e-2);
773 assert!(bounds.height > 0.0);
774 assert!(bounds.height < line_height);
775 }
776
777 assert!(bounds[0].y + bounds[0].height <= bounds[1].y + 1e-2);
780 assert!((bounds[0].height - bounds[1].height).abs() < 1e-2);
781 }
782}