Skip to content

feat(gpui): open gaps of a set width inside styled text - #36

Open
nodelike wants to merge 4 commits into
sonorahq:masterfrom
nodelike:feat/text-gaps
Open

nodelike wants to merge 4 commits into
sonorahq:masterfrom
nodelike:feat/text-gaps

Conversation

@nodelike

Copy link
Copy Markdown
Contributor

Summary

  • StyledText::with_gaps([(byte_index, width)]) opens empty space of a given width before each byte index, without changing the text or its indices
  • a gap at a point where the line wraps stays at the start of the next row
  • TextLayout::gap_origin(index) returns where the gap was drawn, so the element can paint an icon or chip into it

We use it to put file icons and small chips inline in chat text without inserting placeholder characters into it.

Builds on #33 (letter spacing) and #35 (font scale); only the last commit is new here.

Checked on macOS (Apple silicon): cargo clippy --all-targets for gpui, gpui_macos, gpui_apple, gpui_wgpu and gpui_platform adds no warnings, and cargo test -p gpui --lib passes.

@coderabbitai

coderabbitai Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

Explain Change →

Summary

This change adds StyledText::with_gaps, which inserts empty space of a set width before given UTF-8 byte indices without changing the text. It adds TextLayout::gap_origin to return the drawing position of each gap, and adds FontScale and per-run scale and leading fields to support font scaling and gap layout.

Text styles and fonts now support font scaling. Styled text accepts gaps before UTF-8 byte indices, and text shaping and wrapped layout account for these gaps and per-run scale and leading values. Painting uses gap positions and optional run-specific font sizes. Tests cover gap positions, wrapping, and leading. Platform implementations and fixtures initialize the added fields.

Merge Risk: Moderate · up to 0194d

Gap-aware text layout is opt-in, so existing text is unaffected. However, gaps combined with start truncation can panic on Windows, and gap-only changes between frames can reuse stale layout. Fix the truncation remapping and the measurement identity before merging; the alignment, RTL and decoration issues are smaller edge cases.

Security architecture risk: Low · up to 0194d

Changing only the spaces reserved for inline content can leave later frames using outdated positions and dimensions. This is a bounded rendering-state issue; no expanded privilege or demonstrated security attack path was established.

Retained concerns

  • Low · reliability · inferred: Retained measurement identity omits gap configuration. With otherwise identical text and styles, changing gap indices or widths can transfer an incompatible prior layout into the new element. A matching-width measurement can then return the old geometry without processing the new gaps, leaving dimensions and gap-origin queries stale across frames.
Security review details

Security Blast Radius

  • inferred — The traced new inputs affect caller-selected text layout and rendering within the application process. No tenant, credential, service, or infrastructure authority transition was established along this path. Whether production callers derive these parameters from untrusted content remains unverified.

Trust Boundaries and Controls

  • observed — The new coordinate accessor reads the element’s existing layout cell and returns geometry after measurement and prepaint. It does not introduce an authorization decision or access another identity’s state in the inspected implementation.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

Critical · The Windows build breaks because Font gained two fields. · direct_write.rs:466-472

crates/gpui_windows/src/direct_write.rs:466-472
Critical · Functional Correctness · Quick win

The Windows build breaks because Font gained two fields.

Font now has the public fields letter_spacing and scale. This file was only partly updated (Line 1649). Two other places still use the old five-field shape:

  • Lines 466-472: make_font_from_font_collection destructures &Font { ref family, ref features, ref fallbacks, weight, style } without ... This gives error E0027, a pattern that does not mention all fields.
  • Lines 1818-1824: font_face_to_font builds Font { family, features, weight, style, fallbacks } and omits the two new fields. This gives error E0063, a missing struct field.

gpui_windows will not compile on Windows. The PR reports checks only on macOS. Other crates that construct or destructure Font may have the same problem. Search the workspace for them.

