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