1use 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
70pub 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);
292 text_style.set_height(line_height);
293 }
294
295 for text_shadow in context.text_style_state.text_shadows.iter() {
296 text_style.add_shadow((*text_shadow).into());
297 }
298
299 if let Some(ellipsis) = context.text_style_state.text_overflow.get_ellipsis() {
300 paragraph_style.set_ellipsis(ellipsis);
301 }
302
303 paragraph_style.set_text_style(&text_style);
304 paragraph_style.set_max_lines(self.max_lines);
305 paragraph_style.set_text_align(context.text_style_state.text_align.into());
306
307 let mut paragraph_builder =
308 ParagraphBuilder::new(¶graph_style, &*context.font_collection);
309
310 for span in &self.spans {
311 let text_style_state =
312 TextStyleState::from_data(context.text_style_state, &span.text_style_data);
313 let mut text_style = TextStyle::new();
314 let mut font_families = context.text_style_state.font_families.clone();
315 font_families.extend_from_slice(context.fallback_fonts);
316
317 for text_shadow in text_style_state.text_shadows.iter() {
318 text_style.add_shadow((*text_shadow).into());
319 }
320
321 text_style.set_color(text_style_state.color);
322 text_style.set_font_size(
323 f32::from(text_style_state.font_size) * context.scale_factor as f32,
324 );
325 text_style.set_font_families(&font_families);
326 text_style.set_font_style(FontStyle::new(
327 text_style_state.font_weight.into(),
328 text_style_state.font_width.into(),
329 text_style_state.font_slant.into(),
330 ));
331 text_style.set_decoration_type(text_style_state.text_decoration.into());
332 if let Some(line_height) = self.line_height {
333 text_style.set_height_override(true);
334 text_style.set_height(line_height);
335 }
336 paragraph_builder.push_style(&text_style);
337 paragraph_builder.add_text(&span.text);
338 }
339
340 let mut paragraph = paragraph_builder.build();
341 paragraph.layout(
342 if self.max_lines == Some(1)
343 && context.text_style_state.text_align == TextAlign::default()
344 && !paragraph_style.ellipsized()
345 {
346 f32::MAX
347 } else {
348 context.area_size.width + 1.0
349 },
350 );
351 context
352 .text_cache
353 .insert(context.node_id, &cached_paragraph, paragraph)
354 });
355
356 let size = Size2D::new(paragraph.longest_line(), paragraph.height());
357
358 self.sk_paragraph
359 .0
360 .borrow_mut()
361 .replace(ParagraphHolderInner {
362 paragraph,
363 scale_factor: context.scale_factor,
364 });
365
366 Some((size, Rc::new(())))
367 }
368
369 fn should_hook_measurement(&self) -> bool {
370 true
371 }
372
373 fn should_measure_inner_children(&self) -> bool {
374 false
375 }
376
377 fn events_handlers(&'_ self) -> Option<Cow<'_, FxHashMap<EventName, EventHandlerType>>> {
378 Some(Cow::Borrowed(&self.event_handlers))
379 }
380
381 fn render(&self, context: RenderContext) {
382 let paragraph = self.sk_paragraph.0.borrow();
383 let ParagraphHolderInner { paragraph, .. } = paragraph.as_ref().unwrap();
384 let visible_area = context.layout_node.visible_area();
385
386 let cursor_area = match self.cursor_mode {
387 CursorMode::Fit => visible_area,
388 CursorMode::Expanded => context.layout_node.area,
389 };
390
391 let paragraph_height = paragraph.height();
392 let area_height = visible_area.height();
393 let vertical_offset = match self.vertical_align {
394 VerticalAlign::Start => 0.0,
395 VerticalAlign::Center => (area_height - paragraph_height).max(0.0) / 2.0,
396 };
397
398 let cursor_vertical_offset = match self.cursor_mode {
399 CursorMode::Fit => vertical_offset,
400 CursorMode::Expanded => 0.0,
401 };
402 let cursor_vertical_size_offset = match self.cursor_mode {
403 CursorMode::Fit => 0.,
404 CursorMode::Expanded => vertical_offset * 2.,
405 };
406
407 for (from, to) in self.highlights.iter() {
409 if from == to {
410 continue;
411 }
412 let (from, to) = { if from < to { (from, to) } else { (to, from) } };
413 let rects = paragraph.get_rects_for_range(
414 *from..*to,
415 RectHeightStyle::Tight,
416 RectWidthStyle::Tight,
417 );
418
419 let mut highlights_paint = Paint::default();
420 highlights_paint.set_anti_alias(true);
421 highlights_paint.set_style(PaintStyle::Fill);
422 highlights_paint.set_color(self.cursor_style_data.highlight_color);
423
424 if rects.is_empty() && *from == 0 {
425 let avg_line_height =
426 paragraph.height() / paragraph.get_line_metrics().len().max(1) as f32;
427 let rect = SkRect::new(
428 cursor_area.min_x(),
429 cursor_area.min_y() + cursor_vertical_offset,
430 cursor_area.min_x() + 6.,
431 cursor_area.min_y() + avg_line_height + cursor_vertical_size_offset,
432 );
433
434 context.canvas.draw_rect(rect, &highlights_paint);
435 }
436
437 for rect in rects {
438 let rect = SkRect::new(
439 cursor_area.min_x() + rect.rect.left,
440 cursor_area.min_y() + rect.rect.top + cursor_vertical_offset,
441 cursor_area.min_x() + rect.rect.right.max(6.),
442 cursor_area.min_y() + rect.rect.bottom + cursor_vertical_size_offset,
443 );
444 context.canvas.draw_rect(rect, &highlights_paint);
445 }
446 }
447
448 let visible_highlights = self
450 .highlights
451 .iter()
452 .filter(|highlight| highlight.0 != highlight.1)
453 .count()
454 > 0;
455
456 if let Some(cursor_index) = self.cursor_index
458 && self.cursor_style == CursorStyle::Block
459 && let Some(cursor_rect) = paragraph
460 .get_rects_for_range(
461 cursor_index..cursor_index + 1,
462 RectHeightStyle::Tight,
463 RectWidthStyle::Tight,
464 )
465 .first()
466 .map(|text| text.rect)
467 .or_else(|| {
468 let text_len = paragraph
470 .get_glyph_position_at_coordinate((f32::MAX, f32::MAX))
471 .position as usize;
472 let last_rects = paragraph.get_rects_for_range(
473 text_len.saturating_sub(1)..text_len,
474 RectHeightStyle::Tight,
475 RectWidthStyle::Tight,
476 );
477
478 if let Some(last_rect) = last_rects.first() {
479 let mut caret = last_rect.rect;
480 caret.left = caret.right;
481 Some(caret)
482 } else {
483 let avg_line_height =
484 paragraph.height() / paragraph.get_line_metrics().len().max(1) as f32;
485 Some(SkRect::new(0., 0., 6., avg_line_height))
486 }
487 })
488 {
489 let width = (cursor_rect.right - cursor_rect.left).max(6.0);
490 let cursor_rect = SkRect::new(
491 cursor_area.min_x() + cursor_rect.left,
492 cursor_area.min_y() + cursor_rect.top + cursor_vertical_offset,
493 cursor_area.min_x() + cursor_rect.left + width,
494 cursor_area.min_y() + cursor_rect.bottom + cursor_vertical_size_offset,
495 );
496
497 let mut paint = Paint::default();
498 paint.set_anti_alias(true);
499 paint.set_style(PaintStyle::Fill);
500 paint.set_color(self.cursor_style_data.color);
501
502 context.canvas.draw_rect(cursor_rect, &paint);
503 }
504
505 paragraph.paint(
507 context.canvas,
508 (visible_area.min_x(), visible_area.min_y() + vertical_offset),
509 );
510
511 if let Some(cursor_index) = self.cursor_index
513 && !visible_highlights
514 {
515 let cursor_rects = paragraph.get_rects_for_range(
516 cursor_index..cursor_index + 1,
517 RectHeightStyle::Tight,
518 RectWidthStyle::Tight,
519 );
520 if let Some(cursor_rect) = cursor_rects.first().map(|text| text.rect).or_else(|| {
521 let text_len = paragraph
523 .get_glyph_position_at_coordinate((f32::MAX, f32::MAX))
524 .position as usize;
525 let last_rects = paragraph.get_rects_for_range(
526 text_len.saturating_sub(1)..text_len,
527 RectHeightStyle::Tight,
528 RectWidthStyle::Tight,
529 );
530
531 if let Some(last_rect) = last_rects.first() {
532 let mut caret = last_rect.rect;
533 caret.left = caret.right;
534 Some(caret)
535 } else {
536 None
537 }
538 }) {
539 let paint_color = self.cursor_style_data.color;
540 match self.cursor_style {
541 CursorStyle::Underline => {
542 let thickness = 2.0;
543 let underline_rect = SkRect::new(
544 cursor_area.min_x() + cursor_rect.left,
545 cursor_area.min_y() + cursor_rect.bottom - thickness
546 + cursor_vertical_offset,
547 cursor_area.min_x() + cursor_rect.right,
548 cursor_area.min_y() + cursor_rect.bottom + cursor_vertical_size_offset,
549 );
550
551 let mut paint = Paint::default();
552 paint.set_anti_alias(true);
553 paint.set_style(PaintStyle::Fill);
554 paint.set_color(paint_color);
555
556 context.canvas.draw_rect(underline_rect, &paint);
557 }
558 CursorStyle::Line => {
559 let cursor_rect = SkRect::new(
560 cursor_area.min_x() + cursor_rect.left,
561 cursor_area.min_y() + cursor_rect.top + cursor_vertical_offset,
562 cursor_area.min_x() + cursor_rect.left + 2.,
563 cursor_area.min_y() + cursor_rect.bottom + cursor_vertical_size_offset,
564 );
565
566 let mut paint = Paint::default();
567 paint.set_anti_alias(true);
568 paint.set_style(PaintStyle::Fill);
569 paint.set_color(paint_color);
570
571 context.canvas.draw_rect(cursor_rect, &paint);
572 }
573 _ => {}
574 }
575 }
576 }
577 }
578}
579
580impl From<Paragraph> for Element {
581 fn from(value: Paragraph) -> Self {
582 Element::Element {
583 key: value.key,
584 element: Rc::new(value.element),
585 elements: vec![],
586 }
587 }
588}
589
590impl KeyExt for Paragraph {
591 fn write_key(&mut self) -> &mut DiffKey {
592 &mut self.key
593 }
594}
595
596impl EventHandlersExt for Paragraph {
597 fn get_event_handlers(&mut self) -> &mut FxHashMap<EventName, EventHandlerType> {
598 &mut self.element.event_handlers
599 }
600}
601
602impl MaybeExt for Paragraph {}
603
604impl LayerExt for Paragraph {
605 fn get_layer(&mut self) -> &mut Layer {
606 &mut self.element.relative_layer
607 }
608}
609
610pub struct Paragraph {
611 key: DiffKey,
612 element: ParagraphElement,
613}
614
615impl LayoutExt for Paragraph {
616 fn get_layout(&mut self) -> &mut LayoutData {
617 &mut self.element.layout
618 }
619}
620
621impl ContainerExt for Paragraph {}
622
623impl AccessibilityExt for Paragraph {
624 fn get_accessibility_data(&mut self) -> &mut AccessibilityData {
625 &mut self.element.accessibility
626 }
627}
628
629impl TextStyleExt for Paragraph {
630 fn get_text_style_data(&mut self) -> &mut TextStyleData {
631 &mut self.element.text_style_data
632 }
633}
634
635impl Paragraph {
636 pub fn try_downcast(element: &dyn ElementExt) -> Option<ParagraphElement> {
637 (element as &dyn Any)
638 .downcast_ref::<ParagraphElement>()
639 .cloned()
640 }
641
642 pub fn spans_iter(mut self, spans: impl Iterator<Item = Span<'static>>) -> Self {
643 let spans = spans.collect::<Vec<Span>>();
644 self.element.spans.extend(spans);
647 self
648 }
649
650 pub fn span(mut self, span: impl Into<Span<'static>>) -> Self {
651 let span = span.into();
652 self.element.spans.push(span);
655 self
656 }
657
658 pub fn cursor_color(mut self, cursor_color: impl Into<Color>) -> Self {
659 self.element.cursor_style_data.color = cursor_color.into();
660 self
661 }
662
663 pub fn highlight_color(mut self, highlight_color: impl Into<Color>) -> Self {
664 self.element.cursor_style_data.highlight_color = highlight_color.into();
665 self
666 }
667
668 pub fn cursor_style(mut self, cursor_style: impl Into<CursorStyle>) -> Self {
669 self.element.cursor_style = cursor_style.into();
670 self
671 }
672
673 pub fn holder(mut self, holder: ParagraphHolder) -> Self {
674 self.element.sk_paragraph = holder;
675 self
676 }
677
678 pub fn cursor_index(mut self, cursor_index: impl Into<Option<usize>>) -> Self {
679 self.element.cursor_index = cursor_index.into();
680 self
681 }
682
683 pub fn highlights(mut self, highlights: impl Into<Option<Vec<(usize, usize)>>>) -> Self {
684 if let Some(highlights) = highlights.into() {
685 self.element.highlights = highlights;
686 }
687 self
688 }
689
690 pub fn max_lines(mut self, max_lines: impl Into<Option<usize>>) -> Self {
691 self.element.max_lines = max_lines.into();
692 self
693 }
694
695 pub fn line_height(mut self, line_height: impl Into<Option<f32>>) -> Self {
696 self.element.line_height = line_height.into();
697 self
698 }
699
700 pub fn cursor_mode(mut self, cursor_mode: impl Into<CursorMode>) -> Self {
704 self.element.cursor_mode = cursor_mode.into();
705 self
706 }
707
708 pub fn vertical_align(mut self, vertical_align: impl Into<VerticalAlign>) -> Self {
712 self.element.vertical_align = vertical_align.into();
713 self
714 }
715}
716
717#[derive(Clone, PartialEq, Hash)]
718pub struct Span<'a> {
719 pub text_style_data: TextStyleData,
720 pub text: Cow<'a, str>,
721}
722
723impl From<&'static str> for Span<'static> {
724 fn from(text: &'static str) -> Self {
725 Span {
726 text_style_data: TextStyleData::default(),
727 text: text.into(),
728 }
729 }
730}
731
732impl From<String> for Span<'static> {
733 fn from(text: String) -> Self {
734 Span {
735 text_style_data: TextStyleData::default(),
736 text: text.into(),
737 }
738 }
739}
740
741impl<'a> Span<'a> {
742 pub fn new(text: impl Into<Cow<'a, str>>) -> Self {
743 Self {
744 text: text.into(),
745 text_style_data: TextStyleData::default(),
746 }
747 }
748}
749
750impl<'a> TextStyleExt for Span<'a> {
751 fn get_text_style_data(&mut self) -> &mut TextStyleData {
752 &mut self.text_style_data
753 }
754}