Proposed fix

         &Font {
             ref family,
             ref features,
             ref fallbacks,
             weight,
             style,
+            ..
         }: &Font,
     Some(Font {
         family: family_name.into(),
         features: FontFeatures::default(),
         weight: font_weight_from_dwrite(weight),
         style: font_style_from_dwrite(style),
         fallbacks: None,
+        letter_spacing: Default::default(),
+        scale: Default::default(),
     })

Also applies to: 1818-1824

Nitpick comments: 1

crates/gpui/src/text_system.rs: 1

1395-1400: Trivial · Performance & Scalability · Quick win

Keep letter_spacing and scale out of font identity.

Font derives Hash and Eq, so both new fields now take part in the font_ids_by_font key and in each platform's font cache.

  • In TextSystem::font_id, every distinct letter-spacing or scale value adds a cache entry.
  • In gpui_windows, font_to_font_id is keyed by Font. A cache miss calls select_and_cache_font, which pushes a new FontInfo and a new FontId for the same face. Animated letter spacing therefore grows fonts without bound and splits glyph-atlas entries.

Strip the two fields before the cache lookup and before the platform call:

fn font_id(&self, font: &Font) -> Result<FontId> {
    let key = Font { letter_spacing: Default::default(), scale: Default::default(), ..font.clone() };
    // use `key` for the font_ids_by_font lookup, insert and platform_text_system.font_id call
}

resolve_font still passes the original Font, so run data keeps the per-run values.

