text.rs

  1use crate::{
  2    AnyElement, BorrowWindow, Bounds, Component, Element, ElementId, LayoutId, Pixels,
  3    SharedString, Size, TextRun, ViewContext, WrappedLine,
  4};
  5use parking_lot::{Mutex, MutexGuard};
  6use smallvec::SmallVec;
  7use std::{cell::Cell, rc::Rc, sync::Arc};
  8use util::ResultExt;
  9
 10pub struct Text {
 11    text: SharedString,
 12    runs: Option<Vec<TextRun>>,
 13}
 14
 15impl Text {
 16    /// Renders text with runs of different styles.
 17    ///
 18    /// Callers are responsible for setting the correct style for each run.
 19    /// For text with a uniform style, you can usually avoid calling this constructor
 20    /// and just pass text directly.
 21    pub fn styled(text: SharedString, runs: Vec<TextRun>) -> Self {
 22        Text {
 23            text,
 24            runs: Some(runs),
 25        }
 26    }
 27}
 28
 29impl<V: 'static> Component<V> for Text {
 30    fn render(self) -> AnyElement<V> {
 31        AnyElement::new(self)
 32    }
 33}
 34
 35impl<V: 'static> Element<V> for Text {
 36    type ElementState = TextState;
 37
 38    fn element_id(&self) -> Option<crate::ElementId> {
 39        None
 40    }
 41
 42    fn layout(
 43        &mut self,
 44        _view: &mut V,
 45        element_state: Option<Self::ElementState>,
 46        cx: &mut ViewContext<V>,
 47    ) -> (LayoutId, Self::ElementState) {
 48        let element_state = element_state.unwrap_or_default();
 49        let text_system = cx.text_system().clone();
 50        let text_style = cx.text_style();
 51        let font_size = text_style.font_size.to_pixels(cx.rem_size());
 52        let line_height = text_style
 53            .line_height
 54            .to_pixels(font_size.into(), cx.rem_size());
 55        let text = self.text.clone();
 56
 57        let rem_size = cx.rem_size();
 58
 59        let runs = if let Some(runs) = self.runs.take() {
 60            runs
 61        } else {
 62            vec![text_style.to_run(text.len())]
 63        };
 64
 65        let layout_id = cx.request_measured_layout(Default::default(), rem_size, {
 66            let element_state = element_state.clone();
 67            move |known_dimensions, available_space| {
 68                let wrap_width = known_dimensions.width.or(match available_space.width {
 69                    crate::AvailableSpace::Definite(x) => Some(x),
 70                    _ => None,
 71                });
 72
 73                let Some(lines) = text_system
 74                    .shape_text(
 75                        &text,
 76                        font_size,
 77                        &runs[..],
 78                        wrap_width, // Wrap if we know the width.
 79                    )
 80                    .log_err()
 81                else {
 82                    element_state.lock().replace(TextStateInner {
 83                        lines: Default::default(),
 84                        line_height,
 85                    });
 86                    return Size::default();
 87                };
 88
 89                let mut size: Size<Pixels> = Size::default();
 90                for line in &lines {
 91                    let line_size = line.size(line_height);
 92                    size.height += line_size.height;
 93                    size.width = size.width.max(line_size.width);
 94                }
 95
 96                element_state
 97                    .lock()
 98                    .replace(TextStateInner { lines, line_height });
 99
100                size
101            }
102        });
103
104        (layout_id, element_state)
105    }
106
107    fn paint(
108        &mut self,
109        bounds: Bounds<Pixels>,
110        _: &mut V,
111        element_state: &mut Self::ElementState,
112        cx: &mut ViewContext<V>,
113    ) {
114        let element_state = element_state.lock();
115        let element_state = element_state
116            .as_ref()
117            .ok_or_else(|| anyhow::anyhow!("measurement has not been performed on {}", &self.text))
118            .unwrap();
119
120        let line_height = element_state.line_height;
121        let mut line_origin = bounds.origin;
122        for line in &element_state.lines {
123            line.paint(line_origin, line_height, cx).log_err();
124            line_origin.y += line.size(line_height).height;
125        }
126    }
127}
128
129#[derive(Default, Clone)]
130pub struct TextState(Arc<Mutex<Option<TextStateInner>>>);
131
132impl TextState {
133    fn lock(&self) -> MutexGuard<Option<TextStateInner>> {
134        self.0.lock()
135    }
136}
137
138struct TextStateInner {
139    lines: SmallVec<[WrappedLine; 1]>,
140    line_height: Pixels,
141}
142
143struct InteractiveText {
144    id: ElementId,
145    text: Text,
146}
147
148struct InteractiveTextState {
149    text_state: TextState,
150    clicked_range_ixs: Rc<Cell<SmallVec<[usize; 1]>>>,
151}
152
153impl<V: 'static> Element<V> for InteractiveText {
154    type ElementState = InteractiveTextState;
155
156    fn element_id(&self) -> Option<ElementId> {
157        Some(self.id.clone())
158    }
159
160    fn layout(
161        &mut self,
162        view_state: &mut V,
163        element_state: Option<Self::ElementState>,
164        cx: &mut ViewContext<V>,
165    ) -> (LayoutId, Self::ElementState) {
166        if let Some(InteractiveTextState {
167            text_state,
168            clicked_range_ixs,
169        }) = element_state
170        {
171            let (layout_id, text_state) = self.text.layout(view_state, Some(text_state), cx);
172            let element_state = InteractiveTextState {
173                text_state,
174                clicked_range_ixs,
175            };
176            (layout_id, element_state)
177        } else {
178            let (layout_id, text_state) = self.text.layout(view_state, None, cx);
179            let element_state = InteractiveTextState {
180                text_state,
181                clicked_range_ixs: Rc::default(),
182            };
183            (layout_id, element_state)
184        }
185    }
186
187    fn paint(
188        &mut self,
189        bounds: Bounds<Pixels>,
190        view_state: &mut V,
191        element_state: &mut Self::ElementState,
192        cx: &mut ViewContext<V>,
193    ) {
194        self.text
195            .paint(bounds, view_state, &mut element_state.text_state, cx)
196    }
197}
198
199impl<V: 'static> Component<V> for SharedString {
200    fn render(self) -> AnyElement<V> {
201        Text {
202            text: self,
203            runs: None,
204        }
205        .render()
206    }
207}
208
209impl<V: 'static> Component<V> for &'static str {
210    fn render(self) -> AnyElement<V> {
211        Text {
212            text: self.into(),
213            runs: None,
214        }
215        .render()
216    }
217}
218
219// TODO: Figure out how to pass `String` to `child` without this.
220// This impl doesn't exist in the `gpui2` crate.
221impl<V: 'static> Component<V> for String {
222    fn render(self) -> AnyElement<V> {
223        Text {
224            text: self.into(),
225            runs: None,
226        }
227        .render()
228    }
229}