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