1use super::*;
4
5pub struct Flat {
11 pub text: SharedString,
12 pub runs: Vec<TextRun>,
13 pub links: Vec<(Range<usize>, String)>,
14 pub code: Vec<Range<usize>>,
15 pub mentions: Vec<Mention>,
16 pub shown: Shown,
17}
18
19#[derive(Clone, Debug)]
21pub struct Mention {
22 pub url: String,
23 pub range: Range<usize>,
25 pub icon: Range<usize>,
27 pub favicon: Option<SharedString>,
28 pub glyph: Option<ui::icons::Icon>,
30 pub initial: SharedString,
32}
33
34pub use ui::input::Shown;
35
36const ICON_SLOT: &str = "\u{2003}";
39
40pub fn flatten(text: &Text, base_weight: FontWeight, theme: &Theme) -> Flat {
43 flatten_with(text, base_weight, theme, |_| None, |_| None)
44}
45
46pub fn flatten_with(
50 text: &Text,
51 base_weight: FontWeight,
52 theme: &Theme,
53 paint: impl Fn(&str) -> Option<crate::MarkPaint>,
54 preview: impl Fn(&str) -> Option<preview::Preview>,
55) -> Flat {
56 let mut cuts: Vec<usize> = text
57 .marks
58 .iter()
59 .flat_map(|span| [span.range.start, span.range.end])
60 .chain([0, text.text.len()])
61 .filter(|cut| *cut <= text.text.len())
62 .collect();
63 cuts.sort_unstable();
64 cuts.dedup();
65
66 let mut atoms: Vec<(Range<usize>, &str)> = text
68 .marks
69 .iter()
70 .filter_map(|span| match &span.mark {
71 Mark::Mention { url, .. } if !span.range.is_empty() => {
72 Some((span.range.clone(), url.as_str()))
73 }
74 _ => None,
75 })
76 .collect();
77 atoms.sort_by_key(|(range, _)| range.start);
78 atoms.dedup_by(|later, earlier| later.0.start < earlier.0.end);
79
80 let mut shown = String::with_capacity(text.text.len());
81 let mut runs = Vec::new();
82 let mut links: Vec<(Range<usize>, String)> = Vec::new();
83 let mut code: Vec<Range<usize>> = Vec::new();
84 let mut mentions: Vec<Mention> = Vec::new();
85 let mut map: Vec<(Range<usize>, Range<usize>)> = Vec::new();
86
87 for pair in cuts.windows(2) {
88 let (start, end) = (pair[0], pair[1]);
89 let atom = atoms
90 .iter()
91 .find(|(range, _)| range.start <= start && end <= range.end);
92 if atom.is_some_and(|(range, _)| range.start != start) {
93 continue;
94 }
95 let covering = text
96 .marks
97 .iter()
98 .filter(|span| span.range.start <= start && span.range.end >= end);
99
100 let (mut bold, mut italic, mut mono, mut strike) = (false, false, false, false);
101 let mut link = None;
102 let mut custom = crate::MarkPaint::default();
105 for span in covering {
106 match &span.mark {
107 Mark::Bold => bold = true,
108 Mark::Italic => italic = true,
109 Mark::Strike => strike = true,
110 Mark::Code => mono = true,
111 Mark::Mention { .. } => {}
112 Mark::Link(url) | Mark::Image(url) => link = Some(url.clone()),
113 Mark::Custom(name) => {
114 let Some(painted) = paint(name) else { continue };
115 custom.color = painted.color.or(custom.color);
116 custom.background = painted.background.or(custom.background);
117 custom.weight = painted.weight.or(custom.weight);
118 custom.italic |= painted.italic;
119 custom.underline |= painted.underline;
120 custom.strikethrough |= painted.strikethrough;
121 }
122 }
123 }
124 let (italic, strike) = (italic || custom.italic, strike || custom.strikethrough);
125
126 let mut face = font(if mono && atom.is_none() {
127 theme.font_mono.clone()
128 } else {
129 theme.font_body.clone()
130 });
131 face.weight = if bold && base_weight.0 < FontWeight::SEMIBOLD.0 {
132 FontWeight::SEMIBOLD
133 } else {
134 custom.weight.unwrap_or(base_weight)
135 };
136 face.style = if italic {
137 FontStyle::Italic
138 } else {
139 FontStyle::Normal
140 };
141 let underline = UnderlineStyle {
142 color: Some(theme.text_muted),
143 thickness: px(1.0),
144 wavy: false,
145 };
146
147 if let Some((range, url)) = atom {
148 let described = preview(url).unwrap_or_default();
149 let host = preview::host(url);
150 let own = &text.text[range.clone()];
151 let title: SharedString = match &described.title {
152 Some(title) => title.clone(),
153 None if own != *url => own.to_string().into(),
154 None => host.to_string().into(),
155 };
156 let from = shown.len();
157 let mut run = |shown: &mut String,
158 piece: &str,
159 color: Hsla,
160 underline: Option<UnderlineStyle>| {
161 shown.push_str(piece);
162 runs.push(TextRun {
163 len: piece.len(),
164 font: face.clone(),
165 color,
166 background_color: None,
167 underline,
168 strikethrough: None,
169 });
170 };
171 run(&mut shown, ICON_SLOT, gpui::transparent_black(), None);
172 run(&mut shown, " ", theme.text, None);
173 if let Some(label) = described.label.filter(|_| described.title.is_some()) {
174 run(&mut shown, &label, theme.text_muted, None);
175 run(&mut shown, " ", theme.text, None);
176 }
177 run(&mut shown, &title, theme.text, Some(underline));
178 let to = shown.len();
179 links.push((from..to, url.to_string()));
180 mentions.push(Mention {
181 url: url.to_string(),
182 range: from..to,
183 icon: from..from + ICON_SLOT.len(),
184 favicon: described.icon,
185 glyph: described.glyph,
186 initial: host
187 .chars()
188 .next()
189 .unwrap_or('?')
190 .to_uppercase()
191 .to_string()
192 .into(),
193 });
194 map.push((range.clone(), from..to));
195 continue;
196 }
197
198 let (from, to) = (shown.len(), shown.len() + end - start);
199 shown.push_str(&text.text[start..end]);
200 if mono {
201 match code.last_mut() {
202 Some(range) if range.end == from => range.end = to,
203 _ => code.push(from..to),
204 }
205 }
206 if let Some(url) = &link {
207 match links.last_mut() {
208 Some((range, last)) if range.end == from && last == url => range.end = to,
209 _ => links.push((from..to, url.clone())),
210 }
211 }
212
213 runs.push(TextRun {
214 len: end - start,
215 font: face,
216 color: match (mono, custom.color) {
219 (_, Some(color)) => color,
220 (true, None) => theme.code_text,
221 (false, None) => theme.text,
222 },
223 background_color: custom.background,
224 underline: (link.is_some() || custom.underline).then_some(underline),
225 strikethrough: strike.then_some(StrikethroughStyle {
226 thickness: px(1.0),
227 color: Some(theme.text_muted),
228 }),
229 });
230 }
231
232 Flat {
233 text: shown.into(),
234 runs,
235 links,
236 code,
237 mentions,
238 shown: Shown::new(map),
239 }
240}
241
242pub(super) fn text_element(
243 text: &Text,
244 size: f32,
245 line_height: f32,
246 weight: FontWeight,
247 overlay: Overlay,
248 theme: &Theme,
249 cx: &App,
250) -> AnyElement {
251 let flat = flatten_with(
252 text,
253 weight,
254 theme,
255 |name| crate::marks::paint_of(cx, name, theme),
256 |url| preview::of(cx, url),
257 );
258 painted_text(flat, text.text.len(), size, line_height, overlay, theme)
259}
260
261pub(super) fn painted_text(
267 flat: Flat,
268 len: usize,
269 size: f32,
270 line_height: f32,
271 overlay: Overlay,
272 theme: &Theme,
273) -> AnyElement {
274 let (ix, part) = (overlay.block, overlay.part);
275 let shown = flat.shown.clone();
276 let caret = overlay.caret_painted().map(|offset| shown.at(offset));
277 let selected = overlay.selected(len).map(|range| shown.range(&range));
278 let span = 0..len;
279 let hint = overlay
282 .placeholder
283 .filter(|_| len == 0 && overlay.caret().is_some())
286 .map(|hint| {
287 div()
288 .absolute()
289 .text_color(theme.text_faint)
290 .child(hint.clone())
291 });
292 let (shape, height, hollow) = (
293 overlay.caret_shape,
294 overlay.caret_height,
295 overlay.caret_hollow(),
296 );
297 let glyph = caret
298 .filter(|_| shape.cuts_out(hollow))
299 .and_then(|offset| glyph_at(&flat.text, offset));
300 let runs = match &glyph {
301 Some(glyph) => ui::input::caret::recoloured(flat.runs, glyph, theme.bg),
302 None => flat.runs,
303 };
304 let styled = StyledText::new(flat.text).with_runs(runs);
305 let layout = styled.layout().clone();
306
307 let mentions = flat.mentions;
308 let painted: AnyElement =
309 if flat.links.is_empty() {
310 styled.into_any_element()
311 } else {
312 let (ranges, urls): (Vec<_>, Vec<_>) = flat.links.into_iter().unzip();
313 let hovered: Vec<(Range<usize>, String)> = mentions
314 .iter()
315 .filter(|mention| mention.glyph.is_none())
316 .map(|mention| (mention.range.clone(), mention.url.clone()))
317 .collect();
318 let text = InteractiveText::new(ElementId::named_usize("md-text", ix), styled)
319 .on_click(ranges, move |clicked, window, cx| {
320 if let Some(url) = urls.get(clicked) {
321 crate::link::open(url, window, cx);
322 }
323 });
324 match hovered.is_empty() {
325 true => text.into_any_element(),
326 false => text
327 .tooltip(move |at, _window, cx| {
328 let (_, url) = hovered.iter().find(|(range, _)| range.contains(&at))?;
329 Some(MentionCard::view(url, cx))
330 })
331 .into_any_element(),
332 }
333 };
334
335 let wash = theme.code_wash;
339 let code_ranges = flat.code;
340 let (icon_color, icon_wash) = (theme.text_muted, theme.element_hover);
341 let caret_color = theme.caret;
342 let selection_color = theme.selection;
343 let annotated: Vec<_> = overlay
344 .annotated(len, theme)
345 .into_iter()
346 .map(|(range, wash)| (shown.range(&range), wash))
347 .collect();
348 let layouts = overlay.layouts.cloned();
349 let underlay = canvas(
350 {
351 let mentions = mentions.clone();
352 move |_, window, cx| {
353 mentions
354 .iter()
355 .map(|mention| {
356 let favicon = mention.favicon.clone()?;
357 let source = gpui::Resource::Uri(favicon.to_string().into());
358 window
359 .use_asset::<gpui::ImgResourceLoader>(&source, cx)?
360 .ok()
361 })
362 .collect::<Vec<_>>()
363 }
364 },
365 move |_, favicons, window, cx| {
366 if let Some(layouts) = &layouts {
367 layouts.record(ix, part, span.clone(), layout.clone(), shown.clone());
368 }
369 for (range, wash) in &annotated {
372 for rect in range_rects(&layout, range, 0.0, 0.0) {
373 window.paint_quad(quad(
374 rect,
375 px(2.0),
376 *wash,
377 px(0.0),
378 gpui::transparent_black(),
379 BorderStyle::default(),
380 ));
381 }
382 }
383 if let Some(range) = &selected {
387 for rect in range_rects(&layout, range, 0.0, 0.0) {
388 window.paint_quad(quad(
389 rect,
390 px(2.0),
391 selection_color,
392 px(0.0),
393 gpui::transparent_black(),
394 BorderStyle::default(),
395 ));
396 }
397 }
398 if let Some(offset) = caret {
399 let face = font(Theme::of(cx).font_body.clone());
400 paint_caret(
401 &layout,
402 offset,
403 glyph.as_ref(),
404 CaretPaint {
405 shape,
406 height,
407 hollow,
408 color: caret_color,
409 size,
410 face,
411 },
412 window,
413 );
414 }
415 for range in &code_ranges {
416 for rect in range_rects(&layout, range, INLINE_CODE_PAD_X, INLINE_CODE_INSET_Y) {
417 window.paint_quad(quad(
418 rect,
419 px(INLINE_CODE_RADIUS),
420 wash,
421 px(0.0),
422 gpui::transparent_black(),
423 BorderStyle::default(),
424 ));
425 }
426 }
427 for (mention, favicon) in mentions.iter().zip(favicons) {
428 let Some(slot) = range_rects(&layout, &mention.icon, 0.0, 0.0).pop() else {
429 continue;
430 };
431 let side = slot.size.width.min(px(size));
432 let icon = Bounds::new(
433 slot.origin + point(px(0.0), (slot.size.height - side) / 2.0),
434 gpui::size(side, side),
435 );
436 let radius = gpui::Corners::all(side / 4.0);
437 if let Some(data) = mention.glyph.as_ref().and_then(|glyph| glyph.data()) {
438 let path = SharedString::from(format!("markdown-glyph-{:p}", data.as_ptr()));
439 window
440 .paint_svg(
441 icon,
442 path,
443 Some(data),
444 gpui::TransformationMatrix::unit(),
445 icon_color,
446 cx,
447 )
448 .ok();
449 continue;
450 }
451 if let Some(favicon) = favicon {
452 window
453 .paint_image(icon, icon, radius, favicon, 0, false)
454 .ok();
455 continue;
456 }
457 window.paint_quad(quad(
458 icon,
459 side / 4.0,
460 icon_wash,
461 px(0.0),
462 gpui::transparent_black(),
463 BorderStyle::default(),
464 ));
465 let font = font(Theme::of(cx).font_body.clone());
466 let letter = window.text_system().shape_line(
467 mention.initial.clone(),
468 side * 0.55,
469 &[TextRun {
470 len: mention.initial.len(),
471 font,
472 color: icon_color,
473 background_color: None,
474 underline: None,
475 strikethrough: None,
476 }],
477 None,
478 );
479 let at = point(icon.center().x - letter.width / 2.0, icon.origin.y);
480 letter
481 .paint(at, side, gpui::TextAlign::Left, None, window, cx)
482 .ok();
483 }
484 },
485 )
486 .absolute()
487 .size_full();
488
489 div()
490 .text_size(px(size))
491 .line_height(px(line_height))
492 .relative()
493 .child(underlay)
494 .children(hint)
495 .child(painted)
496 .into_any_element()
497}
498
499pub(super) fn caret_quad(head: Point<Pixels>, size: f32, line_height: Pixels) -> Bounds<Pixels> {
505 let inset = (line_height - px(size)) / 2.0;
506 Bounds::new(
507 head + point(px(0.0), inset),
508 gpui::size(px(CARET_WIDTH), px(size)),
509 )
510}
511
512pub(super) fn glyph_at(text: &str, offset: usize) -> Option<Range<usize>> {
514 (offset < text.len() && text.is_char_boundary(offset) && !text[offset..].starts_with('\n'))
515 .then(|| offset..ui::input::next_boundary(text, offset))
516}
517
518pub(super) struct CaretPaint {
520 pub shape: ui::input::CaretShape,
521 pub height: ui::input::CaretHeight,
522 pub hollow: bool,
523 pub color: Hsla,
524 pub size: f32,
526 pub face: gpui::Font,
528}
529
530pub(super) fn paint_caret(
533 layout: &TextLayout,
534 offset: usize,
535 glyph: Option<&Range<usize>>,
536 paint: CaretPaint,
537 window: &mut Window,
538) {
539 let line_height = layout.line_height();
540 let covered = glyph.and_then(|glyph| range_rects(layout, glyph, 0.0, 0.0).into_iter().next());
541 let (head, width) = match covered {
542 Some(rect) => (rect.origin, rect.size.width),
543 None => {
544 let Some(head) = layout.position_for_index(offset) else {
545 return;
546 };
547 let width = match paint.shape {
548 ui::input::CaretShape::Bar => px(0.0),
549 _ => caret_advance(layout, offset).unwrap_or_else(|| {
550 ui::input::caret::zero_width(paint.face, px(paint.size), window)
551 }),
552 };
553 (head, width)
554 }
555 };
556 window.paint_quad(paint.shape.quad(
557 caret_quad(head, paint.size, line_height),
558 line_height,
559 paint.height,
560 width,
561 paint.color,
562 paint.hollow,
563 ));
564}
565
566pub(super) fn range_rects(
568 layout: &gpui::TextLayout,
569 range: &Range<usize>,
570 pad_x: f32,
571 inset_y: f32,
572) -> Vec<Bounds<Pixels>> {
573 let mut rects = Vec::new();
574 let line_height = layout.line_height();
575 let mut origin = layout.bounds().origin;
576 let mut line_start = 0;
577 for line in layout.line_layouts() {
578 let shaped = &line.unwrapped_layout;
579 let row_ends = line
582 .wrap_boundaries()
583 .iter()
584 .map(|wrap| shaped.runs[wrap.run_ix].glyphs[wrap.glyph_ix].index)
585 .chain([line.len()]);
586 let mut row_start = 0;
587 for (row, row_end) in row_ends.enumerate() {
588 let from = range
589 .start
590 .saturating_sub(line_start)
591 .clamp(row_start, row_end);
592 let to = range.end.saturating_sub(line_start).min(row_end);
593 let row_x = shaped.x_for_index(row_start);
594 let (left, right) = (shaped.x_for_index(from), shaped.x_for_index(to));
595 if from < to && right > left {
596 rects.push(Bounds::new(
597 origin
598 + point(
599 left - row_x - px(pad_x),
600 line_height * row as f32 + px(inset_y),
601 ),
602 size(
603 right - left + px(2.0 * pad_x),
604 line_height - px(2.0 * inset_y),
605 ),
606 ));
607 }
608 row_start = row_end;
609 }
610 origin.y += line.size(line_height).height;
611 line_start += line.len() + 1;
613 }
614 rects
615}
616
617pub(super) fn caret_advance(layout: &TextLayout, offset: usize) -> Option<Pixels> {
619 let text = layout.text();
620 let mut start = 0;
621 for line in layout.line_layouts() {
622 let end = start + line.len();
623 if offset <= end {
624 return ui::input::caret::character_advance(&line, &text[start..end], offset - start);
625 }
626 start = end + 1;
627 }
628 None
629}