🐛 Fix Mainland punctuation spacing in a Traditional Chinese font

Mainland spacing trims the right half of a stop's em, where its font
leaves it blank. A Traditional Chinese face draws ,。:; centred, so
the trimmed stop drifted from the text before it and crowded the next
mark. The layout now measures where the font draws each stop and trims
a centred one by a quarter em on each side, as Hong Kong spacing does.

Add a Noto Serif TC subset as a test font.

AI-assisted-by: claude-opus-5-5
This commit is contained in:
alonso.torres 2026-11-24 13:58:18 +01:00
parent b7496c5901
commit 8c6ce999d9
4 changed files with 209 additions and 8 deletions

Binary file not shown.

View File

@ -33,6 +33,7 @@ use crate::math::Point;
use crate::shapes::jlreq::{
aki_class, is_cjk_text_char, pair_rule, punctuation_aki_sheds, AkiShed, JlreqClass,
};
use crate::shapes::text_policy::{ChineseRegion, TextLayoutPolicy};
use crate::shapes::{line_breaks, merge_fills};
use crate::utils::{get_fallback_fonts, get_font_collection};
use skia_safe::{
@ -148,8 +149,71 @@ fn jlreq_aki_sheds(paragraph: &Paragraph, texts: &[String]) -> Vec<Vec<(usize, f
/// Signed advance changes: positive removes punctuation space, negative adds
/// the regional Han/Latin gap. Source and builder text stay unchanged.
fn horizontal_pairwise_spacing(paragraph: &Paragraph, texts: &[String]) -> Vec<Vec<(usize, f32)>> {
horizontal_pairwise_spacing_with(paragraph, texts, draws_stop_centred)
}
/// Whether the font of `span` draws the regional stop `ch` in the centre of
/// its em, as Traditional Chinese faces do, rather than in the left half,
/// as mainland faces do. False when there are no fonts to measure.
fn draws_stop_centred(span: &TextSpan, ch: char) -> bool {
if !crate::globals::has_render_resources() {
return false;
}
let provider = get_resources().fonts.font_provider();
draws_stop_centred_with(span, ch, provider, get_fallback_fonts())
}
fn draws_stop_centred_with(
span: &TextSpan,
ch: char,
provider: &skia::textlayout::TypefaceFontProvider,
fallbacks: &crate::render::FallbackFonts,
) -> bool {
let runs = shape_segment_with_fallbacks(
&ch.to_string(),
span.font_size.max(1.0),
&span_font_families(span, fallbacks),
provider,
false,
span.font_features,
&FontMgr::from(provider.clone()),
&span.language,
);
let [run] = runs.as_slice() else {
return false;
};
let count = run.glyphs.len();
let advance = run.cluster_advance(0, count);
// A left-half mark centres its ink near a quarter of the em.
advance > 0.0
&& run
.cluster_ink_bounds(0, count)
.is_some_and(|ink| ink.center_x() > advance * 0.375)
}
/// `horizontal_pairwise_spacing` with `centred` telling whether a span's
/// font draws a regional stop in the centre of its em. Only mainland
/// spacing asks, once per span and mark.
fn horizontal_pairwise_spacing_with(
paragraph: &Paragraph,
texts: &[String],
centred: impl Fn(&TextSpan, char) -> bool,
) -> Vec<Vec<(usize, f32)>> {
let mut result = vec![Vec::new(); texts.len()];
let policy = paragraph.layout_policy();
let asks = policy == TextLayoutPolicy::Chinese(ChineseRegion::Mainland);
let mut measured: Vec<(usize, char, bool)> = Vec::new();
let mut is_centred = |span: usize, ch: char| -> bool {
if !asks || !TextLayoutPolicy::is_regional_stop(ch) {
return false;
}
if let Some(&(_, _, known)) = measured.iter().find(|m| m.0 == span && m.1 == ch) {
return known;
}
let known = centred(&paragraph.children()[span], ch);
measured.push((span, ch, known));
known
};
let mut previous: Option<(usize, usize, char)> = None;
for (span, text) in texts.iter().enumerate() {
for (index, ch) in text.chars().enumerate() {
@ -161,7 +225,8 @@ fn horizontal_pairwise_spacing(paragraph: &Paragraph, texts: &[String]) -> Vec<V
let b = &paragraph.children()[span];
if !a.has_ruby() && !b.has_ruby() && !a.is_warichu() && !b.is_warichu() {
let em = a.font_size.min(b.font_size);
let spacing = policy.pair_spacing_em(before, ch, false);
let drawn = (is_centred(before_span, before), is_centred(span, ch));
let spacing = policy.drawn_pair_spacing_em(before, ch, false, drawn);
// `palt` already sets punctuation proportionally.
let compression = if a.font_features == FontFeatures::Palt
|| b.font_features == FontFeatures::Palt

View File

@ -2972,3 +2972,70 @@ fn a_joined_reading_paints_like_the_reading_of_one_span() {
"{joined:?} vs {one:?}"
);
}
/// Noto Serif TC subset (,。「」晚): its stops sit in the centre of the em.
const TC_STOPS_TEST_FONT: &[u8] = include_bytes!("../../fonts/notoseriftc-stops-test.ttf");
#[test]
fn a_traditional_face_draws_its_stops_centred() {
use crate::shapes::text_vertical::test_support::{provider, VPAL_TEST_FONT};
let fallbacks = crate::render::FallbackFonts::default();
let span = make_span("。", 0.0);
let traditional = provider(TC_STOPS_TEST_FONT);
assert!(draws_stop_centred_with(
&span,
'。',
&traditional,
&fallbacks
));
assert!(draws_stop_centred_with(
&span,
',',
&traditional,
&fallbacks
));
assert!(
!draws_stop_centred_with(&span, '。', &provider(VPAL_TEST_FONT), &fallbacks),
"Noto Sans JP sets 。 in the left half"
);
}
#[test]
fn mainland_spacing_trims_a_centred_stop_by_a_quarter_em() {
init_state();
let texts = vec!["晚。」".to_string()];
let mut paragraph = make_paragraph(vec![make_span(&texts[0], 0.0)], 0.0);
paragraph.set_language("zh-Hans-CN".to_owned());
let sheds =
|centred: bool| horizontal_pairwise_spacing_with(&paragraph, &texts, |_, _| centred);
assert_eq!(sheds(false), vec![vec![(1, 8.0)]], "half of the 16px em");
assert_eq!(sheds(true), vec![vec![(1, 4.0)]], "a quarter of it");
paragraph.set_language("zh-Hant-HK".to_owned());
assert_eq!(
horizontal_pairwise_spacing_with(&paragraph, &texts, |_, _| panic!("asked")),
vec![vec![(1, 4.0)]],
"only mainland spacing measures the font"
);
}
#[test]
fn mainland_text_in_a_traditional_face_sheds_as_in_hong_kong() {
init_state();
let mut resources =
crate::render::RenderResources::try_new_headless().expect("headless resources");
let family = crate::shapes::FontFamily::new(Uuid::nil(), 400, crate::shapes::FontStyle::Normal);
resources
.fonts
.add(family, TC_STOPS_TEST_FONT, false, false)
.expect("test font");
let _guard = crate::globals::TestRenderResourcesGuard::install(&mut resources);
let texts = vec!["晚。」".to_string()];
let mut paragraph = make_paragraph(vec![make_span(&texts[0], 0.0)], 0.0);
paragraph.set_language("zh-Hans-CN".to_owned());
assert_eq!(
horizontal_pair_spacing(&paragraph, &texts),
vec![vec![(1, 4.0)]],
"the centred 。 gives up a quarter of its 16px em to 」"
);
}

View File

@ -292,9 +292,34 @@ impl TextLayoutPolicy {
}
}
pub fn compression_em(self, before: char, after: char, vertical: bool) -> f32 {
let a = self.punctuation_space(before, vertical);
let b = self.punctuation_space(after, vertical);
/// True for the marks whose place in the em CLREQ sets by region in
/// horizontal text: the left half in mainland China, the centre in
/// Taiwan and Hong Kong. A font draws them in the way of its own region.
pub fn is_regional_stop(ch: char) -> bool {
COMMAS_AND_FULL_STOPS.contains(ch) || ":;!?".contains(ch)
}
/// `punctuation_space` of `ch` as its font draws it. Mainland spacing
/// puts the blank half of a regional stop on its right; a stop its font
/// draws `centred` (a Traditional Chinese face) has a quarter em blank
/// on each side, and sheds those as Hong Kong does.
fn drawn_punctuation_space(self, ch: char, vertical: bool, centred: bool) -> (f32, f32) {
let (start, end) = self.punctuation_space(ch, vertical);
if centred
&& !vertical
&& self == Self::Chinese(ChineseRegion::Mainland)
&& Self::is_regional_stop(ch)
{
let half = (start + end) / 2.0;
(half, half)
} else {
(start, end)
}
}
/// Punctuation space to remove between two characters, in em, from
/// their removable side bearings `a` and `b`.
fn compression_between(a: (f32, f32), b: (f32, f32)) -> f32 {
// Both characters must be adjustable punctuation. Never trim ordinary
// Han cells or assume proportional ASCII punctuation contains half an em.
if a == (0.0, 0.0) || b == (0.0, 0.0) {
@ -308,8 +333,24 @@ impl TextLayoutPolicy {
/// compression to remove and the script gap to add. Each axis applies
/// its own caps and skips.
pub fn pair_spacing_em(self, before: char, after: char, vertical: bool) -> PairSpacing {
self.drawn_pair_spacing_em(before, after, vertical, (false, false))
}
/// `pair_spacing_em` for marks as their fonts draw them: `centred` tells,
/// for `before` and `after`, whether the font draws that character in
/// the centre of its em (see `drawn_punctuation_space`).
pub fn drawn_pair_spacing_em(
self,
before: char,
after: char,
vertical: bool,
centred: (bool, bool),
) -> PairSpacing {
PairSpacing {
compression: self.compression_em(before, after, vertical),
compression: Self::compression_between(
self.drawn_punctuation_space(before, vertical, centred.0),
self.drawn_punctuation_space(after, vertical, centred.1),
),
script_gap: self.script_spacing_em(before, after),
}
}
@ -496,9 +537,9 @@ mod tests {
let cn = TextLayoutPolicy::Chinese(ChineseRegion::Mainland);
let tw = TextLayoutPolicy::Chinese(ChineseRegion::Taiwan);
let hk = TextLayoutPolicy::Chinese(ChineseRegion::HongKong);
assert_eq!(cn.compression_em(',', '」', false), 0.5);
assert_eq!(tw.compression_em(',', '」', false), 0.0);
assert_eq!(hk.compression_em(',', '」', false), 0.25);
assert_eq!(cn.pair_spacing_em(',', '」', false).compression, 0.5);
assert_eq!(tw.pair_spacing_em(',', '」', false).compression, 0.0);
assert_eq!(hk.pair_spacing_em(',', '」', false).compression, 0.25);
assert_eq!(cn.punctuation_space('!', true), (0.0, 0.0));
assert_eq!(hk.punctuation_space('!', false), (0.0, 0.0));
assert_eq!(tw.hanging_em(',', false), 0.0);
@ -519,6 +560,34 @@ mod tests {
);
}
#[test]
fn a_centred_mainland_stop_sheds_on_both_sides_as_in_hong_kong() {
let cn = TextLayoutPolicy::Chinese(ChineseRegion::Mainland);
let hk = TextLayoutPolicy::Chinese(ChineseRegion::HongKong);
let compression = |policy: TextLayoutPolicy, before, after, centred| {
policy
.drawn_pair_spacing_em(before, after, false, centred)
.compression
};
// A left-half 。 gives its blank right half to 」; a centred one only
// has a quarter em there.
assert_eq!(compression(cn, '。', '」', (false, false)), 0.5);
assert_eq!(compression(cn, '。', '」', (true, false)), 0.25);
assert_eq!(
compression(cn, '。', '」', (true, false)),
compression(hk, '。', '」', (true, false))
);
// A centred : still meets the blank half of 「.
assert_eq!(compression(cn, ':', '「', (true, false)), 0.5);
// Brackets keep their own sides; vertical text places stops itself.
assert_eq!(compression(cn, '」', '「', (true, true)), 0.5);
assert_eq!(
cn.drawn_pair_spacing_em('。', '」', true, (true, false))
.compression,
cn.pair_spacing_em('。', '」', true).compression
);
}
#[test]
fn chinese_basic_restrictions_do_not_include_small_kana() {
let policy = TextLayoutPolicy::Chinese(ChineseRegion::Basic);