Comment on lines +531 to +534
pub fn with_gaps(mut self, gaps: impl IntoIterator<Item = (usize, Pixels)>) -> Self {
self.gaps = gaps.into_iter().collect();
self
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Stability & Availability · Quick win

Validate gap indices in with_gaps.

The doc comment says gaps must be sorted and on character boundaries, but nothing checks this. Other builders in this file use debug_assert!(is_char_boundary(..)).

A gap inside a multi-byte code point splits a TextRun inside that character:

  • shape_text_with_gaps cuts run_len_within_line at the gap.
  • The resulting FontRun length is not a char boundary.
  • AppleTextSystemState::layout_line calls text.split_at(run.len) and panics.
  • compute_wrap_boundaries slices the text with text[index..] and can also panic.

Unsorted input also breaks next_gap, which takes the first matching gap and not the smallest.

Drop invalid entries and sort the rest. Keep a debug_assert! so the mistake shows up in debug builds.

Proposed fix

--- "a/crates/gpui/src/elements/text.rs"
+++ "b/crates/gpui/src/elements/text.rs"
@@ -528,10 +528,16 @@
     /// its own inside the text there, such as an icon, at the place
     /// [`TextLayout::position_for_index`] gives for the index, less the width. The indices must
     /// be sorted and fall on character boundaries; the text and its indices stay as they were.
     pub fn with_gaps(mut self, gaps: impl IntoIterator<Item = (usize, Pixels)>) -> Self {
-        self.gaps = gaps.into_iter().collect();
+        let mut gaps: Vec<(usize, Pixels)> = gaps
+            .into_iter()
+            .inspect(|(index, _)| debug_assert!(self.text.is_char_boundary(*index)))
+            .filter(|(index, _)| self.text.is_char_boundary(*index))
+            .collect();
+        gaps.sort_by_key(|(index, _)| *index);
+        self.gaps = gaps.into();
         self
     }
 
     /// Set the text runs for this piece of text.
     pub fn with_runs(mut self, runs: Vec<TextRun>) -> Self {

Based on learnings: "When a computed UTF-8 byte offset is used as a text boundary for slicing, measuring, or cursor placement, first check whether it can fall inside a multi-byte code point."

Committable suggestion

IMPORTANT
Review the replacement and indentation, then test before committing.

Suggested change
pub fn with_gaps(mut self, gaps: impl IntoIterator<Item = (usize, Pixels)>) -> Self {
self.gaps = gaps.into_iter().collect();
self
}
pub fn with_gaps(mut self, gaps: impl IntoIterator<Item = (usize, Pixels)>) -> Self {
let mut gaps: Vec<(usize, Pixels)> = gaps
.into_iter()
.inspect(|(index, _)| debug_assert!(self.text.is_char_boundary(*index)))
.filter(|(index, _)| self.text.is_char_boundary(*index))
.collect();
gaps.sort_by_key(|(index, _)| *index);
self.gaps = gaps.into();
self
}

Source: Learnings

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

0194db6 sorts the gaps and drops any inside a character. Debug builds assert on those.

Comment on lines +795 to +804
let gap_at = |at: usize| gaps.iter().find(|(index, _)| *index == at);
let next_gap = gaps
.iter()
.map(|(index, _)| *index)
.find(|index| *index > run_start && *index < line_end);
let run_len_within_line = cmp::min(line_end - run_start, run.len)
.min(next_gap.map_or(usize::MAX, |gap| gap - run_start));
let leading = gap_at(run_start).map_or(LetterSpacing::default(), |(_, width)| {
LetterSpacing(*width / font_size)
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

Gaps on the third and later lines land at the wrong byte index.

gap_at and next_gap compare gap indices against run_start. run_start starts at the line_start that the caller passes to process_line. For the third and later lines, the caller computes line_start incorrectly (Lines 894-901). It adds the length of the current line, not the length of the previous line:

  • "a\nbbb\nc" has its third line at byte 6.
  • The loop passes 2 + 1 + 1 = 4.

Before this change only line_end - line_start mattered, so the error was harmless. Now a gap on any line after the second one is dropped or placed on the wrong run when the lines differ in length. The icon or chip then overlaps text.

Fix the line-start tracking:

Proposed fix

             line_start += first_line.len() + '\n'.len_utf8();
             process_line(
                 SharedString::new(second_line),
                 line_start,
                 line_start + second_line.len(),
             );
+            let mut previous_len = second_line.len();
             for line_text in split_lines {
-                line_start += line_text.len() + '\n'.len_utf8();
+                line_start += previous_len + '\n'.len_utf8();
                 process_line(
                     SharedString::new(line_text),
                     line_start,
                     line_start + line_text.len(),
                 );
+                previous_len = line_text.len();
             }

Add a test with a gap on a third line whose length differs from the second line.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in 0194db6, with a test for a gap on the third line.

@zxsleebu zxsleebu added macos changes the macOS backend rendering changes the scene, shaders or a renderer text changes text shaping, layout or rasterising windows changes the Windows backend labels Nov 15, 2026
HighlightStyle::font_scale and Font::scale work like CSS font-size in ems. The
scale rides on each FontRun and is applied once after shaping, as letter
spacing is, so every text system gives the same result.
The bidi paint path and both culling bounds now use a run's own font size,
as the left-to-right path does. Font resolution ignores letter spacing and
scale, which only line layout applies, so animating either no longer adds
a font per value to every cache keyed by Font. -0.0 now hashes like 0.0 for
both, and DirectWrite builds and reads a Font with the scale field.

Agent: Nostrade (claude 2.1.325, claude-opus-5-5, sikemux 0.6.1-nightly.2702, session 636c5d95-6ba1-4572-82e4-c052db75f17d, chat agent-c154176576e34c2d8430e4a6e717101b, host 03c112f7c38a48c2)
Agent-Signature: I9XunFi9sfQ5oDop+eEv58Te4tiUV6Sm5WCNz/rqPyydCjGZ3zlyV0/wlmtpTry3zSi147PEiy1Y52eIdXIXCQ
StyledText::with_gaps opens space before byte indices without changing the
text, kept at the start of a row that wraps there, and TextLayout::gap_origin
says where to draw into it.
Each line after the second started at the previous line's start plus
its own length, so gaps from the third line on landed in the wrong
place. Gaps given to StyledText::with_gaps are now sorted, and any
inside a character are dropped.

Agent: Nostrade (claude 2.1.325, claude-opus-5-5, sikemux 0.6.1-nightly.2702, session 636c5d95-6ba1-4572-82e4-c052db75f17d, chat agent-c154176576e34c2d8430e4a6e717101b, host 03c112f7c38a48c2)
Agent-Signature: AtEv8m9OmJQetFseIJML9Fn/xhxkW3o8X/uybqQ5a0rISrSksG0YC0+GQ0yi0+9xBK3cdvRWjf/jGtYaMvHZCg

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (2)

Minor · Include gap widths in the truncation decision. · text.rs:930-934

crates/gpui/src/elements/text.rs:930-934
Minor · Functional Correctness · Heavy lift

Include gap widths in the truncation decision.

If ungapped text fits but its gaps make it exceed truncate_width, this probe accepts the complete text. The later shaping call adds the gaps after truncation has been skipped. With WhiteSpace::Nowrap, the text overflows without an ellipsis.

Use gap-aware measurement and include gap widths in the truncation budget.

Minor · Keep the opening gap in final-row decoration endpoints. · line.rs:827-831

crates/gpui/src/text_system/line.rs:827-831
Minor · Functional Correctness · Quick win

Keep the opening gap in final-row decoration endpoints.

If a row wraps at a gap, the changed paint path starts its first glyph after that gap. These final endpoint calculations still subtract the full boundary glyph position. They omit the gap retained at the row start.

For a left-aligned final row with a 20px opening gap, underlines, strikethroughs and backgrounds end 20px early. Subtract the row origin before its gap, consistently with the changed wrap reset.

Also applies to: 1006-1010

&self,
text: SharedString,
runs: Option<Vec<TextRun>>,
gaps: Rc<[(usize, Pixels)]>,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

Include gaps in retained measurement identity.

If only a gap width or index changes between frames, TextMeasure::measures_as still returns true. The retained-layout path transfers the previous layouts, and the measurement callback can return their cached size without calling shape_text_with_gaps. Text and inline content then use stale positions.

Store gaps in TextMeasure and compare them in measures_as before reusing layouts.

text,
font_size,
&runs,
&gaps,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Stability & Availability · Heavy lift

Remap gap indices after start truncation, or the Windows text layout can panic.

When truncate_line removes the start of the text, shape_text_with_gaps still receives the original gap indices. For example, "aaébc" with a gap at byte 4 becomes "…ébc", where byte 4 is inside é. The text layout then splits a FontRun inside that character. On Windows, direct_write.rs slices the text by each run length (&text[utf8_offset..(utf8_offset + first_run.len)]), which panics on a non-boundary index.

Map each gap index through the truncation before shaping. Subtract the removed prefix length and add the affix length. Drop any gap that falls inside the removed prefix or does not land on a character boundary in the truncated text.

Source: Learnings

line_origin.y += line.size(line_height).height;
line_start_ix = line_end_ix + 1;
} else {
return Some(line_origin + line.gap_origin(index - line_start_ix, line_height)?);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

Apply text alignment to the returned gap origin.

If text is centered or right-aligned, painting offsets each row within its alignment width. This calculation adds only bounds.origin, so an icon drawn at gap_origin does not occupy the painted gap.

Include the same per-row alignment offset that painting uses.

Comment on lines +1266 to +1269
.filter(|(start, _)| glyph.index >= *start)
.map(|(_, width)| *width)
.sum();
glyph.position.x += opened;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Heavy lift

Apply leading gaps in visual order for bidirectional text.

The byte-index comparison moves a logical suffix to the right. A logical suffix need not be a visual suffix.

For the supplied RTL fixture, a 16px gap at byte 4 changes glyph positions from [30,20,10,0] to [30,20,26,16]. The glyphs overlap instead of leaving a 16px opening. bidi_lines derives advances from these positions, so painting does not correct the overlap.

Place the gap at its visual boundary and shift the appropriate visual glyphs.

@nodelike

Copy link
Copy Markdown
Contributor Author

The Windows build and the font identity nit are fixed underneath, in #35's 704770f.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

macos changes the macOS backend rendering changes the scene, shaders or a renderer text changes text shaping, layout or rasterising windows changes the Windows backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants