1use crate::{
2 color::Color,
3 fonts::{HighlightStyle, TextStyle},
4 geometry::{
5 rect::RectF,
6 vector::{vec2f, Vector2F},
7 },
8 json::{ToJson, Value},
9 platform::CursorStyle,
10 text_layout::{Line, RunStyle, ShapedBoundary},
11 CursorRegion, Element, FontCache, MouseRegion, SceneBuilder, SizeConstraint, TextLayoutCache,
12 View, ViewContext,
13};
14use log::warn;
15use serde_json::json;
16use std::{borrow::Cow, ops::Range, sync::Arc};
17
18pub struct Text {
19 text: Cow<'static, str>,
20 style: TextStyle,
21 soft_wrap: bool,
22 highlights: Option<Box<[(Range<usize>, HighlightStyle)]>>,
23 mouse_runs: Option<(
24 Box<[Range<usize>]>,
25 Box<dyn FnMut(usize, RectF) -> MouseRegion>,
26 )>,
27}
28
29pub struct LayoutState {
30 shaped_lines: Vec<Line>,
31 wrap_boundaries: Vec<Vec<ShapedBoundary>>,
32 line_height: f32,
33}
34
35impl Text {
36 pub fn new<I: Into<Cow<'static, str>>>(text: I, style: TextStyle) -> Self {
37 Self {
38 text: text.into(),
39 style,
40 soft_wrap: true,
41 highlights: None,
42 mouse_runs: None,
43 }
44 }
45
46 pub fn with_default_color(mut self, color: Color) -> Self {
47 self.style.color = color;
48 self
49 }
50
51 pub fn with_highlights(
52 mut self,
53 runs: impl Into<Box<[(Range<usize>, HighlightStyle)]>>,
54 ) -> Self {
55 self.highlights = Some(runs.into());
56 self
57 }
58
59 pub fn with_mouse_regions(
60 mut self,
61 runs: impl Into<Box<[Range<usize>]>>,
62 build_mouse_region: impl 'static + FnMut(usize, RectF) -> MouseRegion,
63 ) -> Self {
64 self.mouse_runs = Some((runs.into(), Box::new(build_mouse_region)));
65 self
66 }
67
68 pub fn with_soft_wrap(mut self, soft_wrap: bool) -> Self {
69 self.soft_wrap = soft_wrap;
70 self
71 }
72}
73
74impl<V: View> Element<V> for Text {
75 type LayoutState = LayoutState;
76 type PaintState = ();
77
78 fn layout(
79 &mut self,
80 constraint: SizeConstraint,
81 _: &mut V,
82 cx: &mut ViewContext<V>,
83 ) -> (Vector2F, Self::LayoutState) {
84 // Convert the string and highlight ranges into an iterator of highlighted chunks.
85
86 let mut offset = 0;
87 let mut highlight_ranges = self
88 .highlights
89 .as_ref()
90 .map_or(Default::default(), AsRef::as_ref)
91 .iter()
92 .peekable();
93 let chunks = std::iter::from_fn(|| {
94 let result;
95 if let Some((range, highlight_style)) = highlight_ranges.peek() {
96 if offset < range.start {
97 result = Some((&self.text[offset..range.start], None));
98 offset = range.start;
99 } else if range.end <= self.text.len() {
100 result = Some((&self.text[range.clone()], Some(*highlight_style)));
101 highlight_ranges.next();
102 offset = range.end;
103 } else {
104 warn!(
105 "Highlight out of text range. Text len: {}, Highlight range: {}..{}",
106 self.text.len(),
107 range.start,
108 range.end
109 );
110 result = None;
111 }
112 } else if offset < self.text.len() {
113 result = Some((&self.text[offset..], None));
114 offset = self.text.len();
115 } else {
116 result = None;
117 }
118 result
119 });
120
121 // Perform shaping on these highlighted chunks
122 let shaped_lines = layout_highlighted_chunks(
123 chunks,
124 &self.style,
125 cx.text_layout_cache(),
126 &cx.font_cache,
127 usize::MAX,
128 self.text.matches('\n').count() + 1,
129 );
130
131 // If line wrapping is enabled, wrap each of the shaped lines.
132 let font_id = self.style.font_id;
133 let mut line_count = 0;
134 let mut max_line_width = 0_f32;
135 let mut wrap_boundaries = Vec::new();
136 let mut wrapper = cx.font_cache.line_wrapper(font_id, self.style.font_size);
137 for (line, shaped_line) in self.text.split('\n').zip(&shaped_lines) {
138 if self.soft_wrap {
139 let boundaries = wrapper
140 .wrap_shaped_line(line, shaped_line, constraint.max.x())
141 .collect::<Vec<_>>();
142 line_count += boundaries.len() + 1;
143 wrap_boundaries.push(boundaries);
144 } else {
145 line_count += 1;
146 }
147 max_line_width = max_line_width.max(shaped_line.width());
148 }
149
150 let line_height = cx.font_cache.line_height(self.style.font_size);
151 let size = vec2f(
152 max_line_width
153 .ceil()
154 .max(constraint.min.x())
155 .min(constraint.max.x()),
156 (line_height * line_count as f32).ceil(),
157 );
158 (
159 size,
160 LayoutState {
161 shaped_lines,
162 wrap_boundaries,
163 line_height,
164 },
165 )
166 }
167
168 fn paint(
169 &mut self,
170 scene: &mut SceneBuilder,
171 bounds: RectF,
172 visible_bounds: RectF,
173 layout: &mut Self::LayoutState,
174 _: &mut V,
175 cx: &mut ViewContext<V>,
176 ) -> Self::PaintState {
177 let mut origin = bounds.origin();
178 let empty = Vec::new();
179
180 let mouse_runs;
181 let mut build_mouse_region;
182 if let Some((runs, build_region)) = &mut self.mouse_runs {
183 mouse_runs = runs.iter();
184 build_mouse_region = Some(build_region);
185 } else {
186 mouse_runs = [].iter();
187 build_mouse_region = None;
188 }
189 let mut mouse_runs = mouse_runs.enumerate().peekable();
190
191 let mut offset = 0;
192 for (ix, line) in layout.shaped_lines.iter().enumerate() {
193 let wrap_boundaries = layout.wrap_boundaries.get(ix).unwrap_or(&empty);
194 let boundaries = RectF::new(
195 origin,
196 vec2f(
197 bounds.width(),
198 (wrap_boundaries.len() + 1) as f32 * layout.line_height,
199 ),
200 );
201
202 if boundaries.intersects(visible_bounds) {
203 if self.soft_wrap {
204 line.paint_wrapped(
205 scene,
206 origin,
207 visible_bounds,
208 layout.line_height,
209 wrap_boundaries,
210 cx,
211 );
212 } else {
213 line.paint(scene, origin, visible_bounds, layout.line_height, cx);
214 }
215 }
216
217 // Add the mouse regions
218 let end_offset = offset + line.len();
219 if let Some((mut mouse_run_ix, mut mouse_run_range)) = mouse_runs.peek().cloned() {
220 if mouse_run_range.start < end_offset {
221 let mut current_mouse_run = None;
222 if mouse_run_range.start <= offset {
223 current_mouse_run = Some((mouse_run_ix, origin));
224 }
225
226 let mut glyph_origin = origin;
227 let mut prev_position = 0.;
228 let mut wrap_boundaries = wrap_boundaries.iter().copied().peekable();
229 for (glyph_ix, glyph) in line
230 .runs()
231 .iter()
232 .flat_map(|run| run.glyphs().iter().enumerate())
233 {
234 glyph_origin.set_x(glyph_origin.x() + glyph.position.x() - prev_position);
235 prev_position = glyph.position.x();
236
237 if wrap_boundaries
238 .peek()
239 .map_or(false, |b| b.glyph_ix == glyph_ix)
240 {
241 if let Some((mouse_run_ix, mouse_region_start)) = &mut current_mouse_run
242 {
243 let bounds = RectF::from_points(
244 *mouse_region_start,
245 glyph_origin + vec2f(0., layout.line_height),
246 );
247 scene.push_cursor_region(CursorRegion {
248 bounds,
249 style: CursorStyle::PointingHand,
250 });
251 scene.push_mouse_region((build_mouse_region.as_mut().unwrap())(
252 *mouse_run_ix,
253 bounds,
254 ));
255 *mouse_region_start =
256 vec2f(origin.x(), glyph_origin.y() + layout.line_height);
257 }
258
259 wrap_boundaries.next();
260 glyph_origin = vec2f(origin.x(), glyph_origin.y() + layout.line_height);
261 }
262
263 if offset + glyph.index == mouse_run_range.start {
264 current_mouse_run = Some((mouse_run_ix, glyph_origin));
265 }
266 if offset + glyph.index == mouse_run_range.end {
267 if let Some((mouse_run_ix, mouse_region_start)) =
268 current_mouse_run.take()
269 {
270 let bounds = RectF::from_points(
271 mouse_region_start,
272 glyph_origin + vec2f(0., layout.line_height),
273 );
274 scene.push_cursor_region(CursorRegion {
275 bounds,
276 style: CursorStyle::PointingHand,
277 });
278 scene.push_mouse_region((build_mouse_region.as_mut().unwrap())(
279 mouse_run_ix,
280 bounds,
281 ));
282 mouse_runs.next();
283 }
284
285 if let Some(next) = mouse_runs.peek() {
286 mouse_run_ix = next.0;
287 mouse_run_range = next.1;
288 if mouse_run_range.start >= end_offset {
289 break;
290 }
291 if mouse_run_range.start == offset + glyph.index {
292 current_mouse_run = Some((mouse_run_ix, glyph_origin));
293 }
294 }
295 }
296 }
297
298 if let Some((mouse_run_ix, mouse_region_start)) = current_mouse_run {
299 let line_end = glyph_origin + vec2f(line.width() - prev_position, 0.);
300 let bounds = RectF::from_points(
301 mouse_region_start,
302 line_end + vec2f(0., layout.line_height),
303 );
304 scene.push_cursor_region(CursorRegion {
305 bounds,
306 style: CursorStyle::PointingHand,
307 });
308 scene.push_mouse_region((build_mouse_region.as_mut().unwrap())(
309 mouse_run_ix,
310 bounds,
311 ));
312 }
313 }
314 }
315
316 offset = end_offset + 1;
317 origin.set_y(boundaries.max_y());
318 }
319 }
320
321 fn rect_for_text_range(
322 &self,
323 _: Range<usize>,
324 _: RectF,
325 _: RectF,
326 _: &Self::LayoutState,
327 _: &Self::PaintState,
328 _: &V,
329 _: &ViewContext<V>,
330 ) -> Option<RectF> {
331 None
332 }
333
334 fn debug(
335 &self,
336 bounds: RectF,
337 _: &Self::LayoutState,
338 _: &Self::PaintState,
339 _: &V,
340 _: &ViewContext<V>,
341 ) -> Value {
342 json!({
343 "type": "Text",
344 "bounds": bounds.to_json(),
345 "text": &self.text,
346 "style": self.style.to_json(),
347 })
348 }
349}
350
351/// Perform text layout on a series of highlighted chunks of text.
352pub fn layout_highlighted_chunks<'a>(
353 chunks: impl Iterator<Item = (&'a str, Option<HighlightStyle>)>,
354 text_style: &TextStyle,
355 text_layout_cache: &TextLayoutCache,
356 font_cache: &Arc<FontCache>,
357 max_line_len: usize,
358 max_line_count: usize,
359) -> Vec<Line> {
360 let mut layouts = Vec::with_capacity(max_line_count);
361 let mut line = String::new();
362 let mut styles = Vec::new();
363 let mut row = 0;
364 let mut line_exceeded_max_len = false;
365 for (chunk, highlight_style) in chunks.chain([("\n", Default::default())]) {
366 for (ix, mut line_chunk) in chunk.split('\n').enumerate() {
367 if ix > 0 {
368 layouts.push(text_layout_cache.layout_str(&line, text_style.font_size, &styles));
369 line.clear();
370 styles.clear();
371 row += 1;
372 line_exceeded_max_len = false;
373 if row == max_line_count {
374 return layouts;
375 }
376 }
377
378 if !line_chunk.is_empty() && !line_exceeded_max_len {
379 let text_style = if let Some(style) = highlight_style {
380 text_style
381 .clone()
382 .highlight(style, font_cache)
383 .map(Cow::Owned)
384 .unwrap_or_else(|_| Cow::Borrowed(text_style))
385 } else {
386 Cow::Borrowed(text_style)
387 };
388
389 if line.len() + line_chunk.len() > max_line_len {
390 let mut chunk_len = max_line_len - line.len();
391 while !line_chunk.is_char_boundary(chunk_len) {
392 chunk_len -= 1;
393 }
394 line_chunk = &line_chunk[..chunk_len];
395 line_exceeded_max_len = true;
396 }
397
398 line.push_str(line_chunk);
399 styles.push((
400 line_chunk.len(),
401 RunStyle {
402 font_id: text_style.font_id,
403 color: text_style.color,
404 underline: text_style.underline,
405 },
406 ));
407 }
408 }
409 }
410
411 layouts
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417 use crate::{elements::Empty, fonts, AnyElement, AppContext, Entity, View, ViewContext};
418
419 #[crate::test(self)]
420 fn test_soft_wrapping_with_carriage_returns(cx: &mut AppContext) {
421 cx.add_window(Default::default(), |cx| {
422 let mut view = TestView;
423 fonts::with_font_cache(cx.font_cache().clone(), || {
424 let mut text = Text::new("Hello\r\n", Default::default()).with_soft_wrap(true);
425 let (_, state) = text.layout(
426 SizeConstraint::new(Default::default(), vec2f(f32::INFINITY, f32::INFINITY)),
427 &mut view,
428 cx,
429 );
430 assert_eq!(state.shaped_lines.len(), 2);
431 assert_eq!(state.wrap_boundaries.len(), 2);
432 });
433 view
434 });
435 }
436
437 struct TestView;
438
439 impl Entity for TestView {
440 type Event = ();
441 }
442
443 impl View for TestView {
444 fn ui_name() -> &'static str {
445 "TestView"
446 }
447
448 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
449 Empty::new().into_any()
450 }
451 }
452}