✨ Lay out vertical CJK text in the WASM renderer

Add vertical writing (`vertical-rl`) to the renderer: characters set in
cells along columns, upright or sideways orientation, vertical glyph
alternates and metrics, tate-chu-yoko, kinsoku and JLREQ squeezing across
columns, and readings and emphasis marks beside the column.

AI-assisted-by: claude-opus-5-5
This commit is contained in:
alonso.torres 2026-11-16 16:43:12 +01:00
parent 028a36c656
commit 52e7ce8105
11 changed files with 9014 additions and 0 deletions

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,235 @@
//! Column planning, spacing and alignment of the pairwise policies (plain,
//! Chinese and Korean) along the vertical flow. Break opportunities, spacing
//! and justification come from `TextLayoutPolicy` pair rules over the whole
//! paragraph text.
use crate::shapes::cjk_chars::is_punctuation;
use crate::shapes::line_breaks::PolicyBoundaries;
use crate::shapes::text_allocation::{allocate_bounded_expansion, bounded_expansion};
use crate::shapes::text_policy::TextLayoutPolicy;
use crate::shapes::TextAlign;
use unicode_segmentation::UnicodeSegmentation;
use super::super::layout::CellKind;
use super::{align_offset_along_column, is_bounded, FlowCell, FIT_TOLERANCE};
/// Column planning of the pairwise policies (plain, Chinese and Korean):
/// break opportunities come from `TextLayoutPolicy::break_allowed`.
/// Boundaries use the entire paragraph, so font and style runs cannot split
/// a grapheme or create a word boundary.
pub(in crate::shapes::text_vertical) fn plan_pairwise_columns(
cells: &[FlowCell],
text: &str,
policy: TextLayoutPolicy,
max_height: f32,
) -> Vec<(usize, f32)> {
let boundaries = PolicyBoundaries::new(text, policy);
let mut emergency_start = Vec::with_capacity(cells.len());
let mut unit_start = Vec::with_capacity(cells.len());
let mut prefix = vec![0.0];
for (i, flow) in cells.iter().enumerate() {
let boundary = boundaries.at(flow.cell.start);
let atomic =
i > 0 && (flow.keep_with_previous || flow.shares_previous_box || boundary.is_none());
let emergency_joined = atomic || boundary.is_some_and(|(_, emergency)| !emergency);
emergency_start.push(if i > 0 && emergency_joined {
emergency_start[i - 1]
} else {
i
});
let joined = atomic || boundary.is_some_and(|(allowed, _)| !allowed);
unit_start.push(if i > 0 && joined {
unit_start[i - 1]
} else {
i
});
prefix.push(prefix[i] + flow.cell.extent);
}
let mut unit_end = vec![cells.len(); cells.len()];
for i in (0..cells.len().saturating_sub(1)).rev() {
unit_end[i] = if unit_start[i] == unit_start[i + 1] {
unit_end[i + 1]
} else {
i + 1
};
}
let mut placements = Vec::with_capacity(cells.len());
let (mut column, mut column_start, mut cursor) = (0, 0, 0.0);
for (i, flow) in cells.iter().enumerate() {
let punctuation = |at: usize| cells.get(at).and_then(|c| c.ch).is_some_and(is_punctuation);
let solitary = (i == 0 || !punctuation(i - 1)) && !punctuation(i + 1);
let hang = if solitary {
flow.ch
.map_or(0.0, |ch| policy.hanging_em(ch, true) * flow.cell.font_size)
} else {
0.0
};
if cursor > 0.0 && cursor + flow.cell.extent - hang > max_height + FIT_TOLERANCE {
let candidate = unit_start[i];
let end = if policy.measures_whole_unit() {
unit_end[i]
} else {
i + 1
};
let fits_empty = prefix[end] - prefix[candidate] <= max_height + FIT_TOLERANCE;
let break_at = if candidate > column_start && fits_empty {
candidate
} else {
emergency_start[i]
};
// Overlong words may use emergency boundaries; punctuation,
// graphemes, explicit no-break controls and annotations may not.
if break_at > column_start {
column += 1;
cursor = 0.0;
for k in break_at..i {
placements[k] = (column, cursor);
cursor += cells[k].cell.extent;
}
column_start = break_at;
}
}
placements.push((column, cursor));
cursor += flow.cell.extent;
}
placements
}
/// Source edge characters of every cell, including sideways runs. Offsets
/// stay in UTF-16 source space; typography never inserts saved spaces.
fn pairwise_cell_edges(cells: &[FlowCell], text: &str) -> Vec<(Option<char>, Option<char>)> {
let mut offset = 0;
let chars: Vec<_> = text
.chars()
.map(|ch| {
let at = offset;
offset += ch.len_utf16();
(at, ch)
})
.collect();
cells
.iter()
.map(|flow| {
let start = chars.partition_point(|(at, _)| *at < flow.cell.start);
let end = chars.partition_point(|(at, _)| *at < flow.cell.end);
(
chars.get(start).filter(|_| start < end).map(|(_, ch)| *ch),
end.checked_sub(1)
.and_then(|at| chars.get(at))
.filter(|_| start < end)
.map(|(_, ch)| *ch),
)
})
.collect()
}
pub(in crate::shapes::text_vertical) fn apply_pairwise_spacing(
cells: &mut [FlowCell],
text: &str,
policy: TextLayoutPolicy,
) {
let edges = pairwise_cell_edges(cells, text);
for i in 1..cells.len() {
if cells[i].keep_with_previous || cells[i].shares_previous_box {
continue;
}
let (Some(before), Some(after)) = (edges[i - 1].1, edges[i].0) else {
continue;
};
let em = cells[i - 1].cell.font_size.min(cells[i].cell.font_size);
let available = (cells[i - 1].cell.extent
- cells[i - 1].trailing_spacing
- 0.5 * cells[i - 1].cell.font_size)
.max(0.0);
let spacing = policy.pair_spacing_em(before, after, true);
let compression = (spacing.compression * em).min(available);
// A tate-chu-yoko composite sets in one ideograph's cell, so the
// Han/Western gap of its digits or letters does not apply.
let tate_chu_yoko =
|flow: &FlowCell| matches!(flow.cell.kind, CellKind::TateChuYoko { .. });
let gap = if tate_chu_yoko(&cells[i - 1]) || tate_chu_yoko(&cells[i]) {
0.0
} else {
spacing.script_gap * em
};
cells[i - 1].cell.extent = (cells[i - 1].cell.extent + gap - compression)
.max(cells[i - 1].trailing_spacing.max(0.0));
cells[i - 1].cell.min_squeezed_extent = cells[i - 1].cell.extent;
}
}
/// Justify non-final columns over policy-approved gaps with bounded amounts.
/// Korean word mode only expands spaces; grapheme and annotation interiors
/// never become opportunities merely because a font/style run split them.
pub(in crate::shapes::text_vertical) fn pairwise_aligned_tops(
cells: &[FlowCell],
text: &str,
policy: TextLayoutPolicy,
placements: &[(usize, f32)],
align: TextAlign,
budget: f32,
) -> Vec<f32> {
let mut tops: Vec<f32> = placements.iter().map(|(_, top)| *top).collect();
let edges = pairwise_cell_edges(cells, text);
let graphemes: Vec<usize> = text
.graphemes(true)
.scan(0, |at, g| {
let start = *at;
*at += g.encode_utf16().count();
Some(start)
})
.collect();
let last_column = placements.last().map_or(0, |p| p.0);
let mut start = 0;
while start < cells.len() {
let column = placements[start].0;
let end = placements.partition_point(|p| p.0 <= column);
let used = placements[end - 1].1 + cells[end - 1].cell.extent;
let shift = align_offset_along_column(align, budget, used);
for top in &mut tops[start..end] {
*top += shift;
}
if (align == TextAlign::Distribute || (align == TextAlign::Justify && column < last_column))
&& is_bounded(budget)
{
let remaining = (budget - used).max(0.0);
let mut extras = vec![0.0; end - start];
let mut opportunities = Vec::new();
for i in start..end - 1 {
if cells[i + 1].keep_with_previous
|| cells[i + 1].shares_previous_box
|| graphemes.binary_search(&cells[i + 1].cell.start).is_err()
{
continue;
}
let (Some(before), Some(after)) = (edges[i].1, edges[i + 1].0) else {
continue;
};
if align == TextAlign::Distribute
&& matches!(before, '\u{00a0}' | '\u{202f}' | '\u{2060}')
|| align == TextAlign::Distribute
&& matches!(after, '\u{00a0}' | '\u{202f}' | '\u{2060}')
{
continue;
}
let em = cells[i].cell.font_size.min(cells[i + 1].cell.font_size);
let distribute = (align == TextAlign::Distribute).then_some(budget);
if let Some((priority, cap)) =
bounded_expansion(policy, before, after, em, distribute)
{
opportunities.push((i, priority, cap));
}
}
for (i, amount) in allocate_bounded_expansion(&opportunities, remaining) {
extras[i - start] += amount;
}
let mut extra = 0.0;
for i in start..end {
tops[i] += extra;
extra += extras[i - start];
}
}
start = end;
}
tops
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,48 @@
// Vertical (tategaki) text layout: columns flow top->bottom and advance
// right->left. Skia's skparagraph has no vertical writing mode, so this
// module owns the whole vertical pipeline:
//
// segment spans by glyph orientation and shape each segment with
// SkShaper, OpenType `vert`/`vrt2` for upright runs (`text_shaping`) ->
// derive cells: one per upright glyph cluster, one per rotated run, one per
// composite (`cells`) -> JLREQ spacing and kinsoku-aware column breaks
// (`flow`) -> place columns and annotations (`layout`, `annotations`) ->
// paint / outline export (`paint`) and position data / hit-testing
// (`positions`) from the cells.
//
// Offsets: cells use UTF-16 offsets in transformed layout text. Position
// data maps those ranges back to the original span text before it crosses
// the WASM boundary; the WORD JOINER OffsetMap applies only to
// skparagraph-driven horizontal breaks.
//
// Layouts are computed on demand, as the horizontal path rebuilds its
// skparagraph objects per paint; only per-typeface font tables are cached.
//
// Text-align aligns each column's glyphs along the vertical (inline) axis:
// Left/Start->top, Center->middle, Right/End->bottom of the wrap budget.
// Justify stretches every column but the last to fill the wrap budget.
//
// Letter-spacing adds advance along the column once per upright cluster
// and once per glyph inside a rotated run, matching the horizontal
// `letter-spacing` that Skia applies to each glyph advance.
//
// Not supported yet: PDF/vector emoji overlays and inner shadows.
mod annotations;
mod cells;
mod flow;
mod layout;
mod paint;
mod positions;
#[cfg(test)]
pub(crate) mod test_support;
#[cfg(test)]
pub(crate) use layout::CellKind;
pub use layout::{block_axis_offset, layout_for_rect, VerticalLayout};
pub use paint::{
paint_drop_shadow, paint_grid, paint_layout, paint_stroke, paint_text_vertical,
paint_text_vertical_with, vertical_text_paths, GlyphOutput,
};
pub use positions::{caret_from_point, caret_rect, intersects, position_data, range_rects};

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,194 @@
// Fixtures for the vertical layout tests: real shaping with bundled test
// fonts. Glyph coverage does not matter for offsets/columns; tofu still
// shapes with real advances.
use skia_safe::{textlayout::TypefaceFontProvider, FontMgr};
use crate::math::Rect;
use crate::render::FallbackFonts;
use crate::shapes::{
FontFamily, FontStyle, GrowType, Paragraph, TextAlign, TextContent, TextDecoration,
TextDirection, TextOrientation, TextSpan, WritingMode,
};
use crate::Uuid;
use super::layout::{layout_vertical, VerticalLayout};
pub(crate) const TEST_FONT: &[u8] = include_bytes!("../../fonts/sourcesanspro-regular.ttf");
/// Work Sans subset with Latin letters and combining Pinyin tone marks.
pub(crate) const PINYIN_TEST_FONT: &[u8] = include_bytes!("../../fonts/pinyin-test.ttf");
/// Noto Sans JP subset with `vmtx`/`vhea`: 〱 advances 2em vertically, あ/く 1em.
pub(crate) const VMTX_TEST_FONT: &[u8] = include_bytes!("../../fonts/notosansjp-vmtx-test.ttf");
/// Noto Sans JP subset with GSUB `vert` and GPOS `vpal` for 、。「」あく.
pub(crate) const VPAL_TEST_FONT: &[u8] = include_bytes!("../../fonts/notosansjp-vpal-test.ttf");
/// Font size of every test span.
pub(crate) const EM: f32 = 20.0;
/// Provider with `font` registered under the family every test span uses
/// (spans serialize their family as "uuid-weight-style").
pub(crate) fn provider(font: &[u8]) -> TypefaceFontProvider {
let typeface = FontMgr::new()
.new_from_data(skia_safe::Data::new_copy(font), None)
.expect("failed to load test font");
let mut provider = TypefaceFontProvider::new();
let family = format!("{}", FontFamily::new(Uuid::nil(), 400, FontStyle::Normal));
provider.register_typeface(typeface, Some(family.as_str()));
provider
}
/// `provider(font)` plus `fallback` registered as the "fallback" family.
pub(crate) fn provider_with_fallback(font: &[u8], fallback: &[u8]) -> TypefaceFontProvider {
let mut provider = provider(font);
let typeface = FontMgr::new()
.new_from_data(skia_safe::Data::new_copy(fallback), None)
.expect("failed to load fallback font");
provider.register_typeface(typeface, Some("fallback"));
provider
}
pub(crate) fn make_span(text: &str) -> TextSpan {
TextSpan {
text: text.to_string(),
font_size: EM,
line_height: 1.0,
..TextSpan::default()
}
}
pub(crate) fn vertical_paragraph(
spans: Vec<TextSpan>,
align: TextAlign,
line_height: f32,
) -> Paragraph {
let mut paragraph = Paragraph::new(
align,
TextDirection::LTR,
None,
None,
line_height,
0.0,
spans,
);
paragraph.set_writing_mode(WritingMode::VerticalRl);
paragraph.set_language("ja".to_string());
paragraph
}
/// A 200px wide box `height` tall holding `paragraphs`.
pub(crate) fn content_of(
paragraphs: Vec<Paragraph>,
height: f32,
grow_type: GrowType,
) -> TextContent {
crate::globals::design_init();
let mut content = TextContent::new(Rect::from_xywh(0.0, 0.0, 200.0, height), grow_type);
for paragraph in paragraphs {
content.add_paragraph(paragraph);
}
content
}
/// One left-aligned paragraph holding `spans`.
pub(crate) fn spans_content(spans: Vec<TextSpan>, height: f32) -> TextContent {
content_of(
vec![vertical_paragraph(spans, TextAlign::Left, 1.0)],
height,
GrowType::Fixed,
)
}
/// One paragraph per text, each a single span.
pub(crate) fn make_content(texts: &[&str], height: f32) -> TextContent {
let paragraphs = texts
.iter()
.map(|text| vertical_paragraph(vec![make_span(text)], TextAlign::Left, 1.0))
.collect();
content_of(paragraphs, height, GrowType::Fixed)
}
/// One paragraph with a span per text.
pub(crate) fn make_content_with_spans(texts: &[&str], height: f32) -> TextContent {
spans_content(texts.iter().map(|text| make_span(text)).collect(), height)
}
pub(crate) fn ruby_content(base: &str, ruby: &str, height: f32) -> TextContent {
spans_content(
vec![TextSpan {
ruby: ruby.to_string(),
..make_span(base)
}],
height,
)
}
pub(crate) fn warichu_content(base: &str, height: f32) -> TextContent {
spans_content(
vec![TextSpan {
warichu: true,
text_orientation: TextOrientation::Upright,
..make_span(base)
}],
height,
)
}
pub(crate) fn spaced_content(text: &str, letter_spacing: f32) -> TextContent {
spans_content(
vec![TextSpan {
letter_spacing,
..make_span(text)
}],
1000.0,
)
}
pub(crate) fn decorated_content(text: &str, decoration: TextDecoration) -> TextContent {
spans_content(
vec![TextSpan {
text_decoration: Some(decoration),
..make_span(text)
}],
1000.0,
)
}
pub(crate) fn layout_with_fallback(
provider: &TypefaceFontProvider,
content: &TextContent,
max_height: f32,
fallback_families: &[String],
) -> VerticalLayout {
layout_vertical(
content,
max_height,
provider,
FontMgr::from(provider.clone()),
&FallbackFonts::from_families(fallback_families.iter().cloned()),
content.bounds(),
)
}
pub(crate) fn layout_with_height(
provider: &TypefaceFontProvider,
content: &TextContent,
max_height: f32,
) -> VerticalLayout {
layout_with_fallback(provider, content, max_height, &[])
}
/// Layout with `provider` and a 1000px wrap budget.
pub(crate) fn layout_with(
provider: &TypefaceFontProvider,
content: &TextContent,
) -> VerticalLayout {
layout_with_height(provider, content, 1000.0)
}
/// Layout with the Latin test face.
pub(crate) fn layout_content(content: &TextContent, max_height: f32) -> VerticalLayout {
layout_with_height(&provider(TEST_FONT), content, max_height)
}