mirror of
https://github.com/penpot/penpot.git
synced 2026-11-26 21:00:32 +00:00
🐛 Fix not rendering & computing into layout trailing white spaces (#13127)
* 🐛 Keep trailing spaces in WASM text bounds Skia's longest_line() and line widths leave out the spaces at the end of a line, so auto-width texts lost their trailing spaces in the selrect, and the tight text bounds cut them off too. Fonts that draw a glyph for spaces, like Zilla Slab Highlight, showed the gap. - Measure auto-width text with max_intrinsic_width(), which keeps trailing spaces. - Extend each line's tight bounds with the rects of its whole range, trailing spaces included. Closes #12998 AI-assisted-by: claude-opus-5-5 * 🐛 Paint trailing spaces in WASM text Skia lays out the spaces at the end of a line but never paints them. Fonts that draw a glyph for spaces, like Zilla Slab Highlight, lost those glyphs on the WebGL renderer. - End each paragraph that ends in whitespace with a zero-size placeholder. The spaces are no longer trailing, so Skia measures and paints them with the right glyphs and paints. - Add it to the fill and stroke builders alike, so their layouts match. - Leave it out when it would wrap onto a line of its own in a fixed or auto-height box, which would add an empty line. A probe layout per paragraph decides this, cached per content version and box width. Closes #12998 AI-assisted-by: claude-opus-5-5
This commit is contained in:
parent
5fafca7665
commit
5aac5ab9ba
@ -3,11 +3,11 @@ use crate::{
|
||||
error::Result,
|
||||
math::{Point, Rect},
|
||||
shapes::{
|
||||
add_text_with_tabs, calculate_text_layout_data, set_paint_fill, vertical_align_offset,
|
||||
ListMarker, ListStyleType, Paragraph as TextParagraph, ParagraphBuilderGroup,
|
||||
ParagraphLayout, Stroke, StrokeKind, TextContent, TextDecorationSegment, TextDirection,
|
||||
LIST_MARKER_CENTER_FACTOR, LIST_MARKER_GAP_FACTOR, LIST_MARKER_MIN_RADIUS,
|
||||
LIST_MARKER_RADIUS_FACTOR,
|
||||
add_text_with_tabs, add_trailing_space_anchor, calculate_text_layout_data, set_paint_fill,
|
||||
vertical_align_offset, ListMarker, ListStyleType, Paragraph as TextParagraph,
|
||||
ParagraphBuilderGroup, ParagraphLayout, Stroke, StrokeKind, TextContent,
|
||||
TextDecorationSegment, TextDirection, LIST_MARKER_CENTER_FACTOR, LIST_MARKER_GAP_FACTOR,
|
||||
LIST_MARKER_MIN_RADIUS, LIST_MARKER_RADIUS_FACTOR,
|
||||
},
|
||||
utils::{get_fallback_fonts, get_font_collection},
|
||||
};
|
||||
@ -29,8 +29,9 @@ pub fn stroke_paragraph_builder_group_from_text(
|
||||
let mut paragraph_group = Vec::new();
|
||||
let remove_stroke_alpha = use_shadow.unwrap_or(false) && !stroke.is_transparent();
|
||||
let mut group_layer_opacity: Option<f32> = None;
|
||||
let anchors = text_content.trailing_space_anchors();
|
||||
|
||||
for paragraph in text_content.paragraphs() {
|
||||
for (index, paragraph) in text_content.paragraphs().iter().enumerate() {
|
||||
let mut stroke_paragraphs_map: std::collections::HashMap<usize, ParagraphBuilder> =
|
||||
std::collections::HashMap::new();
|
||||
|
||||
@ -62,9 +63,14 @@ pub fn stroke_paragraph_builder_group_from_text(
|
||||
}
|
||||
}
|
||||
|
||||
let stroke_paragraphs: Vec<ParagraphBuilder> = (0..stroke_paragraphs_map.len())
|
||||
let mut stroke_paragraphs: Vec<ParagraphBuilder> = (0..stroke_paragraphs_map.len())
|
||||
.filter_map(|i| stroke_paragraphs_map.remove(&i))
|
||||
.collect();
|
||||
if anchors.get(index).copied().unwrap_or(false) {
|
||||
stroke_paragraphs
|
||||
.iter_mut()
|
||||
.for_each(add_trailing_space_anchor);
|
||||
}
|
||||
|
||||
paragraph_group.push(stroke_paragraphs);
|
||||
}
|
||||
|
||||
@ -21,7 +21,7 @@ use skia_safe::{
|
||||
};
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::Cell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::collections::HashSet;
|
||||
use std::rc::Rc;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
@ -90,9 +90,8 @@ pub struct TextContentSize {
|
||||
|
||||
const DEFAULT_TEXT_CONTENT_SIZE: f32 = 0.01;
|
||||
|
||||
/// Matches `marginRight: "1px"` on `.paragraph-set` in the HTML text renderer
|
||||
/// (`frontend/src/app/main/ui/shapes/text/styles.cljs`). DOM `getBoundingClientRect`
|
||||
/// includes that margin in auto-width measurements; Skia `longest_line()` does not.
|
||||
/// The 1px `marginRight` of `.paragraph-set` (frontend `shapes/text/styles.cljs`), which DOM
|
||||
/// auto-width measurements include and Skia `max_intrinsic_width()` does not.
|
||||
const PARAGRAPH_SET_MARGIN_RIGHT: f32 = 1.0;
|
||||
|
||||
impl TextContentSize {
|
||||
@ -455,6 +454,15 @@ pub struct TextContent {
|
||||
/// Box size the gradient and image shaders were built for. They are relative
|
||||
/// to the whole box, so a new size must rebuild them.
|
||||
layout_paint_size: Option<(f32, f32)>,
|
||||
trailing_space_anchors: RefCell<Option<TrailingSpaceAnchors>>,
|
||||
}
|
||||
|
||||
/// Which paragraphs get a trailing space anchor, for one content version and width.
|
||||
#[derive(Debug, Clone)]
|
||||
struct TrailingSpaceAnchors {
|
||||
content_version: u64,
|
||||
width: f32,
|
||||
anchored: Rc<Vec<bool>>,
|
||||
}
|
||||
|
||||
impl PartialEq for TextContent {
|
||||
@ -480,6 +488,7 @@ impl TextContent {
|
||||
layout_width: None,
|
||||
layout_paint_origin: None,
|
||||
layout_paint_size: None,
|
||||
trailing_space_anchors: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
@ -497,6 +506,7 @@ impl TextContent {
|
||||
layout_width: None,
|
||||
layout_paint_origin: None,
|
||||
layout_paint_size: None,
|
||||
trailing_space_anchors: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
@ -648,6 +658,16 @@ impl TextContent {
|
||||
max_y = max_y.max(line_baseline + line.descent as f32);
|
||||
min_x = min_x.min(x + line.left as f32);
|
||||
max_x = max_x.max(x + line.left as f32 + line.width as f32);
|
||||
|
||||
// line.width drops trailing spaces, which some fonts paint.
|
||||
for text_box in paragraph.get_rects_for_range(
|
||||
line.start_index..line.end_index,
|
||||
RectHeightStyle::Tight,
|
||||
RectWidthStyle::Tight,
|
||||
) {
|
||||
min_x = min_x.min(x + text_box.rect.left);
|
||||
max_x = max_x.max(x + text_box.rect.right);
|
||||
}
|
||||
has_lines = true;
|
||||
}
|
||||
y_accum += paragraph.height();
|
||||
@ -971,9 +991,10 @@ impl TextContent {
|
||||
) -> Vec<ParagraphBuilderGroup> {
|
||||
let fonts = get_font_collection();
|
||||
let fallback_fonts = get_fallback_fonts();
|
||||
let anchors = self.trailing_space_anchors();
|
||||
let mut paragraph_group = Vec::new();
|
||||
|
||||
for paragraph in self.paragraphs() {
|
||||
for (index, paragraph) in self.paragraphs().iter().enumerate() {
|
||||
let mut paragraph_style = paragraph.paragraph_to_style();
|
||||
if let Some(align) = align_override {
|
||||
paragraph_style.set_text_align(align);
|
||||
@ -1048,15 +1069,81 @@ impl TextContent {
|
||||
if !has_text {
|
||||
builder.add_text(" ");
|
||||
}
|
||||
if anchors.get(index).copied().unwrap_or(false) {
|
||||
add_trailing_space_anchor(&mut builder);
|
||||
}
|
||||
paragraph_group.push(vec![builder]);
|
||||
}
|
||||
|
||||
paragraph_group
|
||||
}
|
||||
|
||||
/// Per paragraph, whether its builders end with [`add_trailing_space_anchor`].
|
||||
///
|
||||
/// Only paragraphs ending in whitespace get one, unless the anchor would wrap onto a
|
||||
/// line of its own, which would add an empty line.
|
||||
pub fn trailing_space_anchors(&self) -> Rc<Vec<bool>> {
|
||||
let width = if self.grow_type() == GrowType::AutoWidth {
|
||||
f32::MAX
|
||||
} else {
|
||||
self.bounds.width()
|
||||
};
|
||||
if let Some(cached) = self.trailing_space_anchors.borrow().as_ref() {
|
||||
if cached.content_version == self.content_version
|
||||
&& cached.width == width
|
||||
&& cached.anchored.len() == self.paragraphs.len()
|
||||
{
|
||||
return Rc::clone(&cached.anchored);
|
||||
}
|
||||
}
|
||||
let anchored: Rc<Vec<bool>> = Rc::new(
|
||||
self.paragraphs
|
||||
.iter()
|
||||
.map(|paragraph| {
|
||||
ends_with_trailing_space(paragraph)
|
||||
&& (width == f32::MAX || self.anchor_shares_last_line(paragraph, width))
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
*self.trailing_space_anchors.borrow_mut() = Some(TrailingSpaceAnchors {
|
||||
content_version: self.content_version,
|
||||
width,
|
||||
anchored: Rc::clone(&anchored),
|
||||
});
|
||||
anchored
|
||||
}
|
||||
|
||||
/// Whether an anchored `paragraph` laid out at `width` keeps the anchor next to text.
|
||||
fn anchor_shares_last_line(&self, paragraph: &Paragraph, width: f32) -> bool {
|
||||
let fallback_fonts = get_fallback_fonts();
|
||||
let mut builder =
|
||||
ParagraphBuilder::new(¶graph.paragraph_to_style(), get_font_collection());
|
||||
let mut text_len = 0;
|
||||
for span in paragraph.children() {
|
||||
let style = span.to_style(
|
||||
&self.bounds(),
|
||||
fallback_fonts,
|
||||
false,
|
||||
paragraph.line_height(),
|
||||
);
|
||||
let text = span.apply_text_transform();
|
||||
text_len += text.encode_utf16().count();
|
||||
builder.push_style(&style);
|
||||
add_text_with_tabs(&mut builder, &text, span.font_size);
|
||||
}
|
||||
add_trailing_space_anchor(&mut builder);
|
||||
let mut probe = builder.build();
|
||||
probe.layout(width);
|
||||
probe
|
||||
.get_line_metrics()
|
||||
.last()
|
||||
.is_some_and(|line| line.start_index < text_len)
|
||||
}
|
||||
|
||||
/// Performs an Auto Width text layout.
|
||||
fn text_layout_auto_width(&self) -> TextContentLayoutResult {
|
||||
// Left-aligned MAX-width pass: longest_line() is glyph width, not the huge container.
|
||||
// Left-aligned MAX-width pass. max_intrinsic_width() keeps trailing spaces;
|
||||
// longest_line() drops them.
|
||||
let mut measure_builders = self.paragraph_builders(
|
||||
None,
|
||||
false,
|
||||
@ -1076,7 +1163,7 @@ impl TextContent {
|
||||
.iter()
|
||||
.flatten()
|
||||
.fold(0.0_f32, |auto_width, paragraph| {
|
||||
f32::max(paragraph.longest_line(), auto_width)
|
||||
f32::max(paragraph.max_intrinsic_width(), auto_width)
|
||||
})
|
||||
.ceil();
|
||||
|
||||
@ -1442,6 +1529,7 @@ impl Default for TextContent {
|
||||
layout_width: None,
|
||||
layout_paint_origin: None,
|
||||
layout_paint_size: None,
|
||||
trailing_space_anchors: RefCell::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1680,6 +1768,31 @@ fn capitalize_words(text: &str) -> String {
|
||||
}
|
||||
|
||||
/// Add `text`, pushing every '\t' as a one em wide placeholder.
|
||||
/// Ends a paragraph with a zero-size placeholder, so Skia doesn't trim the spaces before it
|
||||
/// and measures and paints them.
|
||||
pub fn add_trailing_space_anchor(builder: &mut ParagraphBuilder) {
|
||||
builder.add_placeholder(&PlaceholderStyle::new(
|
||||
0.0,
|
||||
0.0,
|
||||
PlaceholderAlignment::Baseline,
|
||||
TextBaseline::Alphabetic,
|
||||
0.0,
|
||||
));
|
||||
}
|
||||
|
||||
fn ends_with_trailing_space(paragraph: &Paragraph) -> bool {
|
||||
paragraph
|
||||
.children()
|
||||
.iter()
|
||||
.rev()
|
||||
.map(|span| span.apply_text_transform())
|
||||
.find(|text| !text.is_empty())
|
||||
.and_then(|text| text.chars().last())
|
||||
.is_some_and(|ch| {
|
||||
ch.is_whitespace() && !matches!(ch, '\n' | '\r' | '\u{2028}' | '\u{2029}')
|
||||
})
|
||||
}
|
||||
|
||||
pub fn add_text_with_tabs(builder: &mut ParagraphBuilder, text: &str, font_size: f32) {
|
||||
let tab = PlaceholderStyle::new(
|
||||
font_size,
|
||||
@ -2731,4 +2844,201 @@ mod tests {
|
||||
layout.clear();
|
||||
assert!(layout.needs_update());
|
||||
}
|
||||
|
||||
/// A laid-out 200x100 text at the origin with one paragraph of `text`.
|
||||
fn plain_text_shape(grow_type: GrowType, text: &str) -> Shape {
|
||||
let mut content = TextContent::new(Rect::from_xywh(0.0, 0.0, 200.0, 100.0), grow_type);
|
||||
content.add_paragraph(test_paragraph(&[text]));
|
||||
|
||||
let mut shape = Shape::new(Uuid::nil());
|
||||
shape.set_shape_type(shapes::Type::Text(content));
|
||||
shape.set_selrect(0.0, 0.0, 200.0, 100.0);
|
||||
shape
|
||||
}
|
||||
|
||||
fn auto_width_of(text: &str) -> f32 {
|
||||
let mut content =
|
||||
TextContent::new(Rect::from_xywh(0.0, 0.0, 200.0, 100.0), GrowType::AutoWidth);
|
||||
content.add_paragraph(test_paragraph(&[text]));
|
||||
content
|
||||
.update_layout(Rect::from_xywh(0.0, 0.0, 200.0, 100.0))
|
||||
.width
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_width_includes_trailing_spaces() {
|
||||
let mut resources = RenderResources::try_new_headless().expect("headless resources");
|
||||
let _guard = TestRenderResourcesGuard::install(&mut resources);
|
||||
let trimmed = auto_width_of("hello");
|
||||
let with_spaces = auto_width_of("hello ");
|
||||
assert!(
|
||||
with_spaces > trimmed + 3.0,
|
||||
"trimmed: {trimmed}, with spaces: {with_spaces}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_width_counts_leading_and_trailing_spaces_alike() {
|
||||
let mut resources = RenderResources::try_new_headless().expect("headless resources");
|
||||
let _guard = TestRenderResourcesGuard::install(&mut resources);
|
||||
let leading = auto_width_of(" hello");
|
||||
let trailing = auto_width_of("hello ");
|
||||
assert!(
|
||||
(leading - trailing).abs() < 1.0,
|
||||
"leading: {leading}, trailing: {trailing}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extrect_includes_trailing_spaces() {
|
||||
let mut resources = RenderResources::try_new_headless().expect("headless resources");
|
||||
let _guard = TestRenderResourcesGuard::install(&mut resources);
|
||||
for grow_type in [GrowType::Fixed, GrowType::AutoHeight] {
|
||||
let trimmed = text_extrect(&plain_text_shape(grow_type, "hello"));
|
||||
let with_spaces = text_extrect(&plain_text_shape(grow_type, "hello "));
|
||||
assert!(
|
||||
with_spaces.right() > trimmed.right() + 3.0,
|
||||
"{grow_type:?}: trimmed {trimmed:?}, with spaces {with_spaces:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A laid-out fixed or auto-height text, `width` wide, with one paragraph of `text`.
|
||||
fn laid_out_content(grow_type: GrowType, text: &str, width: f32) -> TextContent {
|
||||
let selrect = Rect::from_xywh(0.0, 0.0, width, 100.0);
|
||||
let mut content = TextContent::new(selrect, grow_type);
|
||||
content.add_paragraph(test_paragraph(&[text]));
|
||||
content.update_layout(selrect);
|
||||
content
|
||||
}
|
||||
|
||||
/// Glyphs Skia paints for each paragraph of `builders` laid out at `width`.
|
||||
fn painted_glyphs(builders: &mut [ParagraphBuilderGroup], width: f32) -> Vec<usize> {
|
||||
build_paragraphs_from_paragraph_builders(builders, width)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(|mut paragraph| {
|
||||
let mut count = 0;
|
||||
paragraph.visit(|_, info| {
|
||||
if let Some(info) = info {
|
||||
count += info.count();
|
||||
}
|
||||
});
|
||||
count
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn hello_width() -> f32 {
|
||||
let content = laid_out_content(GrowType::AutoWidth, "hello", 200.0);
|
||||
content.size.width
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_spaces_are_painted() {
|
||||
let mut resources = RenderResources::try_new_headless().expect("headless resources");
|
||||
let _guard = TestRenderResourcesGuard::install(&mut resources);
|
||||
for grow_type in [GrowType::Fixed, GrowType::AutoHeight, GrowType::AutoWidth] {
|
||||
let content = laid_out_content(grow_type, "hello ", 200.0);
|
||||
let mut builders = content.paragraph_builder_group_from_text(None);
|
||||
let width = content.get_width(200.0);
|
||||
assert_eq!(
|
||||
painted_glyphs(&mut builders, width),
|
||||
vec![8],
|
||||
"{grow_type:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_spaces_are_painted_by_strokes() {
|
||||
let mut resources = RenderResources::try_new_headless().expect("headless resources");
|
||||
let _guard = TestRenderResourcesGuard::install(&mut resources);
|
||||
let content = laid_out_content(GrowType::Fixed, "hello ", 200.0);
|
||||
let mut stroke = shapes::Stroke::new_center_stroke(
|
||||
1.0,
|
||||
shapes::StrokeStyle::Solid,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
stroke.fill = solid_fill();
|
||||
let (mut builders, _) = crate::render::text::stroke_paragraph_builder_group_from_text(
|
||||
&content,
|
||||
&stroke,
|
||||
&content.bounds(),
|
||||
None,
|
||||
);
|
||||
assert_eq!(painted_glyphs(&mut builders, 200.0), vec![8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_of_only_spaces_is_painted() {
|
||||
let mut resources = RenderResources::try_new_headless().expect("headless resources");
|
||||
let _guard = TestRenderResourcesGuard::install(&mut resources);
|
||||
let content = laid_out_content(GrowType::Fixed, " ", 200.0);
|
||||
let mut builders = content.paragraph_builder_group_from_text(None);
|
||||
assert_eq!(painted_glyphs(&mut builders, 200.0), vec![3]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_paragraphs_ending_in_whitespace_get_an_anchor() {
|
||||
let mut resources = RenderResources::try_new_headless().expect("headless resources");
|
||||
let _guard = TestRenderResourcesGuard::install(&mut resources);
|
||||
let selrect = Rect::from_xywh(0.0, 0.0, 200.0, 100.0);
|
||||
let mut content = TextContent::new(selrect, GrowType::Fixed);
|
||||
for text in ["hello ", " hello", "", "hello\t"] {
|
||||
content.add_paragraph(test_paragraph(&[text]));
|
||||
}
|
||||
content.update_layout(selrect);
|
||||
assert_eq!(
|
||||
*content.trailing_space_anchors(),
|
||||
vec![true, false, false, true]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_anchor_when_it_would_wrap_onto_its_own_line() {
|
||||
let mut resources = RenderResources::try_new_headless().expect("headless resources");
|
||||
let _guard = TestRenderResourcesGuard::install(&mut resources);
|
||||
let width = hello_width();
|
||||
for grow_type in [GrowType::Fixed, GrowType::AutoHeight] {
|
||||
let trimmed = laid_out_content(grow_type, "hello", width);
|
||||
let content = laid_out_content(grow_type, "hello ", width);
|
||||
assert_eq!(
|
||||
*content.trailing_space_anchors(),
|
||||
vec![false],
|
||||
"{grow_type:?}"
|
||||
);
|
||||
assert_eq!(content.size.height, trimmed.size.height, "{grow_type:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_space_anchor_keeps_the_height() {
|
||||
let mut resources = RenderResources::try_new_headless().expect("headless resources");
|
||||
let _guard = TestRenderResourcesGuard::install(&mut resources);
|
||||
for grow_type in [GrowType::Fixed, GrowType::AutoHeight, GrowType::AutoWidth] {
|
||||
let trimmed = laid_out_content(grow_type, "hello", 200.0);
|
||||
let content = laid_out_content(grow_type, "hello ", 200.0);
|
||||
assert_eq!(
|
||||
*content.trailing_space_anchors(),
|
||||
vec![true],
|
||||
"{grow_type:?}"
|
||||
);
|
||||
assert_eq!(content.size.height, trimmed.size.height, "{grow_type:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caret_past_a_trailing_space_anchor_stays_at_the_text_end() {
|
||||
let mut resources = RenderResources::try_new_headless().expect("headless resources");
|
||||
let _guard = TestRenderResourcesGuard::install(&mut resources);
|
||||
let content = laid_out_content(GrowType::Fixed, "hello ", 200.0);
|
||||
let position = content
|
||||
.get_caret_position_from_shape_coords(&Point::new(190.0, 5.0))
|
||||
.expect("caret position");
|
||||
assert_eq!(position.offset, 8);
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user