1use crate::{
2 AnyElement, Element, IntoAnyElement, Layout, LayoutId, Line, Pixels, Result, Size, ViewContext,
3};
4use parking_lot::Mutex;
5use std::{marker::PhantomData, sync::Arc};
6use util::arc_cow::ArcCow;
7
8impl<S: 'static> IntoAnyElement<S> for ArcCow<'static, str> {
9 fn into_any(self) -> AnyElement<S> {
10 Text {
11 text: self,
12 state_type: PhantomData,
13 }
14 .into_any()
15 }
16}
17
18impl<V: 'static> IntoAnyElement<V> for &'static str {
19 fn into_any(self) -> AnyElement<V> {
20 Text {
21 text: ArcCow::from(self),
22 state_type: PhantomData,
23 }
24 .into_any()
25 }
26}
27
28pub struct Text<S> {
29 text: ArcCow<'static, str>,
30 state_type: PhantomData<S>,
31}
32
33impl<S: 'static> Element for Text<S> {
34 type State = S;
35 type FrameState = Arc<Mutex<Option<TextLayout>>>;
36
37 fn layout(
38 &mut self,
39 _view: &mut S,
40 cx: &mut ViewContext<S>,
41 ) -> Result<(LayoutId, Self::FrameState)> {
42 let text_system = cx.text_system().clone();
43 let text_style = cx.text_style();
44 let font_size = text_style.font_size * cx.rem_size();
45 let line_height = text_style
46 .line_height
47 .to_pixels(font_size.into(), cx.rem_size());
48 let text = self.text.clone();
49 let paint_state = Arc::new(Mutex::new(None));
50
51 let rem_size = cx.rem_size();
52 let layout_id = cx.request_measured_layout(Default::default(), rem_size, {
53 let frame_state = paint_state.clone();
54 move |_, _| {
55 let line_layout = text_system.layout_str(
56 text.as_ref(),
57 font_size,
58 &[(text.len(), text_style.to_run())],
59 );
60
61 let size = Size {
62 width: line_layout.width(),
63 height: line_height,
64 };
65
66 frame_state.lock().replace(TextLayout {
67 line: Arc::new(line_layout),
68 line_height,
69 });
70
71 size
72 }
73 });
74
75 Ok((layout_id?, paint_state))
76 }
77
78 fn paint<'a>(
79 &mut self,
80 layout: Layout,
81 _: &mut Self::State,
82 paint_state: &mut Self::FrameState,
83 cx: &mut ViewContext<S>,
84 ) -> Result<()> {
85 let bounds = layout.bounds;
86
87 let line;
88 let line_height;
89 {
90 let paint_state = paint_state.lock();
91 let paint_state = paint_state
92 .as_ref()
93 .expect("measurement has not been performed");
94 line = paint_state.line.clone();
95 line_height = paint_state.line_height;
96 }
97
98 let _text_style = cx.text_style();
99
100 // todo!("We haven't added visible bounds to the new element system yet, so this is a placeholder.");
101 let visible_bounds = bounds;
102 line.paint(bounds.origin, visible_bounds, line_height, cx)?;
103
104 Ok(())
105 }
106}
107
108pub struct TextLayout {
109 line: Arc<Line>,
110 line_height: Pixels,
111}