BlueGit

ict rusty-teams

Files

rusty-teams / vendor / gpui-base / src / text / inline_flow.rs

inline_flow.rs

eef6c0a4 History
inline_flow.rs 79.8 KiB Download Raw
1use std::{
2 cell::RefCell,
3 ops::Range,
4 rc::Rc,
5 sync::{Arc, Mutex},
6};
7use unicode_segmentation::UnicodeSegmentation as _;
8
9use gpui::{
10 AbsoluteLength, AnyElement, App, AvailableSpace, Bounds, DefiniteLength, Element, ElementId,
11 GlobalElementId, Hsla, ImageSource, InspectorElementId, InteractiveElement as _, IntoElement,
12 LayoutId, LineFragment as WrapLineFragment, ObjectFit, Pixels, Refineable as _, ShapedLine,
13 SharedString, Size, StatefulInteractiveElement as _, Styled, StyledImage as _, TextRun,
14 TextStyle, WhiteSpace, Window, img, point, prelude::FluentBuilder as _, px, relative, size,
15};
16
17use crate::text::text_view::{LinkClickHandlerFn, handle_link_click};
18
19use super::{
20 inline::{Inline, InlineHighlight, InlineState, text_runs, text_size_ranges},
21 inline_object::{InlineObject, MeasuredInlineObject},
22 node::LinkMark,
23 range_highlight::RevealAt,
24};
25
26const IMAGE_LEN: usize = 1;
27pub(super) const INLINE_CODE_PADDING: f32 = 2.;
28
29pub(super) struct InlineFlow {
30 id: ElementId,
31 items: Vec<InlineFlowItem>,
32 link_click_handler: Option<Arc<LinkClickHandlerFn>>,
33}
34
35pub(super) type InlineRenderer = dyn Fn(&super::InlineRenderContext, &mut Window, &mut App) -> Option<super::InlineElement>
36 + Send
37 + Sync;
38
39pub(super) enum InlineFlowItem {
40 Object {
41 text: SharedString,
42 id: usize,
43 renderer: Arc<InlineRenderer>,
44 accessibility_label: SharedString,
45 selected: Arc<Mutex<bool>>,
46 style: gpui::HighlightStyle,
47 link: Option<LinkMark>,
48 },
49 Text {
50 state: Arc<Mutex<InlineState>>,
51 text: SharedString,
52 links: Vec<(Range<usize>, LinkMark)>,
53 highlights: Vec<(Range<usize>, InlineHighlight)>,
54 /// Range highlight backgrounds, in this item's byte space. They are
55 /// only painted, so unlike `highlights` they take no part in layout.
56 backgrounds: Vec<(Range<usize>, Hsla)>,
57 /// The start of a pending reveal, when it is in this item.
58 reveal: Option<RevealAt>,
59 },
60 Image {
61 source: ImageSource,
62 link: Option<LinkMark>,
63 title: String,
64 width: Option<DefiniteLength>,
65 height: Option<DefiniteLength>,
66 },
67}
68
69pub(crate) struct InlineFlowLayoutState {
70 typography: InlineFlowTypography,
71 frame_state: Rc<RefCell<InlineFlowFrameState>>,
72 /// The layout this element's last measurement returned, which is the
73 /// one to paint. Per element, not per state: two flows under the same
74 /// id (the same document shown twice) share the state's layouts but
75 /// paint their own.
76 current: Rc<RefCell<Option<Rc<InlineFlowLayout>>>>,
77}
78
79/// What a flow keeps from one frame to the next, as GPUI element state under
80/// the flow's id.
81#[derive(Default)]
82struct InlineFlowFrameState {
83 /// One state per text fragment, by text-fragment index. A fragment's `Inline`
84 /// retains its shaped text under its state (see `RetainedLayout`), so
85 /// the state has to be the same one next frame for the text to be
86 /// found; a fresh state per frame shaped every fragment again and left
87 /// an entry in the table that nobody would take.
88 fragment_states: Vec<Arc<Mutex<InlineState>>>,
89 /// What `layouts` were laid out from. A frame whose items or typography
90 /// differ starts over.
91 key: Option<FlowLayoutKey>,
92 /// The layouts of `key`, one per wrap width the flow was measured at:
93 /// taffy probes a flow at more than one width in a frame (unconstrained,
94 /// then the column's). A frame that changes nothing finds every width
95 /// here and wraps and shapes nothing.
96 layouts: Vec<Rc<InlineFlowLayout>>,
97}
98
99/// How many wrap widths a flow keeps a layout for.
100const LAYOUTS_PER_FLOW: usize = 3;
101
102impl InlineFlowFrameState {
103 fn fragment_state(&mut self, fragment_ix: usize) -> Arc<Mutex<InlineState>> {
104 if self.fragment_states.len() <= fragment_ix {
105 self.fragment_states
106 .resize_with(fragment_ix + 1, Default::default);
107 }
108 self.fragment_states[fragment_ix].clone()
109 }
110
111 /// Makes `key` the current one, dropping the layouts of another key.
112 fn set_key(&mut self, key: FlowLayoutKey) {
113 if !self
114 .key
115 .as_ref()
116 .is_some_and(|current| current.matches(&key))
117 {
118 self.layouts.clear();
119 }
120 self.key = Some(key);
121 }
122
123 /// The layout at `wrap_width`, if the key was laid out there already.
124 fn layout_at(&self, wrap_width: Option<Pixels>) -> Option<Rc<InlineFlowLayout>> {
125 self.layouts
126 .iter()
127 .find(|layout| layout.wrap_width == wrap_width)
128 .cloned()
129 }
130
131 /// Keeps `layout`, in place of the oldest one when the flow has been
132 /// measured at more widths than it keeps.
133 fn push_layout(&mut self, layout: Rc<InlineFlowLayout>) {
134 if self.layouts.len() >= LAYOUTS_PER_FLOW {
135 self.layouts.remove(0);
136 }
137 self.layouts.push(layout);
138 }
139}
140
141/// Everything but the wrap width that a flow's layout depends on.
142struct FlowLayoutKey {
143 items: Vec<MeasureItem>,
144 image_sizes: Vec<Option<Size<Pixels>>>,
145 typography: InlineFlowTypography,
146}
147
148impl FlowLayoutKey {
149 fn matches(&self, other: &Self) -> bool {
150 self.items.len() == other.items.len()
151 && self
152 .items
153 .iter()
154 .zip(&other.items)
155 .all(|(item, other)| item.same_layout_input(other))
156 && self.image_sizes == other.image_sizes
157 && self.typography == other.typography
158 }
159}
160
161/// Resolved before `request_measured_layout`, while the parent's text-style
162/// and rem stacks are still active.
163#[derive(Clone, PartialEq)]
164struct InlineFlowTypography {
165 text_style: TextStyle,
166 rem_size: Pixels,
167 line_height: Pixels,
168}
169
170#[derive(Default)]
171struct InlineFlowLayout {
172 fragments: Vec<PositionedFragment>,
173 size: Size<Pixels>,
174 wrap_width: Option<Pixels>,
175}
176
177enum PositionedFragment {
178 Object {
179 item_ix: usize,
180 origin: gpui::Point<Pixels>,
181 object: Box<MeasuredInlineObject>,
182 selection_bounds: Bounds<Pixels>,
183 },
184 Text {
185 item_ix: usize,
186 origin: gpui::Point<Pixels>,
187 size: Size<Pixels>,
188 source_range: Range<usize>,
189 font_size: Pixels,
190 text: SharedString,
191 links: Vec<(Range<usize>, LinkMark)>,
192 highlights: Vec<(Range<usize>, InlineHighlight)>,
193 selection_bounds: Bounds<Pixels>,
194 /// The rounded box behind a code span, relative to the flow.
195 code_background: Option<(Bounds<Pixels>, Hsla)>,
196 },
197 Image {
198 item_ix: usize,
199 origin: gpui::Point<Pixels>,
200 size: Size<Pixels>,
201 },
202}
203
204enum MeasureItem {
205 Object {
206 text: SharedString,
207 id: usize,
208 renderer: Arc<InlineRenderer>,
209 style: gpui::HighlightStyle,
210 },
211 Text {
212 text: SharedString,
213 links: Vec<(Range<usize>, LinkMark)>,
214 highlights: Vec<(Range<usize>, InlineHighlight)>,
215 },
216 Image {
217 source: ImageSource,
218 width: Option<DefiniteLength>,
219 height: Option<DefiniteLength>,
220 },
221}
222
223struct LineFragmentLayout {
224 item_ix: usize,
225 kind: LineFragmentKind,
226 size: Size<Pixels>,
227 source_range: Range<usize>,
228 baseline: Pixels,
229}
230
231enum LineFragmentKind {
232 Object(Box<MeasuredInlineObject>),
233 Text {
234 font_size: Pixels,
235 text: SharedString,
236 links: Vec<(Range<usize>, LinkMark)>,
237 highlights: Vec<(Range<usize>, InlineHighlight)>,
238 /// The code span's box, relative to the fragment.
239 code_background: Option<(Bounds<Pixels>, Hsla)>,
240 },
241 Image,
242}
243
244impl InlineFlow {
245 pub(super) fn new(
246 id: impl Into<ElementId>,
247 items: Vec<InlineFlowItem>,
248 link_click_handler: Option<Arc<LinkClickHandlerFn>>,
249 ) -> Self {
250 Self {
251 id: id.into(),
252 items,
253 link_click_handler,
254 }
255 }
256
257 fn image_element(
258 ix: usize,
259 source: &ImageSource,
260 link: &Option<LinkMark>,
261 _title: &str,
262 size: Size<Pixels>,
263 link_click_handler: Option<Arc<LinkClickHandlerFn>>,
264 ) -> AnyElement {
265 img(source.clone())
266 .id(ix)
267 .object_fit(ObjectFit::Contain)
268 .max_w(relative(1.))
269 .w(size.width)
270 .h(size.height)
271 .when_some(link.clone(), |this, link| {
272 let aux_link = link.clone();
273 let aux_link_click_handler = link_click_handler.clone();
274 this.cursor_pointer()
275 .on_click(move |event, window, cx| {
276 crate::TextSelection::end(window, cx);
277 cx.stop_propagation();
278 handle_link_click(
279 &link_click_handler,
280 link.url.clone(),
281 event.clone(),
282 window,
283 cx,
284 );
285 })
286 .on_aux_click(move |event, window, cx| {
287 crate::TextSelection::end(window, cx);
288 cx.stop_propagation();
289 handle_link_click(
290 &aux_link_click_handler,
291 aux_link.url.clone(),
292 event.clone(),
293 window,
294 cx,
295 );
296 })
297 })
298 .into_any_element()
299 }
300}
301
302impl IntoElement for InlineFlow {
303 type Element = Self;
304
305 fn into_element(self) -> Self::Element {
306 self
307 }
308}
309
310impl Element for InlineFlow {
311 type RequestLayoutState = InlineFlowLayoutState;
312 type PrepaintState = Vec<(AnyElement, Option<(Bounds<Pixels>, gpui::Hsla)>)>;
313
314 fn id(&self) -> Option<ElementId> {
315 Some(self.id.clone())
316 }
317
318 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
319 None
320 }
321
322 fn request_layout(
323 &mut self,
324 id: Option<&GlobalElementId>,
325 _inspector_id: Option<&InspectorElementId>,
326 window: &mut Window,
327 cx: &mut App,
328 ) -> (LayoutId, Self::RequestLayoutState) {
329 let frame_state = window.with_optional_element_state(id, |state, _| {
330 let state: Rc<RefCell<InlineFlowFrameState>> = state.flatten().unwrap_or_default();
331 (state.clone(), Some(state))
332 });
333 let measure_items = self.items.iter().map(MeasureItem::from).collect::<Vec<_>>();
334 // A measured-layout callback runs after the parent's text-style stack
335 // is gone. Capture every resolved typography input while this element
336 // is still requested under its Markdown block (notably headings).
337 let typography = InlineFlowTypography {
338 text_style: window.text_style(),
339 rem_size: window.rem_size(),
340 line_height: window.line_height(),
341 };
342 let image_sizes = measure_items
343 .iter()
344 .enumerate()
345 .map(|(ix, item)| match item {
346 MeasureItem::Image {
347 source,
348 width,
349 height,
350 } => Some(measure_image_size(
351 ix,
352 source,
353 *width,
354 *height,
355 typography.line_height,
356 typography.rem_size,
357 window,
358 cx,
359 )),
360 MeasureItem::Text { .. } | MeasureItem::Object { .. } => None,
361 })
362 .collect::<Vec<_>>();
363 let objects = prepare_objects(&measure_items, &typography.text_style, window, cx);
364 frame_state.borrow_mut().set_key(FlowLayoutKey {
365 items: measure_items,
366 image_sizes,
367 typography: typography.clone(),
368 });
369 let layout_state = InlineFlowLayoutState {
370 typography: typography.clone(),
371 frame_state: frame_state.clone(),
372 current: Rc::default(),
373 };
374 let current = layout_state.current.clone();
375
376 let layout_id = window.request_measured_layout(Default::default(), {
377 move |known_dimensions, available_space, window, cx| {
378 let wrap_width = if typography.text_style.white_space == WhiteSpace::Normal {
379 known_dimensions.width.or(match available_space.width {
380 AvailableSpace::Definite(width) => Some(width),
381 _ => None,
382 })
383 } else {
384 None
385 };
386 let mut state = frame_state.borrow_mut();
387 if let Some(layout) = state.layout_at(wrap_width) {
388 let size = layout.size;
389 *current.borrow_mut() = Some(layout);
390 return size;
391 }
392 let state = &mut *state;
393 let key = state.key.as_ref().expect("set by request_layout");
394 let layout = window.with_rem_size(Some(typography.rem_size), |window| {
395 window.with_text_style(
396 Some(typography.text_style.subtract(&Default::default())),
397 |window| {
398 layout_measured_flow(
399 &key.items,
400 &key.image_sizes,
401 &objects,
402 &typography.text_style,
403 wrap_width,
404 window,
405 cx,
406 )
407 },
408 )
409 });
410 let size = layout.size;
411 let layout = Rc::new(layout);
412 *current.borrow_mut() = Some(layout.clone());
413 state.push_layout(layout);
414 size
415 }
416 });
417
418 (layout_id, layout_state)
419 }
420
421 fn prepaint(
422 &mut self,
423 _id: Option<&GlobalElementId>,
424 _inspector_id: Option<&InspectorElementId>,
425 bounds: Bounds<Pixels>,
426 request_layout: &mut Self::RequestLayoutState,
427 window: &mut Window,
428 cx: &mut App,
429 ) -> Self::PrepaintState {
430 let frame_state = request_layout.frame_state.clone();
431 let Some(layout) = request_layout.current.borrow().clone() else {
432 return Vec::new();
433 };
434 let typography = request_layout.typography.clone();
435 let text_style = &typography.text_style;
436 let mut elements = Vec::with_capacity(layout.fragments.len());
437
438 // A reveal goes to the fragment it starts in. A line break lays out
439 // no fragment, so a reveal starting on one, or on an empty line, goes
440 // to the next fragment of its text, or to the last when none follows.
441 let reveal_fragment = layout
442 .fragments
443 .iter()
444 .enumerate()
445 .filter_map(|(ix, fragment)| {
446 let PositionedFragment::Text {
447 item_ix,
448 source_range,
449 ..
450 } = fragment
451 else {
452 return None;
453 };
454 let InlineFlowItem::Text {
455 reveal: Some(reveal),
456 ..
457 } = &self.items[*item_ix]
458 else {
459 return None;
460 };
461 Some((ix, source_range.end > reveal.offset()))
462 })
463 .reduce(|found, next| if found.1 { found } else { next })
464 .map(|(ix, _)| ix);
465
466 let mut text_fragment_count = 0;
467 for (fragment_ix, fragment) in layout.fragments.iter().enumerate() {
468 match fragment {
469 PositionedFragment::Object {
470 item_ix,
471 origin,
472 object,
473 selection_bounds,
474 } => {
475 let InlineFlowItem::Object {
476 text,
477 id,
478 accessibility_label,
479 selected,
480 link,
481 ..
482 } = &self.items[*item_ix]
483 else {
484 continue;
485 };
486 let object_size = object.metrics.size;
487 let mut element = InlineObject::new(
488 ("inline-object", *id),
489 text.clone(),
490 accessibility_label.clone(),
491 (**object).clone(),
492 selected.clone(),
493 Bounds::new(
494 bounds.origin + selection_bounds.origin,
495 selection_bounds.size,
496 ),
497 Bounds::new(
498 point(bounds.left(), bounds.top() + selection_bounds.top()),
499 size(bounds.size.width, selection_bounds.size.height),
500 ),
501 )
502 .link(link.clone(), self.link_click_handler.clone())
503 .into_any_element();
504 element.prepaint_as_root(
505 bounds.origin + *origin,
506 size(
507 AvailableSpace::Definite(object_size.width),
508 AvailableSpace::Definite(object_size.height),
509 ),
510 window,
511 cx,
512 );
513 elements.push((element, None));
514 }
515 PositionedFragment::Text {
516 item_ix,
517 origin,
518 size: fragment_size,
519 source_range,
520 font_size,
521 text,
522 links,
523 highlights,
524 selection_bounds,
525 code_background,
526 } => {
527 let InlineFlowItem::Text {
528 state: source_state,
529 backgrounds,
530 reveal,
531 ..
532 } = &self.items[*item_ix]
533 else {
534 continue;
535 };
536 let (origin, fragment_size, font_size) = (*origin, *fragment_size, *font_size);
537 let state = frame_state.borrow_mut().fragment_state(text_fragment_count);
538 text_fragment_count += 1;
539 if let Ok(mut state) = state.lock() {
540 state.set_text(text.clone());
541 }
542
543 let is_code = highlights.iter().any(|(_, h)| h.font_size_scale.is_some());
544 let padding = if is_code {
545 px(INLINE_CODE_PADDING)
546 } else {
547 Pixels::ZERO
548 };
549 let background = code_background.map(|(background, color)| {
550 (
551 Bounds::new(bounds.origin + background.origin, background.size),
552 color,
553 )
554 });
555 // The fragment's typography: the flow's style at the
556 // fragment's size, on one line. Fragments are already
557 // wrapped, so this leaf must not wrap independently.
558 let mut fragment_style = text_style.clone();
559 fragment_style.font_size = font_size.into();
560 fragment_style.line_height = fragment_size.height.into();
561 fragment_style.white_space = WhiteSpace::Nowrap;
562 let mut element = Inline::new(
563 state,
564 links.clone(),
565 highlights.clone(),
566 self.link_click_handler.clone(),
567 )
568 .selection_source(source_state.clone(), source_range.clone())
569 .range_backgrounds(slice_ranges(
570 backgrounds,
571 source_range.start,
572 source_range.end,
573 |range, color| (range, *color),
574 ))
575 .reveal(
576 reveal
577 .as_ref()
578 .filter(|_| reveal_fragment == Some(fragment_ix))
579 .map(|reveal| reveal.clamp(source_range.start, source_range.end)),
580 )
581 .text_style(fragment_style.clone())
582 .selection_bounds(Bounds::new(
583 point(bounds.left(), bounds.top() + selection_bounds.top()),
584 size(bounds.size.width, selection_bounds.size.height),
585 ))
586 .paint_origin(bounds.origin + origin + point(padding, Pixels::ZERO))
587 .into_any_element();
588 // The `Inline` is its own layout root, with no box around
589 // it: its text measures with the window's text style, so
590 // the fragment's style is pushed for the layout.
591 window.with_rem_size(Some(typography.rem_size), |window| {
592 window.with_text_style(
593 Some(fragment_style.subtract(&Default::default())),
594 |window| {
595 element.prepaint_as_root(
596 bounds.origin + origin + point(padding, Pixels::ZERO),
597 size(
598 AvailableSpace::Definite(
599 fragment_size.width - padding * 2.,
600 ),
601 AvailableSpace::Definite(fragment_size.height),
602 ),
603 window,
604 cx,
605 );
606 },
607 );
608 });
609 elements.push((element, background));
610 }
611 PositionedFragment::Image {
612 item_ix,
613 origin,
614 size: fragment_size,
615 } => {
616 let InlineFlowItem::Image {
617 source,
618 link,
619 title,
620 ..
621 } = &self.items[*item_ix]
622 else {
623 continue;
624 };
625 let (origin, fragment_size) = (*origin, *fragment_size);
626 let mut element = Self::image_element(
627 elements.len(),
628 source,
629 link,
630 title.as_str(),
631 fragment_size,
632 self.link_click_handler.clone(),
633 );
634 element.prepaint_as_root(
635 bounds.origin + origin,
636 size(
637 AvailableSpace::Definite(fragment_size.width),
638 AvailableSpace::Definite(fragment_size.height),
639 ),
640 window,
641 cx,
642 );
643 elements.push((element, None));
644 }
645 }
646 }
647
648 frame_state
649 .borrow_mut()
650 .fragment_states
651 .truncate(text_fragment_count);
652
653 elements
654 }
655
656 fn paint(
657 &mut self,
658 _id: Option<&GlobalElementId>,
659 _inspector_id: Option<&InspectorElementId>,
660 _bounds: Bounds<Pixels>,
661 _request_layout: &mut Self::RequestLayoutState,
662 prepaint: &mut Self::PrepaintState,
663 window: &mut Window,
664 cx: &mut App,
665 ) {
666 let preserve_selection = crate::GlobalState::global(cx)
667 .text_view_state()
668 .is_some_and(|view| view.read(cx).preserve_inline_selection);
669 for item in &self.items {
670 if !preserve_selection
671 && let InlineFlowItem::Text { state, .. } = item
672 && let Ok(mut state) = state.lock()
673 {
674 state.selection = None;
675 }
676 }
677 let radius = crate::Theme::global(cx).tokens.radius.sm;
678 for (element, background) in prepaint {
679 if let Some((bounds, color)) = background {
680 window.paint_quad(gpui::fill(*bounds, *color).corner_radii(radius));
681 }
682 element.paint(window, cx);
683 }
684 }
685}
686
687impl From<&InlineFlowItem> for MeasureItem {
688 fn from(item: &InlineFlowItem) -> Self {
689 match item {
690 InlineFlowItem::Object {
691 text,
692 id,
693 renderer,
694 style,
695 ..
696 } => Self::Object {
697 text: text.clone(),
698 id: *id,
699 renderer: renderer.clone(),
700 style: *style,
701 },
702 InlineFlowItem::Text {
703 state: _,
704 text,
705 links,
706 highlights,
707 ..
708 } => MeasureItem::Text {
709 text: text.clone(),
710 links: links.clone(),
711 highlights: highlights.clone(),
712 },
713 InlineFlowItem::Image {
714 source,
715 width,
716 height,
717 ..
718 } => MeasureItem::Image {
719 source: source.clone(),
720 width: *width,
721 height: *height,
722 },
723 }
724 }
725}
726
727impl MeasureItem {
728 fn len(&self) -> usize {
729 match self {
730 MeasureItem::Text { text, .. } => text.len(),
731 MeasureItem::Image { .. } | MeasureItem::Object { .. } => IMAGE_LEN,
732 }
733 }
734
735 /// Whether `other` lays out the same as this item. An object is
736 /// rendered anew every frame, so a flow with one is never reused.
737 fn same_layout_input(&self, other: &Self) -> bool {
738 match (self, other) {
739 (
740 MeasureItem::Text {
741 text,
742 links,
743 highlights,
744 },
745 MeasureItem::Text {
746 text: other_text,
747 links: other_links,
748 highlights: other_highlights,
749 },
750 ) => text == other_text && links == other_links && highlights == other_highlights,
751 (
752 MeasureItem::Image { width, height, .. },
753 MeasureItem::Image {
754 width: other_width,
755 height: other_height,
756 ..
757 },
758 ) => width == other_width && height == other_height,
759 _ => false,
760 }
761 }
762}
763
764/// Intrinsic width for table sizing, using the same objects and wrapping inputs as painting.
765pub(super) fn intrinsic_width(
766 items: &[InlineFlowItem],
767 window: &mut Window,
768 cx: &mut App,
769) -> Pixels {
770 let items = items.iter().map(MeasureItem::from).collect::<Vec<_>>();
771 let line_height = window.line_height();
772 let rem_size = window.rem_size();
773 let images = items
774 .iter()
775 .enumerate()
776 .map(|(ix, item)| match item {
777 MeasureItem::Image {
778 source,
779 width,
780 height,
781 } => Some(measure_image_size(
782 ix,
783 source,
784 *width,
785 *height,
786 line_height,
787 rem_size,
788 window,
789 cx,
790 )),
791 _ => None,
792 })
793 .collect::<Vec<_>>();
794 layout_flow(&items, &images, &window.text_style(), None, window, cx)
795 .size
796 .width
797}
798
799fn prepare_objects(
800 items: &[MeasureItem],
801 text_style: &TextStyle,
802 window: &mut Window,
803 cx: &mut App,
804) -> Vec<Option<MeasuredInlineObject>> {
805 items
806 .iter()
807 .map(|item| match item {
808 MeasureItem::Object {
809 text,
810 id,
811 renderer,
812 style,
813 } => {
814 let style = text_style.clone().highlight(*style);
815 let context = super::InlineRenderContext::new(
816 style.clone(),
817 style.font_size.to_pixels(window.rem_size()),
818 style.line_height_in_pixels(window.rem_size()),
819 window.rem_size(),
820 );
821 // Must be the id `InlineObject` paints under: GPUI asserts a
822 // stateful child (a plugin's HoverCard) sees the same id path
823 // in request_layout as in prepaint, and the element is laid
824 // out here but painted inside `InlineObject`.
825 Some(window.with_id(("inline-object", *id), |window| {
826 let element = window
827 .with_text_style(Some(style.subtract(&Default::default())), |window| {
828 renderer(&context, window, cx)
829 });
830 MeasuredInlineObject::measure(text, element, &style, window, cx)
831 }))
832 }
833 _ => None,
834 })
835 .collect()
836}
837
838fn layout_flow(
839 items: &[MeasureItem],
840 image_sizes: &[Option<Size<Pixels>>],
841 text_style: &TextStyle,
842 wrap_width: Option<Pixels>,
843 window: &mut Window,
844 cx: &mut App,
845) -> InlineFlowLayout {
846 let objects = prepare_objects(items, text_style, window, cx);
847 layout_measured_flow(
848 items,
849 image_sizes,
850 &objects,
851 text_style,
852 wrap_width,
853 window,
854 cx,
855 )
856}
857
858#[cfg(test)]
859thread_local! {
860 /// How many flows were laid out (wrapped and shaped) on this thread.
861 pub(super) static FLOW_LAYOUTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
862}
863
864fn layout_measured_flow(
865 items: &[MeasureItem],
866 image_sizes: &[Option<Size<Pixels>>],
867 prepared_objects: &[Option<MeasuredInlineObject>],
868 text_style: &TextStyle,
869 wrap_width: Option<Pixels>,
870 window: &mut Window,
871 _cx: &mut App,
872) -> InlineFlowLayout {
873 #[cfg(test)]
874 FLOW_LAYOUTS.with(|layouts| layouts.set(layouts.get() + 1));
875 let rem_size = window.rem_size();
876 let line_height = plain_line_height(text_style, rem_size, window);
877 let total_len = items.iter().map(MeasureItem::len).sum::<usize>();
878 if total_len == 0 {
879 return InlineFlowLayout::default();
880 }
881
882 let objects = prepared_objects
883 .iter()
884 .map(|object| object.clone().map(|object| object.fit_text(wrap_width)))
885 .collect::<Vec<_>>();
886 let line_ranges = line_ranges(items, image_sizes, &objects, text_style, wrap_width, window);
887 let font_size = text_style.font_size.to_pixels(rem_size);
888 let mut fragments = Vec::new();
889 let mut max_width = Pixels::ZERO;
890 let mut y = Pixels::ZERO;
891
892 for line_range in line_ranges {
893 let mut line_fragments = Vec::new();
894 let mut line_width = Pixels::ZERO;
895 // `LineLayout` is the metric source used by the text paint path. Its
896 // descent is normalized positive by native backends, whereas
897 // `FontMetrics::descent` remains signed. Start with the same shaped
898 // body metrics used below for every text fragment rather than mixing
899 // those two conventions through `TextSystem::baseline_offset`.
900 let body_runs = text_runs(1, text_style, &[]);
901 let body_line = shape_line(" ".into(), font_size, &body_runs, window);
902 let body_baseline = centered_baseline(&body_line, line_height);
903 // Like a plain text line, the body line box is the line height even
904 // when the font's glyphs are taller; runs may overflow it as far as
905 // body glyphs do.
906 let body_overflow_above = (body_line.ascent - body_baseline).max(Pixels::ZERO);
907 let body_overflow_below =
908 (body_line.descent - (line_height - body_baseline)).max(Pixels::ZERO);
909 let mut line_ascent = body_baseline;
910 let mut line_descent = line_height - body_baseline;
911 let mut item_start = 0;
912
913 for (item_ix, item) in items.iter().enumerate() {
914 let item_end = item_start + item.len();
915 if item_end <= line_range.start {
916 item_start = item_end;
917 continue;
918 }
919 if item_start >= line_range.end {
920 break;
921 }
922
923 match item {
924 MeasureItem::Text {
925 text,
926 links,
927 highlights,
928 } => {
929 let local_start = line_range.start.max(item_start) - item_start;
930 let local_end = line_range.end.min(item_end) - item_start;
931 for (segment, scale) in text_size_ranges(text.len(), highlights) {
932 let start = local_start.max(segment.start);
933 let end = local_end.min(segment.end);
934 if start >= end {
935 continue;
936 }
937 let subtext = SharedString::from(text[start..end].to_string());
938 let mut highlights =
939 slice_ranges(highlights, start, end, |range, style| {
940 (range, style.clone())
941 });
942 let links =
943 slice_ranges(links, start, end, |range, link| (range, link.clone()));
944 let runs = text_runs(subtext.len(), text_style, &highlights);
945 let segment_font_size = font_size * scale;
946 let shaped_line =
947 shape_line(subtext.clone(), segment_font_size, &runs, window);
948 let is_code = highlights.iter().any(|(_, h)| h.font_size_scale.is_some());
949 let padding = if is_code {
950 px(INLINE_CODE_PADDING * 2.)
951 } else {
952 Pixels::ZERO
953 };
954 let width = shaped_line.width() + padding;
955 // Measure the run by its glyph box. The body strut already
956 // carries the line's leading, so a run only has to fit its
957 // glyphs: leading of its own would make a smaller or
958 // differently proportioned run, such as inline code, push
959 // its line taller than a plain one. Positioning grows the
960 // box back to the line. The compact code background is
961 // painted independently.
962 let glyph_size = size(width, shaped_line.ascent + shaped_line.descent);
963 let baseline = shaped_line.ascent;
964 let code_background = is_code
965 .then(|| {
966 code_background(
967 &shaped_line,
968 &runs,
969 segment_font_size,
970 &mut highlights,
971 glyph_size,
972 baseline,
973 window,
974 )
975 })
976 .flatten();
977 line_ascent = line_ascent.max(baseline - body_overflow_above);
978 line_descent =
979 line_descent.max(glyph_size.height - baseline - body_overflow_below);
980 line_width += width;
981 line_fragments.push(LineFragmentLayout {
982 item_ix,
983 kind: LineFragmentKind::Text {
984 font_size: segment_font_size,
985 text: subtext,
986 links,
987 highlights,
988 code_background,
989 },
990 size: glyph_size,
991 source_range: start..end,
992 baseline: baseline,
993 });
994 }
995 }
996 MeasureItem::Object { .. } => {
997 let object = objects[item_ix].as_ref().unwrap().clone();
998 let metrics = object.metrics;
999 line_ascent = line_ascent.max(metrics.baseline);
1000 line_descent = line_descent.max(metrics.size.height - metrics.baseline);
1001 line_width += metrics.size.width;
1002 line_fragments.push(LineFragmentLayout {
1003 item_ix,
1004 kind: LineFragmentKind::Object(Box::new(object)),
1005 size: metrics.size,
1006 source_range: 0..IMAGE_LEN,
1007 baseline: metrics.baseline,
1008 });
1009 }
1010 MeasureItem::Image { .. } => {
1011 if line_range.start <= item_start && item_end <= line_range.end {
1012 let size = image_sizes[item_ix]
1013 .expect("image size should be measured before layout");
1014 line_width += size.width;
1015 let baseline = (size.height / 2. + body_baseline - line_height / 2.)
1016 .max(Pixels::ZERO)
1017 .min(size.height);
1018 line_ascent = line_ascent.max(baseline);
1019 line_descent = line_descent.max(size.height - baseline);
1020 line_fragments.push(LineFragmentLayout {
1021 item_ix,
1022 kind: LineFragmentKind::Image,
1023 size,
1024 source_range: 0..IMAGE_LEN,
1025 baseline: baseline,
1026 });
1027 }
1028 }
1029 }
1030
1031 item_start = item_end;
1032 }
1033
1034 let mut x = Pixels::ZERO;
1035 for mut fragment in line_fragments {
1036 // Give a text run's glyph box equal leading on both sides, as
1037 // much as the line allows: its glyphs are painted centered in the
1038 // box, so this keeps them on the line's baseline, and a body run
1039 // gets exactly the line box. The leading is negative where the
1040 // glyphs overflow the line, as a plain text line's do.
1041 let leading = match fragment.kind {
1042 LineFragmentKind::Text { .. } => (line_ascent - fragment.baseline)
1043 .min(line_descent - (fragment.size.height - fragment.baseline))
1044 .max(-fragment.size.height / 2.),
1045 _ => Pixels::ZERO,
1046 };
1047 fragment.size.height += leading * 2.;
1048 fragment.baseline += leading;
1049 let origin = point(x, y + line_ascent - fragment.baseline);
1050 let selection_bounds = Bounds::new(
1051 point(x, y),
1052 size(fragment.size.width, line_ascent + line_descent),
1053 );
1054 let positioned = match fragment.kind {
1055 LineFragmentKind::Object(object) => PositionedFragment::Object {
1056 item_ix: fragment.item_ix,
1057 origin,
1058 object,
1059 selection_bounds,
1060 },
1061 LineFragmentKind::Text {
1062 font_size,
1063 text,
1064 links,
1065 highlights,
1066 code_background,
1067 } => PositionedFragment::Text {
1068 item_ix: fragment.item_ix,
1069 origin,
1070 size: fragment.size,
1071 source_range: fragment.source_range,
1072 selection_bounds,
1073 font_size,
1074 text,
1075 links,
1076 highlights,
1077 code_background: code_background.map(|(background, color)| {
1078 (
1079 Bounds::new(
1080 origin + point(Pixels::ZERO, leading) + background.origin,
1081 background.size,
1082 ),
1083 color,
1084 )
1085 }),
1086 },
1087 LineFragmentKind::Image => PositionedFragment::Image {
1088 item_ix: fragment.item_ix,
1089 origin,
1090 size: fragment.size,
1091 },
1092 };
1093 x += fragment.size.width;
1094 fragments.push(positioned);
1095 }
1096
1097 max_width = max_width.max(line_width);
1098 y += line_ascent + line_descent;
1099 }
1100
1101 InlineFlowLayout {
1102 fragments,
1103 size: size(max_width, y),
1104 wrap_width,
1105 }
1106}
1107
1108/// The rounded box behind a code span, relative to the fragment: centered on
1109/// the capital-height body of the text, with the descender room shared
1110/// between both sides instead of added only below. Takes the background
1111/// color out of `highlights`, so the text does not paint it a second time
1112/// at the full line height.
1113fn code_background(
1114 shaped_line: &ShapedLine,
1115 runs: &[TextRun],
1116 font_size: Pixels,
1117 highlights: &mut [(Range<usize>, InlineHighlight)],
1118 fragment_size: Size<Pixels>,
1119 baseline: Pixels,
1120 window: &Window,
1121) -> Option<(Bounds<Pixels>, Hsla)> {
1122 let cap_height = runs
1123 .iter()
1124 .map(|run| {
1125 let font = window.text_system().resolve_font(&run.font);
1126 window.text_system().cap_height(font, font_size)
1127 })
1128 .fold(Pixels::ZERO, Pixels::max);
1129 let vertical_padding = font_size * 0.125 + shaped_line.descent / 2.;
1130 let color = highlights
1131 .iter()
1132 .find_map(|(_, h)| h.style.background_color);
1133 for (_, highlight) in highlights.iter_mut() {
1134 highlight.style.background_color = None;
1135 }
1136 color.map(|color| {
1137 (
1138 Bounds::new(
1139 point(Pixels::ZERO, baseline - cap_height - vertical_padding),
1140 size(fragment_size.width, cap_height + vertical_padding * 2.),
1141 ),
1142 color,
1143 )
1144 })
1145}
1146
1147fn line_ranges(
1148 items: &[MeasureItem],
1149 image_sizes: &[Option<Size<Pixels>>],
1150 objects: &[Option<MeasuredInlineObject>],
1151 text_style: &TextStyle,
1152 wrap_width: Option<Pixels>,
1153 window: &mut Window,
1154) -> Vec<Range<usize>> {
1155 let total_len = items.iter().map(MeasureItem::len).sum::<usize>();
1156 let mut hard_lines = Vec::new();
1157 let mut line_start = 0;
1158 let mut item_start = 0;
1159
1160 for item in items {
1161 if let MeasureItem::Text { text, .. } = item {
1162 for (newline, _) in text.match_indices('\n') {
1163 let newline = item_start + newline;
1164 hard_lines.push(line_start..newline);
1165 line_start = newline + 1;
1166 }
1167 }
1168 item_start += item.len();
1169 }
1170 hard_lines.push(line_start..total_len);
1171
1172 let Some(wrap_width) = wrap_width else {
1173 return hard_lines;
1174 };
1175 let rem_size = window.rem_size();
1176 let font_size = text_style.font_size.to_pixels(rem_size);
1177 let mut wrapper = window
1178 .text_system()
1179 .line_wrapper(text_style.font(), font_size);
1180 let mut ranges = Vec::new();
1181
1182 for hard_line in hard_lines {
1183 let mut item_start = 0;
1184 let mut wrap_fragments = Vec::new();
1185 for (ix, item) in items.iter().enumerate() {
1186 let item_end = item_start + item.len();
1187 if item_end > hard_line.start && item_start < hard_line.end {
1188 match item {
1189 MeasureItem::Text {
1190 text, highlights, ..
1191 } => {
1192 let start = hard_line.start.max(item_start) - item_start;
1193 let end = hard_line.end.min(item_end) - item_start;
1194 if start < end {
1195 push_text_wrap_fragments(
1196 &mut wrap_fragments,
1197 text,
1198 highlights,
1199 start..end,
1200 text_style,
1201 wrap_width,
1202 window,
1203 );
1204 }
1205 }
1206 MeasureItem::Object { .. } => {
1207 wrap_fragments.push(WrapLineFragment::element(
1208 objects[ix].as_ref().unwrap().metrics.size.width,
1209 IMAGE_LEN,
1210 ));
1211 }
1212 MeasureItem::Image { .. } => {
1213 if hard_line.start <= item_start && item_end <= hard_line.end {
1214 wrap_fragments.push(WrapLineFragment::element(
1215 image_sizes[ix]
1216 .expect("image size should be measured before wrapping")
1217 .width,
1218 IMAGE_LEN,
1219 ));
1220 }
1221 }
1222 }
1223 }
1224 item_start = item_end;
1225 }
1226
1227 // The wrapper sums per-character widths, which can be narrower than the
1228 // shaped run (CoreText sets an isolated full-width `,` at half width).
1229 // Check each line against the shaped spans and re-wrap it tighter when
1230 // it overflows, so the painted line never exceeds `wrap_width`.
1231 let spans = shaped_spans(items, image_sizes, objects, text_style, &hard_line, window);
1232 let mut start = hard_line.start;
1233 while start < hard_line.end {
1234 let rest = fragments_from(&wrap_fragments, start - hard_line.start);
1235 let mut budget = wrap_width;
1236 let mut end = next_wrap(&mut wrapper, &rest, budget, start, hard_line.end);
1237 let mut overflow = spans_width(&spans, start..end) - wrap_width;
1238 // Shrink the wrapper's budget by the overflow until it breaks earlier,
1239 // doubling the step while the break stays put. A single glyph wider
1240 // than the line keeps its line and overflows as before.
1241 let mut step = overflow;
1242 while overflow > Pixels::ZERO {
1243 budget -= step.max(px(0.5));
1244 if budget <= Pixels::ZERO {
1245 break;
1246 }
1247 let tighter = next_wrap(&mut wrapper, &rest, budget, start, hard_line.end);
1248 if tighter < end {
1249 end = tighter;
1250 overflow = spans_width(&spans, start..end) - wrap_width;
1251 step = overflow;
1252 } else {
1253 step = step * 2.;
1254 }
1255 }
1256 ranges.push(start..end);
1257 start = end;
1258 }
1259
1260 if hard_line.is_empty() {
1261 ranges.push(hard_line.clone());
1262 }
1263 }
1264
1265 ranges
1266}
1267
1268/// Where the first line of `fragments` (which start at byte `start`) wraps at
1269/// `wrap_width`; `end` when it all fits.
1270fn next_wrap(
1271 wrapper: &mut gpui::LineWrapperHandle,
1272 fragments: &[WrapLineFragment],
1273 wrap_width: Pixels,
1274 start: usize,
1275 end: usize,
1276) -> usize {
1277 wrapper
1278 .wrap_line(fragments, wrap_width, gpui::IndentAdjustment::SameIndent)
1279 .next()
1280 .map_or(end, |boundary| (start + boundary.ix).min(end))
1281}
1282
1283/// `fragments` with their first `skip` bytes dropped. Wrap boundaries fall on
1284/// character or element starts, so a text fragment is split on a char boundary.
1285fn fragments_from<'a>(
1286 fragments: &[WrapLineFragment<'a>],
1287 skip: usize,
1288) -> Vec<WrapLineFragment<'a>> {
1289 let mut offset = 0;
1290 let mut out = Vec::with_capacity(fragments.len());
1291 for fragment in fragments {
1292 let len = match fragment {
1293 WrapLineFragment::Text { text } => text.len(),
1294 WrapLineFragment::Element { len_utf8, .. } => *len_utf8,
1295 };
1296 if offset + len <= skip {
1297 offset += len;
1298 continue;
1299 }
1300 out.push(match fragment {
1301 WrapLineFragment::Text { text } => {
1302 WrapLineFragment::text(&text[skip.saturating_sub(offset)..])
1303 }
1304 WrapLineFragment::Element { width, len_utf8 } => {
1305 WrapLineFragment::element(*width, *len_utf8)
1306 }
1307 });
1308 offset += len;
1309 }
1310 out
1311}
1312
1313/// One run of a hard line as the renderer lays it out: text shaped once in
1314/// context, or an object / image of fixed width. Ranges are hard-line offsets.
1315enum ShapedSpan {
1316 Text {
1317 range: Range<usize>,
1318 line: Box<ShapedLine>,
1319 padding: Pixels,
1320 },
1321 Fixed {
1322 range: Range<usize>,
1323 width: Pixels,
1324 },
1325}
1326
1327fn shaped_spans(
1328 items: &[MeasureItem],
1329 image_sizes: &[Option<Size<Pixels>>],
1330 objects: &[Option<MeasuredInlineObject>],
1331 text_style: &TextStyle,
1332 hard_line: &Range<usize>,
1333 window: &mut Window,
1334) -> Vec<ShapedSpan> {
1335 let font_size = text_style.font_size.to_pixels(window.rem_size());
1336 let mut spans = Vec::new();
1337 let mut item_start = 0;
1338 for (ix, item) in items.iter().enumerate() {
1339 let item_end = item_start + item.len();
1340 if item_end > hard_line.start && item_start < hard_line.end {
1341 match item {
1342 MeasureItem::Text {
1343 text, highlights, ..
1344 } => {
1345 let local_start = hard_line.start.max(item_start) - item_start;
1346 let local_end = hard_line.end.min(item_end) - item_start;
1347 for (segment, scale) in text_size_ranges(text.len(), highlights) {
1348 let start = local_start.max(segment.start);
1349 let end = local_end.min(segment.end);
1350 if start >= end {
1351 continue;
1352 }
1353 let highlights = slice_ranges(highlights, start, end, |range, style| {
1354 (range, style.clone())
1355 });
1356 let runs = text_runs(end - start, text_style, &highlights);
1357 let line = Box::new(shape_line(
1358 SharedString::from(text[start..end].to_string()),
1359 font_size * scale,
1360 &runs,
1361 window,
1362 ));
1363 let padding = if highlights.iter().any(|(_, h)| h.font_size_scale.is_some())
1364 {
1365 px(INLINE_CODE_PADDING * 2.)
1366 } else {
1367 Pixels::ZERO
1368 };
1369 spans.push(ShapedSpan::Text {
1370 range: item_start + start..item_start + end,
1371 line,
1372 padding,
1373 });
1374 }
1375 }
1376 MeasureItem::Object { .. } => spans.push(ShapedSpan::Fixed {
1377 range: item_start..item_end,
1378 width: objects[ix].as_ref().unwrap().metrics.size.width,
1379 }),
1380 MeasureItem::Image { .. } => {
1381 if let Some(size) = image_sizes[ix] {
1382 spans.push(ShapedSpan::Fixed {
1383 range: item_start..item_end,
1384 width: size.width,
1385 });
1386 }
1387 }
1388 }
1389 }
1390 item_start = item_end;
1391 }
1392 spans
1393}
1394
1395/// Painted width of `range`: in-context glyph advances of the shaped spans it
1396/// covers, plus the fixed spans that lie inside it.
1397fn spans_width(spans: &[ShapedSpan], range: Range<usize>) -> Pixels {
1398 spans
1399 .iter()
1400 .map(|span| match span {
1401 ShapedSpan::Text {
1402 range: span_range,
1403 line,
1404 padding,
1405 } => {
1406 let start = range.start.max(span_range.start);
1407 let end = range.end.min(span_range.end);
1408 if start >= end {
1409 return Pixels::ZERO;
1410 }
1411 line.x_for_index(end - span_range.start)
1412 - line.x_for_index(start - span_range.start)
1413 + *padding
1414 }
1415 ShapedSpan::Fixed {
1416 range: span_range,
1417 width,
1418 } => {
1419 if range.start <= span_range.start && span_range.end <= range.end {
1420 *width
1421 } else {
1422 Pixels::ZERO
1423 }
1424 }
1425 })
1426 .sum()
1427}
1428
1429/// Appends the wrap fragments for `range` of `text`. The line wrapper
1430/// measures text fragments in the body font, so a span whose highlight sets
1431/// another family is shaped with the same run the renderer uses and enters
1432/// the wrapper as measured elements. Oversized spans retain word boundaries;
1433/// oversized words can break at grapheme boundaries without splitting Unicode.
1434fn push_text_wrap_fragments<'a>(
1435 fragments: &mut Vec<WrapLineFragment<'a>>,
1436 text: &'a str,
1437 highlights: &[(Range<usize>, InlineHighlight)],
1438 range: Range<usize>,
1439 text_style: &TextStyle,
1440 wrap_width: Pixels,
1441 window: &mut Window,
1442) {
1443 let font_size = text_style.font_size.to_pixels(window.rem_size());
1444 let mut cursor = range.start;
1445 for (highlight_range, highlight) in highlights {
1446 if highlight.font_family.is_none() {
1447 continue;
1448 }
1449 let start = highlight_range.start.max(cursor);
1450 let end = highlight_range.end.min(range.end);
1451 if start >= end {
1452 continue;
1453 }
1454 if cursor < start {
1455 fragments.push(WrapLineFragment::text(&text[cursor..start]));
1456 }
1457 let span = &text[start..end];
1458 let measure = |text: &str| {
1459 let runs = text_runs(
1460 text.len(),
1461 text_style,
1462 &[(0..text.len(), highlight.clone())],
1463 );
1464 window
1465 .text_system()
1466 .layout_line(
1467 text,
1468 font_size * highlight.font_size_scale.unwrap_or(1.),
1469 &runs,
1470 None,
1471 )
1472 .width
1473 };
1474 let padding = if highlight.font_size_scale.is_some() {
1475 px(INLINE_CODE_PADDING * 2.)
1476 } else {
1477 Pixels::ZERO
1478 };
1479 let width = measure(span) + padding;
1480 if width <= wrap_width {
1481 fragments.push(WrapLineFragment::element(width, span.len()));
1482 } else {
1483 for word in span.split_word_bounds() {
1484 let width = measure(word) + padding;
1485 if width <= wrap_width {
1486 fragments.push(WrapLineFragment::element(width, word.len()));
1487 } else {
1488 for grapheme in word.graphemes(true) {
1489 fragments.push(WrapLineFragment::element(
1490 measure(grapheme) + padding,
1491 grapheme.len(),
1492 ));
1493 }
1494 }
1495 }
1496 }
1497 cursor = end;
1498 }
1499 if cursor < range.end {
1500 fragments.push(WrapLineFragment::text(&text[cursor..range.end]));
1501 }
1502}
1503
1504#[allow(clippy::too_many_arguments)]
1505fn measure_image_size(
1506 ix: usize,
1507 source: &ImageSource,
1508 width: Option<DefiniteLength>,
1509 height: Option<DefiniteLength>,
1510 line_height: Pixels,
1511 rem_size: Pixels,
1512 window: &mut Window,
1513 cx: &mut App,
1514) -> Size<Pixels> {
1515 let intrinsic_size = if width.is_some() && height.is_some() {
1516 None
1517 } else {
1518 intrinsic_image_size(ix, source, width, height, window, cx)
1519 };
1520 image_size(width, height, intrinsic_size, line_height, rem_size)
1521}
1522
1523fn intrinsic_image_size(
1524 ix: usize,
1525 source: &ImageSource,
1526 width: Option<DefiniteLength>,
1527 height: Option<DefiniteLength>,
1528 window: &mut Window,
1529 cx: &mut App,
1530) -> Option<Size<Pixels>> {
1531 let mut element = img(source.clone())
1532 .id(ix)
1533 .object_fit(ObjectFit::Contain)
1534 .max_w(relative(1.))
1535 .when_some(width, |this, width| this.w(width))
1536 .when_some(height, |this, height| this.h(height))
1537 .into_any_element();
1538 let measured_size = element.layout_as_root(AvailableSpace::min_size(), window, cx);
1539
1540 if measured_size.width <= Pixels::ZERO || measured_size.height <= Pixels::ZERO {
1541 None
1542 } else {
1543 Some(measured_size)
1544 }
1545}
1546
1547fn image_size(
1548 width: Option<DefiniteLength>,
1549 height: Option<DefiniteLength>,
1550 intrinsic_size: Option<Size<Pixels>>,
1551 line_height: Pixels,
1552 rem_size: Pixels,
1553) -> Size<Pixels> {
1554 let base_size = AbsoluteLength::Pixels(line_height);
1555 match (width, height) {
1556 (Some(width), Some(height)) => size(
1557 width.to_pixels(base_size, rem_size),
1558 height.to_pixels(base_size, rem_size),
1559 ),
1560 (Some(width), None) => {
1561 let width = width.to_pixels(base_size, rem_size);
1562 let height = intrinsic_size
1563 .and_then(|intrinsic_size| {
1564 (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO)
1565 .then(|| width * (intrinsic_size.height / intrinsic_size.width))
1566 })
1567 .unwrap_or(line_height);
1568 size(width, height)
1569 }
1570 (None, Some(height)) => {
1571 let height = height.to_pixels(base_size, rem_size);
1572 let width = intrinsic_size
1573 .and_then(|intrinsic_size| {
1574 (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO)
1575 .then(|| height * (intrinsic_size.width / intrinsic_size.height))
1576 })
1577 .unwrap_or(height);
1578 size(width, height)
1579 }
1580 (None, None) => inline_image_size_for_line(intrinsic_size, line_height),
1581 }
1582}
1583
1584fn inline_image_size_for_line(
1585 intrinsic_size: Option<Size<Pixels>>,
1586 line_height: Pixels,
1587) -> Size<Pixels> {
1588 let height = line_height * 0.75;
1589 let aspect_ratio = intrinsic_size
1590 .and_then(|intrinsic_size| {
1591 (intrinsic_size.width > Pixels::ZERO && intrinsic_size.height > Pixels::ZERO)
1592 .then(|| intrinsic_size.width / intrinsic_size.height)
1593 })
1594 .unwrap_or(1.);
1595
1596 size((height * aspect_ratio).max(px(1.)), height.max(px(1.)))
1597}
1598
1599fn shape_line(
1600 text: SharedString,
1601 font_size: Pixels,
1602 runs: &[TextRun],
1603 window: &mut Window,
1604) -> ShapedLine {
1605 window.text_system().shape_line(text, font_size, runs, None)
1606}
1607
1608/// The line height GPUI's text layout gives a plain line in `text_style`.
1609/// Unlike `Window::line_height`, it is not first rounded to a whole logical
1610/// pixel, which would make a flow line taller than a plain one.
1611fn plain_line_height(text_style: &TextStyle, rem_size: Pixels, window: &Window) -> Pixels {
1612 window.pixel_snap(
1613 text_style
1614 .line_height
1615 .to_pixels(text_style.font_size, rem_size),
1616 )
1617}
1618
1619/// Returns where GPUI text painting puts the baseline of `shaped_line` in a
1620/// box `line_height` tall: centered, even when the glyphs overflow the box.
1621/// `ShapedLine::descent` is positive; do not substitute the signed
1622/// `FontMetrics::descent` exposed by `TextSystem::baseline_offset` here.
1623fn centered_baseline(shaped_line: &ShapedLine, line_height: Pixels) -> Pixels {
1624 (line_height - shaped_line.ascent - shaped_line.descent) / 2. + shaped_line.ascent
1625}
1626
1627pub(super) fn slice_ranges<T, U>(
1628 ranges: &[(Range<usize>, T)],
1629 start: usize,
1630 end: usize,
1631 map: impl Fn(Range<usize>, &T) -> U,
1632) -> Vec<U> {
1633 ranges
1634 .iter()
1635 .filter_map(|(range, value)| {
1636 let clipped_start = range.start.max(start);
1637 let clipped_end = range.end.min(end);
1638 (clipped_start < clipped_end)
1639 .then(|| map((clipped_start - start)..(clipped_end - start), value))
1640 })
1641 .collect()
1642}
1643
1644#[cfg(test)]
1645mod tests {
1646 use super::*;
1647 use gpui::SharedUri;
1648
1649 mod frames {
1650 use super::super::FLOW_LAYOUTS;
1651 use crate::text::{TextView, TextViewState};
1652 use gpui::{
1653 AppContext as _, Context, Entity, IntoElement, ParentElement as _, Pixels, Render,
1654 Styled as _, TestAppContext, VisualTestContext, Window, div, px,
1655 };
1656
1657 struct Answer {
1658 state: Entity<TextViewState>,
1659 width: Pixels,
1660 }
1661
1662 impl Render for Answer {
1663 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
1664 div().w(self.width).child(TextView::new(&self.state))
1665 }
1666 }
1667
1668 fn draw(cx: &mut VisualTestContext) {
1669 cx.update(|window, cx| window.draw(cx).clear(cx));
1670 }
1671
1672 fn layouts() -> usize {
1673 FLOW_LAYOUTS.with(|layouts| layouts.get())
1674 }
1675
1676 /// Scrolling redraws every visible paragraph each frame; a flow whose
1677 /// text, style and width are unchanged has nothing to wrap or shape.
1678 #[gpui::test]
1679 fn an_unchanged_flow_is_not_laid_out_again(cx: &mut TestAppContext) {
1680 cx.update(crate::init);
1681 let (_, cx) = cx.add_window_view(|_, cx| Answer {
1682 state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)),
1683 width: px(300.),
1684 });
1685 cx.run_until_parked();
1686 draw(cx);
1687 let after_first_frame = layouts();
1688 assert!(after_first_frame >= 1, "the first frame lays the flow out");
1689
1690 for _ in 0..3 {
1691 draw(cx);
1692 }
1693
1694 assert_eq!(layouts(), after_first_frame, "a frame that changes nothing");
1695 }
1696
1697 #[gpui::test]
1698 fn a_flow_is_laid_out_again_at_another_width(cx: &mut TestAppContext) {
1699 cx.update(crate::init);
1700 let (answer, cx) = cx.add_window_view(|_, cx| Answer {
1701 state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)),
1702 width: px(300.),
1703 });
1704 cx.run_until_parked();
1705 draw(cx);
1706 let before = layouts();
1707
1708 answer.update(cx, |answer, _| answer.width = px(120.));
1709 draw(cx);
1710
1711 assert!(layouts() > before, "a narrower flow wraps differently");
1712 }
1713
1714 #[gpui::test]
1715 fn a_flow_is_laid_out_again_when_its_text_changes(cx: &mut TestAppContext) {
1716 cx.update(crate::init);
1717 let (answer, cx) = cx.add_window_view(|_, cx| Answer {
1718 state: cx.new(|cx| TextViewState::markdown("Call `foo` now.", cx)),
1719 width: px(300.),
1720 });
1721 cx.run_until_parked();
1722 draw(cx);
1723 let before = layouts();
1724
1725 answer.update(cx, |answer, cx| {
1726 answer.state.update(cx, |state, cx| {
1727 state.set_text("Call `foo` and `bar` now.", cx);
1728 })
1729 });
1730 cx.run_until_parked();
1731 draw(cx);
1732
1733 assert!(layouts() > before, "a new text has a new layout");
1734 }
1735 }
1736
1737 #[test]
1738 fn atomic_objects_wrap_and_share_a_baseline_at_multiple_font_sizes() {
1739 use super::super::inline::test_draw::in_prepaint;
1740 use super::super::inline::test_fonts::{BODY, WideMonoTextSystem};
1741 use gpui::TestApp;
1742 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
1743 in_prepaint(&mut app, |window, cx| {
1744 for scale in [1., 1.5, 2.] {
1745 let style = TextStyle {
1746 font_family: BODY.into(),
1747 font_size: px(16. * scale).into(),
1748 ..Default::default()
1749 };
1750 let items = vec![
1751 MeasureItem::Text {
1752 text: "中文 ".into(),
1753 links: vec![],
1754 highlights: vec![],
1755 },
1756 MeasureItem::Object {
1757 text: "x²".into(),
1758 id: 0,
1759 renderer: Arc::new(|_, _, _| None),
1760 style: Default::default(),
1761 },
1762 MeasureItem::Object {
1763 text: "y²".into(),
1764 id: 1,
1765 renderer: Arc::new(|_, _, _| None),
1766 style: Default::default(),
1767 },
1768 MeasureItem::Text {
1769 text: " English".into(),
1770 links: vec![],
1771 highlights: vec![],
1772 },
1773 ];
1774 for width in [1., 30., 80., 500.] {
1775 let layout = layout_flow(
1776 &items,
1777 &[None, None, None, None],
1778 &style,
1779 Some(px(width)),
1780 window,
1781 cx,
1782 );
1783 let objects: Vec<_> = layout
1784 .fragments
1785 .iter()
1786 .filter_map(|fragment| match fragment {
1787 PositionedFragment::Object { origin, object, .. } => {
1788 Some((origin, object))
1789 }
1790 _ => None,
1791 })
1792 .collect();
1793 assert_eq!(objects.len(), 2);
1794 for (origin, object) in &objects {
1795 assert!(object.metrics.size.width <= px(width));
1796 assert!(origin.y >= px(0.));
1797 assert!(origin.y + object.metrics.size.height <= layout.size.height);
1798 }
1799 if width == 500. {
1800 assert_eq!(
1801 objects[0].0.y + objects[0].1.metrics.baseline,
1802 objects[1].0.y + objects[1].1.metrics.baseline
1803 );
1804 }
1805 }
1806 }
1807 });
1808 }
1809
1810 #[test]
1811 fn inline_image_without_explicit_size_scales_intrinsic_ratio_to_line_height() {
1812 let line_height = px(20.);
1813 let intrinsic_size = size(px(160.), px(40.));
1814
1815 let measured = inline_image_size_for_line(Some(intrinsic_size), line_height);
1816
1817 assert_eq!(measured, size(px(60.), px(15.)));
1818 }
1819
1820 #[test]
1821 fn inline_image_without_intrinsic_size_uses_compact_square_fallback() {
1822 let measured = inline_image_size_for_line(None, px(20.));
1823
1824 assert_eq!(measured, size(px(15.), px(15.)));
1825 }
1826
1827 /// Line breaking must see the width of an inline code span in its own
1828 /// family. With a body-font-only wrapper the span below is measured at
1829 /// half its shaped width, the line is kept whole, and the flow reports a
1830 /// width past `wrap_width`.
1831 #[test]
1832 fn inline_code_near_the_wrap_width_does_not_overflow_the_flow() {
1833 use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
1834 use gpui::{AbsoluteLength, Empty, HighlightStyle, TestApp};
1835
1836 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
1837 let mut window = app.open_window(|_, _| Empty);
1838
1839 let font_size = px(10.);
1840 let text_style = TextStyle {
1841 font_family: SharedString::from(BODY),
1842 font_size: AbsoluteLength::Pixels(font_size),
1843 ..Default::default()
1844 };
1845 let lead = SharedString::from("See ");
1846 let tail_text = " with code_span_here end";
1847 let code = tail_text.find("code_span_here").unwrap();
1848 let code_range = code..code + "code_span_here".len();
1849 let code_highlight = InlineHighlight {
1850 style: HighlightStyle::default(),
1851 font_family: Some(SharedString::from(MONO)),
1852 font_size_scale: None,
1853 };
1854 let items = vec![
1855 MeasureItem::Text {
1856 text: lead.clone(),
1857 links: vec![],
1858 highlights: vec![],
1859 },
1860 MeasureItem::Image {
1861 source: SharedUri::from("https://example.com/badge.png").into(),
1862 width: None,
1863 height: None,
1864 },
1865 MeasureItem::Text {
1866 text: SharedString::from(tail_text),
1867 links: vec![],
1868 highlights: vec![(code_range.clone(), code_highlight)],
1869 },
1870 ];
1871 let image_size = size(px(10.), px(10.));
1872 let image_sizes = vec![None, Some(image_size), None];
1873 // Body text, the image and the mono span fill the wrap width exactly;
1874 // the trailing "end" only fits if the span is under-measured.
1875 let wrap_width = WideMonoTextSystem::width_of("See with ", BODY, font_size)
1876 + image_size.width
1877 + WideMonoTextSystem::width_of("code_span_here", MONO, font_size);
1878
1879 let layout = window.update(|_, window, cx| {
1880 layout_flow(
1881 &items,
1882 &image_sizes,
1883 &text_style,
1884 Some(wrap_width),
1885 window,
1886 cx,
1887 )
1888 });
1889
1890 assert!(
1891 layout.size.width <= wrap_width,
1892 "flow width {:?} exceeds wrap width {:?}",
1893 layout.size.width,
1894 wrap_width
1895 );
1896 let mono_fragment_width = layout
1897 .fragments
1898 .iter()
1899 .find_map(|fragment| match fragment {
1900 PositionedFragment::Text { text, size, .. } if text.contains("code_span_here") => {
1901 Some(size.width)
1902 }
1903 _ => None,
1904 })
1905 .expect("the code span is laid out as a text fragment");
1906 assert!(
1907 mono_fragment_width >= WideMonoTextSystem::width_of("code_span_here", MONO, font_size),
1908 "the code span fragment is shaped in the mono family"
1909 );
1910 // The image sits vertically centred in its line, so line membership is
1911 // read off the text fragments only.
1912 let text_lines = layout
1913 .fragments
1914 .iter()
1915 .filter_map(|fragment| match fragment {
1916 PositionedFragment::Text { text, origin, .. } => Some((text.trim(), origin.y)),
1917 PositionedFragment::Image { .. } | PositionedFragment::Object { .. } => None,
1918 })
1919 .collect::<Vec<_>>();
1920 let first_y = text_lines[0].1;
1921 assert!(
1922 text_lines
1923 .iter()
1924 .any(|(text, y)| text.contains("code_span_here") && *y == first_y),
1925 "the span stays on the first line: {text_lines:?}"
1926 );
1927 assert!(
1928 text_lines
1929 .iter()
1930 .any(|(text, y)| *text == "end" && *y > first_y),
1931 "the trailing word wraps to a second line: {text_lines:?}"
1932 );
1933 }
1934 #[test]
1935 fn long_inline_code_wraps_in_mixed_flow() {
1936 use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
1937 use gpui::{Empty, TestApp};
1938 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
1939 let mut window = app.open_window(|_, _| Empty);
1940 let style = TextStyle {
1941 font_family: BODY.into(),
1942 font_size: AbsoluteLength::Pixels(px(10.)),
1943 ..Default::default()
1944 };
1945 for text in [
1946 "one two three four five six",
1947 "very_long_unbroken_identifier",
1948 "你好世界你好世界你好世界",
1949 "e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}",
1950 ] {
1951 let items = vec![
1952 MeasureItem::Image {
1953 source: SharedUri::from("https://example.com/icon.png").into(),
1954 width: None,
1955 height: None,
1956 },
1957 MeasureItem::Text {
1958 text: text.into(),
1959 links: vec![],
1960 highlights: vec![(
1961 0..text.len(),
1962 InlineHighlight {
1963 font_family: Some(MONO.into()),
1964 ..Default::default()
1965 },
1966 )],
1967 },
1968 ];
1969 let image_sizes = vec![Some(size(px(10.), px(10.))), None];
1970 let layout = window.update(|_, window, cx| {
1971 layout_flow(&items, &image_sizes, &style, Some(px(100.)), window, cx)
1972 });
1973 assert!(layout.size.width <= px(100.), "{text:?}: {:?}", layout.size);
1974 let reconstructed: String = layout
1975 .fragments
1976 .iter()
1977 .filter_map(|fragment| match fragment {
1978 PositionedFragment::Text { text, .. } => Some(text.as_ref()),
1979 _ => None,
1980 })
1981 .collect();
1982 assert_eq!(reconstructed, text);
1983 }
1984 }
1985
1986 #[test]
1987 fn inline_code_line_is_as_tall_as_a_plain_line_when_glyphs_overflow_it() {
1988 use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
1989 use gpui::{Empty, TestApp};
1990
1991 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
1992 let mut window = app.open_window(|_, _| Empty);
1993 let style = TextStyle {
1994 font_family: BODY.into(),
1995 font_size: AbsoluteLength::Pixels(px(40.)),
1996 line_height: px(30.).into(),
1997 ..Default::default()
1998 };
1999 let items = vec![MeasureItem::Text {
2000 text: "a code z".into(),
2001 links: vec![],
2002 highlights: vec![(
2003 2..6,
2004 InlineHighlight {
2005 font_family: Some(MONO.into()),
2006 font_size_scale: Some(0.875),
2007 ..Default::default()
2008 },
2009 )],
2010 }];
2011 // The 40px glyphs are taller than the 30px line. A plain text line
2012 // keeps the line height and lets them overflow, so a line with
2013 // inline code must not grow to fit them.
2014 window.update(|_, window, cx| {
2015 let layout = layout_flow(&items, &[None], &style, None, window, cx);
2016 assert_eq!(layout.size.height, window.pixel_snap(px(30.)));
2017 });
2018 }
2019
2020 #[test]
2021 fn inline_code_size_is_relative_and_uses_the_native_body_baseline() {
2022 use super::super::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
2023 use gpui::{Empty, TestApp};
2024
2025 let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
2026 let mut window = app.open_window(|_, _| Empty);
2027 // These are the 16px body size and the example-markdown preview's
2028 // 1.25x/1.5x inherited text-size zooms.
2029 for body_size in [16., 20., 24.] {
2030 let style = TextStyle {
2031 font_family: BODY.into(),
2032 font_size: AbsoluteLength::Pixels(px(body_size)),
2033 ..Default::default()
2034 };
2035 let items = vec![MeasureItem::Text {
2036 text: "a code z".into(),
2037 links: vec![],
2038 highlights: vec![(
2039 2..6,
2040 InlineHighlight {
2041 font_family: Some(MONO.into()),
2042 font_size_scale: Some(0.875),
2043 ..Default::default()
2044 },
2045 )],
2046 }];
2047 window.update(|_, window, cx| {
2048 let layout = layout_flow(&items, &[None], &style, None, window, cx);
2049 let text_fragments = layout
2050 .fragments
2051 .iter()
2052 .filter_map(|fragment| match fragment {
2053 PositionedFragment::Text {
2054 text,
2055 font_size,
2056 origin,
2057 size,
2058 ..
2059 } => Some((text.as_ref(), *font_size, origin.y, *size)),
2060 _ => None,
2061 })
2062 .collect::<Vec<_>>();
2063 assert_eq!(text_fragments.len(), 3);
2064 assert_eq!(text_fragments[0].1, px(body_size));
2065 assert_eq!(text_fragments[1].0, "code");
2066 assert_eq!(text_fragments[1].1, px(body_size * 0.875));
2067 // The code run's box stays inside the line, so whatever it
2068 // paints over its box cannot reach a neighboring line.
2069 assert!(text_fragments[1].2 >= Pixels::ZERO);
2070 assert!(text_fragments[1].2 + text_fragments[1].3.height <= layout.size.height);
2071 assert_eq!(
2072 text_fragments[1].3.width,
2073 WideMonoTextSystem::width_of("code", MONO, px(body_size * 0.875))
2074 + px(INLINE_CODE_PADDING * 2.)
2075 );
2076
2077 // GPUI paints shaped lines with positive `LineLayout::descent`.
2078 // Derive the ordinary body glyph baseline directly from that
2079 // native-compatible shaped line, rather than `baseline_offset`,
2080 // whose FontMetrics descent is intentionally signed.
2081 let body_runs = text_runs(1, &style, &[]);
2082 let body_line = shape_line("a".into(), px(body_size), &body_runs, window);
2083 let body_line_height = plain_line_height(&style, window.rem_size(), window);
2084 let plain_body_baseline = (body_line_height - body_line.ascent - body_line.descent)
2085 / 2.
2086 + body_line.ascent;
2087 // The smaller code run fits inside the body line, so the
2088 // line must be exactly as tall as a plain one.
2089 assert_eq!(
2090 layout.size.height, body_line_height,
2091 "{body_size}px line height"
2092 );
2093 let mut painted_glyph_baseline =
2094 |fragment: &(&str, Pixels, Pixels, Size<Pixels>)| {
2095 let runs = if fragment.0 == "code" {
2096 text_runs(
2097 fragment.0.len(),
2098 &style,
2099 &[(
2100 0..fragment.0.len(),
2101 InlineHighlight {
2102 font_family: Some(MONO.into()),
2103 font_size_scale: Some(0.875),
2104 ..Default::default()
2105 },
2106 )],
2107 )
2108 } else {
2109 text_runs(fragment.0.len(), &style, &[])
2110 };
2111 let shaped = shape_line(fragment.0.into(), fragment.1, &runs, window);
2112 fragment.2
2113 + (fragment.3.height - shaped.ascent - shaped.descent) / 2.
2114 + shaped.ascent
2115 };
2116
2117 // `origin` is passed unchanged to Inline::paint_origin, so this
2118 // checks the first body glyph's painted row position, not only
2119 // the enclosing paragraph height. It must agree with a normal
2120 // body line and with the adjacent inline-code glyph baseline.
2121 assert_eq!(
2122 text_fragments[0].2,
2123 Pixels::ZERO,
2124 "{body_size}px body origin"
2125 );
2126 assert_eq!(
2127 painted_glyph_baseline(&text_fragments[0]),
2128 plain_body_baseline,
2129 "{body_size}px body glyph baseline"
2130 );
2131 assert_eq!(
2132 painted_glyph_baseline(&text_fragments[1]),
2133 plain_body_baseline,
2134 "{body_size}px code glyph baseline"
2135 );
2136 });
2137 }
2138 }
2139}