label.rs

  1use std::{borrow::Cow, ops::Range};
  2
  3use crate::{
  4    fonts::TextStyle,
  5    geometry::{
  6        rect::RectF,
  7        vector::{vec2f, Vector2F},
  8    },
  9    json::{ToJson, Value},
 10    presenter::MeasurementContext,
 11    text_layout::{Line, RunStyle},
 12    DebugContext, Element, LayoutContext, PaintContext, SizeConstraint,
 13};
 14use serde::Deserialize;
 15use serde_json::json;
 16use smallvec::{smallvec, SmallVec};
 17
 18pub struct Label {
 19    text: Cow<'static, str>,
 20    style: LabelStyle,
 21    highlight_indices: Vec<usize>,
 22}
 23
 24#[derive(Clone, Debug, Deserialize, Default)]
 25pub struct LabelStyle {
 26    pub text: TextStyle,
 27    pub highlight_text: Option<TextStyle>,
 28}
 29
 30impl From<TextStyle> for LabelStyle {
 31    fn from(text: TextStyle) -> Self {
 32        LabelStyle {
 33            text,
 34            highlight_text: None,
 35        }
 36    }
 37}
 38
 39impl LabelStyle {
 40    pub fn with_font_size(mut self, font_size: f32) -> Self {
 41        self.text.font_size = font_size;
 42        self
 43    }
 44}
 45
 46impl Label {
 47    pub fn new<I: Into<Cow<'static, str>>>(text: I, style: impl Into<LabelStyle>) -> Self {
 48        Self {
 49            text: text.into(),
 50            highlight_indices: Default::default(),
 51            style: style.into(),
 52        }
 53    }
 54
 55    pub fn with_highlights(mut self, indices: Vec<usize>) -> Self {
 56        self.highlight_indices = indices;
 57        self
 58    }
 59
 60    fn compute_runs(&self) -> SmallVec<[(usize, RunStyle); 8]> {
 61        let font_id = self.style.text.font_id;
 62        if self.highlight_indices.is_empty() {
 63            return smallvec![(
 64                self.text.len(),
 65                RunStyle {
 66                    font_id,
 67                    color: self.style.text.color,
 68                    underline: self.style.text.underline,
 69                }
 70            )];
 71        }
 72
 73        let highlight_font_id = self
 74            .style
 75            .highlight_text
 76            .as_ref()
 77            .map_or(font_id, |style| style.font_id);
 78
 79        let mut highlight_indices = self.highlight_indices.iter().copied().peekable();
 80        let mut runs = SmallVec::new();
 81        let highlight_style = self
 82            .style
 83            .highlight_text
 84            .as_ref()
 85            .unwrap_or(&self.style.text);
 86
 87        for (char_ix, c) in self.text.char_indices() {
 88            let mut font_id = font_id;
 89            let mut color = self.style.text.color;
 90            let mut underline = self.style.text.underline;
 91            if let Some(highlight_ix) = highlight_indices.peek() {
 92                if char_ix == *highlight_ix {
 93                    font_id = highlight_font_id;
 94                    color = highlight_style.color;
 95                    underline = highlight_style.underline;
 96                    highlight_indices.next();
 97                }
 98            }
 99
100            let last_run: Option<&mut (usize, RunStyle)> = runs.last_mut();
101            let push_new_run = if let Some((last_len, last_style)) = last_run {
102                if font_id == last_style.font_id
103                    && color == last_style.color
104                    && underline == last_style.underline
105                {
106                    *last_len += c.len_utf8();
107                    false
108                } else {
109                    true
110                }
111            } else {
112                true
113            };
114
115            if push_new_run {
116                runs.push((
117                    c.len_utf8(),
118                    RunStyle {
119                        font_id,
120                        color,
121                        underline,
122                    },
123                ));
124            }
125        }
126
127        runs
128    }
129}
130
131impl Element for Label {
132    type LayoutState = Line;
133    type PaintState = ();
134
135    fn layout(
136        &mut self,
137        constraint: SizeConstraint,
138        cx: &mut LayoutContext,
139    ) -> (Vector2F, Self::LayoutState) {
140        let runs = self.compute_runs();
141        let line =
142            cx.text_layout_cache
143                .layout_str(&self.text, self.style.text.font_size, runs.as_slice());
144
145        let size = vec2f(
146            line.width()
147                .ceil()
148                .max(constraint.min.x())
149                .min(constraint.max.x()),
150            cx.font_cache.line_height(self.style.text.font_size),
151        );
152
153        (size, line)
154    }
155
156    fn paint(
157        &mut self,
158        bounds: RectF,
159        visible_bounds: RectF,
160        line: &mut Self::LayoutState,
161        cx: &mut PaintContext,
162    ) -> Self::PaintState {
163        line.paint(bounds.origin(), visible_bounds, bounds.size().y(), cx)
164    }
165
166    fn rect_for_text_range(
167        &self,
168        _: Range<usize>,
169        _: RectF,
170        _: RectF,
171        _: &Self::LayoutState,
172        _: &Self::PaintState,
173        _: &MeasurementContext,
174    ) -> Option<RectF> {
175        None
176    }
177
178    fn debug(
179        &self,
180        bounds: RectF,
181        _: &Self::LayoutState,
182        _: &Self::PaintState,
183        _: &DebugContext,
184    ) -> Value {
185        json!({
186            "type": "Label",
187            "bounds": bounds.to_json(),
188            "text": &self.text,
189            "highlight_indices": self.highlight_indices,
190            "style": self.style.to_json(),
191        })
192    }
193}
194
195impl ToJson for LabelStyle {
196    fn to_json(&self) -> Value {
197        json!({
198            "text": self.text.to_json(),
199            "highlight_text": self.highlight_text
200                .as_ref()
201                .map_or(serde_json::Value::Null, |style| style.to_json())
202        })
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209    use crate::color::Color;
210    use crate::fonts::{Properties as FontProperties, Weight};
211
212    #[crate::test(self)]
213    fn test_layout_label_with_highlights(cx: &mut crate::MutableAppContext) {
214        let default_style = TextStyle::new(
215            "Menlo",
216            12.,
217            Default::default(),
218            Default::default(),
219            Default::default(),
220            Color::black(),
221            cx.font_cache(),
222        )
223        .unwrap();
224        let highlight_style = TextStyle::new(
225            "Menlo",
226            12.,
227            *FontProperties::new().weight(Weight::BOLD),
228            Default::default(),
229            Default::default(),
230            Color::new(255, 0, 0, 255),
231            cx.font_cache(),
232        )
233        .unwrap();
234        let label = Label::new(
235            ".αβγδε.ⓐⓑⓒⓓⓔ.abcde.".to_string(),
236            LabelStyle {
237                text: default_style.clone(),
238                highlight_text: Some(highlight_style.clone()),
239            },
240        )
241        .with_highlights(vec![
242            "".len(),
243            ".αβ".len(),
244            ".αβγδ".len(),
245            ".αβγδε.ⓐ".len(),
246            ".αβγδε.ⓐⓑ".len(),
247        ]);
248
249        let default_run_style = RunStyle {
250            font_id: default_style.font_id,
251            color: default_style.color,
252            underline: default_style.underline,
253        };
254        let highlight_run_style = RunStyle {
255            font_id: highlight_style.font_id,
256            color: highlight_style.color,
257            underline: highlight_style.underline,
258        };
259        let runs = label.compute_runs();
260        assert_eq!(
261            runs.as_slice(),
262            &[
263                ("".len(), default_run_style),
264                ("βγ".len(), highlight_run_style),
265                ("δ".len(), default_run_style),
266                ("ε".len(), highlight_run_style),
267                (".ⓐ".len(), default_run_style),
268                ("ⓑⓒ".len(), highlight_run_style),
269                ("ⓓⓔ.abcde.".len(), default_run_style),
270            ]
271        );
272    }
273}