Merge approved PhotoCraft PR #9478: fix(text): vertical type sets roman letters upright, one per em, as Photoshop does (#9470)

Port behavior and regression coverage into current modules; preserve current upstream behavior.
Ported upright Roman classification, independent unkerned/unligated em advances and tab reflow into current Para/VerticalPiece shaping modules; preserved area and paragraph flow; retained vertical geometry and PSD BaselineDirection regressions.
This commit is contained in:
FredApps committed 2026-10-29 05:18:29 +01:00
commit 2e2eec3a43
8 files changed
+198 -14

No files matched your search

+6
View File
@@ -101,6 +101,11 @@ pub struct CharStyle {
pub variations: Vec<FontVariation>,
/// BCP-47 language tag (affects shaping and line breaking).
pub language: Option<String>,
/// Vertical type: roman text (Latin, digits) runs rotated 90° clockwise along the column
/// (PSD `BaselineDirection` 2) instead of standing upright one character per em
/// (`BaselineDirection` 1, what Photoshop's Vertical Type tool sets, #9470). CJK text stands
/// upright either way.
pub rotate_roman: bool,
/// Applied character style (id in [`crate::TextStyles`]); `None` = "None". Attributes above
/// stay fully resolved; differences from the style are local overrides.
#[serde(skip_serializing_if = "Option::is_none")]
@@ -135,6 +140,7 @@ impl Default for CharStyle {
features: Vec::new(),
variations: Vec::new(),
language: None,
rotate_roman: false,
style_sheet: None,
}
}
@@ -111,6 +111,7 @@ fn perturbed_char() -> CharStyle {
features: vec![FontFeature { tag: "\u{1}".into(), value: 9 }],
variations: vec![FontVariation { axis: "\u{1}".into(), value: -1.0 }],
language: Some("\u{1}".into()),
rotate_roman: true,
style_sheet: None,
}
}
+2 -2
View File
@@ -10,8 +10,8 @@
//! into text space: a line becomes a column running top to bottom, and successive columns advance
//! right to left. Within a column, CJK characters stay upright (centred on the column, placed with
//! the font's vertical metrics: `VORG`, `vhea`/`vmtx`, else the ideographic em box) and use the
//! font's vertical alternates (`vert`) for punctuation, brackets and the long-vowel mark; other
//! text (Latin, digits) runs rotated 90° clockwise, Photoshop's default. Lines, clusters, carets
//! font's vertical alternates (`vert`) for punctuation, brackets and the long-vowel mark. Roman
//! letters stand upright one per em unless the run sets `rotate_roman`. Lines, clusters, carets
//! and hit tests stay in line space; [`TextLayout::to_text`] / [`TextLayout::to_line`] convert.
use std::borrow::Cow;
+74 -6
View File
@@ -5,7 +5,7 @@ use std::borrow::Cow;
use std::cell::Cell;
use std::ops::Range;
use parley::{Alignment, AlignmentOptions, FontFeatures, Layout, LayoutContext, StyleProperty};
use parley::{Alignment, AlignmentOptions, FontFeatures, Layout, LayoutContext, PositionedLayoutItem, StyleProperty};
use photocraft_doc::text::{CharStyle, ParagraphStyle, TextAlign, TextDirection};
use super::area::{LineMetrics, MAX_AREA_PASSES, area_metrics, break_area};
@@ -161,7 +161,10 @@ impl VerticalPiece<'_> {
fn push_all(&self, b: &mut parley::RangedBuilder<'_, RunBrush>, piece: &str) {
let mut seg: Option<(usize, VClass)> = None;
for (i, ch) in piece.char_indices() {
let cls = vertical_class(ch);
let cls = match vertical_class(ch) {
VClass::Rotate if !self.style.rotate_roman && upright_roman(ch) => VClass::Upright,
cls => cls,
};
match seg {
Some((_, c)) if c == cls => {}
Some((from, c)) => {
@@ -193,6 +196,7 @@ pub(super) struct Para<'a> {
/// Runs intersecting the paragraph: `si0..si_end`.
si0: usize,
si_end: usize,
roman: Vec<(Range<usize>, f32, f32, usize)>,
fallback: Vec<String>,
pub(super) indent_start: f32,
indent_end: f32,
@@ -242,6 +246,7 @@ impl<'a> Para<'a> {
tabs,
si0,
si_end,
roman: Vec::new(),
fallback,
indent_start,
indent_end,
@@ -253,9 +258,33 @@ impl<'a> Para<'a> {
area_budget: Cell::new(MAX_AREA_PASSES),
};
para.break_scale = para.horizontal_break_scale();
para.roman = para.roman_ranges();
para
}
fn roman_ranges(&self) -> Vec<(Range<usize>, f32, f32, usize)> {
let env = self.env;
let mut roman = Vec::new();
if env.vertical {
for (ri, st) in env.styles.iter().enumerate().take(self.si_end).skip(self.si0) {
let rs = env.run_starts[ri];
let (a, z) = (rs.max(self.start), (rs + env.runs[ri].len).min(self.content_end));
if a >= z || st.rotate_roman {
continue;
}
let base = a - self.start + self.prefix.len();
let piece = self.ptext.get(base..base + (z - a)).unwrap_or("");
let px = st.size_pt * env.k;
for (i, ch) in piece.char_indices() {
if upright_roman(ch) && !ch.is_whitespace() {
roman.push(((base + i)..(base + i + ch.len_utf8()), st.tracking / 1000.0 * px, px, ri));
}
}
}
}
roman
}
pub(super) fn first_style(&self) -> &'a CharStyle {
&self.env.styles[self.si0]
}
@@ -290,7 +319,7 @@ impl<'a> Para<'a> {
}
/// Shapes the paragraph, each tab widened by its letter spacing in `tab_spacing` (px).
fn shape(&self, lcx: &mut LayoutContext<RunBrush>, fcx: &mut parley::FontContext, tab_spacing: &[f32]) -> Layout<RunBrush> {
fn shape(&self, lcx: &mut LayoutContext<RunBrush>, fcx: &mut parley::FontContext, tab_spacing: &[f32], roman_spacing: &[f32]) -> Layout<RunBrush> {
let env = self.env;
let mut b = lcx.ranged_builder(fcx, &self.ptext, 1.0, false);
// Paragraph-start style as the default (covers the direction mark and empty
@@ -318,6 +347,12 @@ impl<'a> Para<'a> {
for (&at, &spacing) in self.tabs.iter().zip(tab_spacing) {
b.push(StyleProperty::LetterSpacing(spacing), at..at + 1);
}
for ((range, _, _, ri), &spacing) in self.roman.iter().zip(roman_spacing) {
b.push(StyleProperty::LetterSpacing(spacing), range.clone());
let mut feats = feature_list(&env.styles[*ri], env.small_caps[*ri]);
feats.extend(["kern", "liga", "clig", "dlig"].map(|f| format!("\"{f}\" 0")));
b.push(StyleProperty::FontFeatures(FontFeatures::Source(Cow::Owned(feats.join(", ")))), range.clone());
}
b.build(&self.ptext)
}
@@ -383,11 +418,18 @@ impl<'a> Para<'a> {
/// that layout gives until they agree; if they don't settle, keep the safe layout.
pub(super) fn break_paragraph(&self, lcx: &mut LayoutContext<RunBrush>, fcx: &mut parley::FontContext, flow: &Flow) -> (Layout<RunBrush>, Vec<Slot>, bool) {
let wide = if self.env.wraps { self.tab_px } else { 0.0 };
let mut layout = self.shape(lcx, fcx, &vec![wide; self.tabs.len()]);
let mut roman_spacing: Vec<f32> = self.roman.iter().map(|r| r.1).collect();
let mut layout = self.shape(lcx, fcx, &vec![wide; self.tabs.len()], &roman_spacing);
if !self.roman.is_empty() {
let _ = self.break_lines(&mut layout, flow);
let advances = cluster_advances(&layout, &self.roman);
roman_spacing = self.roman.iter().zip(&advances).map(|((_, track, em, _), a)| a.map_or(*track, |a| em + track - (a - track))).collect();
layout = self.shape(lcx, fcx, &vec![wide; self.tabs.len()], &roman_spacing);
}
let (mut slots, mut full) = self.break_lines(&mut layout, flow);
if self.env.wraps
&& !self.tabs.is_empty()
&& let Some((settled, settled_slots, settled_full)) = self.settle_tabs(lcx, fcx, &layout, flow)
&& let Some((settled, settled_slots, settled_full)) = self.settle_tabs(lcx, fcx, &layout, flow, &roman_spacing)
{
layout = settled;
slots = settled_slots;
@@ -403,12 +445,13 @@ impl<'a> Para<'a> {
fcx: &mut parley::FontContext,
layout: &Layout<RunBrush>,
flow: &Flow,
roman_spacing: &[f32],
) -> Option<(Layout<RunBrush>, Vec<Slot>, bool)> {
let first = self.tab_widths(layout);
let mut want: Vec<f32> = first.iter().map(|t| t.width).collect();
for _ in 0..4 {
let spacing: Vec<f32> = first.iter().zip(&want).map(|(t, w)| w / t.scale - (t.advance - self.tab_px)).collect();
let mut next = self.shape(lcx, fcx, &spacing);
let mut next = self.shape(lcx, fcx, &spacing, roman_spacing);
let (next_slots, next_full) = self.break_lines(&mut next, flow);
let got: Vec<f32> = self.tab_widths(&next).iter().map(|t| t.width).collect();
if got.iter().zip(&want).all(|(a, b)| (a - b).abs() < 0.01) {
@@ -436,3 +479,28 @@ impl<'a> Para<'a> {
AlignmentOptions { align_when_overflowing: !self.env.wraps }
}
}
/// Whether vertical type sets `c` upright when its style doesn't rotate roman text (#9470): the
/// rotating class except half-width katakana and Hangul, which keep their rotated setting.
fn upright_roman(c: char) -> bool {
vertical_class(c) == VClass::Rotate && !(0xFF61..=0xFFDC).contains(&(c as u32))
}
/// The shaped advance (px, letter spacing included) of the cluster starting each of `ranges`
/// (sorted byte ranges of the shaped text), `None` where no cluster starts there.
fn cluster_advances(layout: &Layout<RunBrush>, ranges: &[(Range<usize>, f32, f32, usize)]) -> Vec<Option<f32>> {
let mut out = vec![None; ranges.len()];
for line in layout.lines() {
for item in line.items() {
let PositionedLayoutItem::GlyphRun(gr) = item else {
continue;
};
for c in gr.run().visual_clusters() {
if let Ok(i) = ranges.binary_search_by_key(&c.text_range().start, |r| r.0.start) {
out[i] = Some(c.advance());
}
}
}
}
out
}
+19
View File
@@ -218,6 +218,25 @@ mod nonfinite_tests {
assert_eq!(char_style(&[], &d, &[], 1.0).size_pt, 24.0);
}
/// #9470: `BaselineDirection` sets vertical type's roman text upright (1, what Photoshop's
/// Vertical Type tool writes in the run) or rotated (2); a run without one takes the style
/// sheet's (Photoshop's default sheet says 2). It is written back.
#[test]
fn baseline_direction_round_trips() {
let sheet = parse(b"<< /BaselineDirection 2 >>").unwrap();
let upright = parse(b"<< /BaselineDirection 1 >>").unwrap();
assert!(!char_style(&[Some(&sheet)], &upright, &[], 1.0).rotate_roman, "the run's own value wins");
let plain = parse(b"<< /FontSize 24.0 >>").unwrap();
assert!(char_style(&[Some(&sheet)], &plain, &[], 1.0).rotate_roman, "else the sheet's");
assert!(!char_style(&[], &plain, &[], 1.0).rotate_roman, "none at all: upright");
for rotate in [false, true] {
let s = CharStyle { rotate_roman: rotate, ..Default::default() };
let data = style_sheet_data(&s, 0, 1.0);
assert_eq!(data.get("BaselineDirection").and_then(E::as_i64), Some(if rotate { 2 } else { 1 }));
assert_eq!(char_style(&[Some(&sheet)], &data, &[], 1.0).rotate_roman, rotate);
}
}
/// #5645: `FontBaseline` (1 superscript, 2 subscript) is read and written back.
#[test]
fn font_baseline_round_trips() {
+1
View File
@@ -54,6 +54,7 @@ pub(crate) fn style_sheet_data(s: &CharStyle, font: usize, k: f32) -> E {
FontBaseline::Subscript => 2,
}),
),
("BaselineDirection".into(), E::Int(if s.rotate_roman { 2 } else { 1 })),
("Underline".into(), E::Bool(s.underline)),
("Strikethrough".into(), E::Bool(s.strikethrough)),
("Ligatures".into(), E::Bool(s.ligatures)),
+3
View File
@@ -590,6 +590,9 @@ pub(crate) fn char_style(base: &[Option<&E>], d: &E, fonts: &[String], k: f32) -
Some(2) => FontBaseline::Subscript,
_ => FontBaseline::Normal,
};
// Vertical type's roman text: 2 rotated along the column, 1 upright (#9470). A run without
// its own value takes the style sheet's, which Photoshop writes as 2.
s.rotate_roman = g("BaselineDirection").and_then(E::as_i64) == Some(2);
if let Some(c) = g("FillColor") {
// Positions matter (alpha, then the channels): a non-finite entry voids the colour.
let v: Vec<f64> = c.get("Values").and_then(E::as_array).map(|a| a.iter().filter_map(E::as_f64).collect()).unwrap_or_default();
+92 -6
View File
@@ -19,6 +19,15 @@ fn vertical(text: &str, family: &str, size_pt: f32) -> TextLayer {
}
}
/// [`vertical`] with its roman text rotated along the column (PSD `BaselineDirection` 2).
fn rotated(text: &str, family: &str, size_pt: f32) -> TextLayer {
let mut t = vertical(text, family, size_pt);
for r in &mut t.runs {
r.style.rotate_roman = true;
}
t
}
/// An engine with an installed Japanese font registered, and that font's family.
fn cjk_engine() -> Option<(TextEngine, String)> {
#[cfg(not(target_arch = "wasm32"))]
@@ -53,7 +62,7 @@ fn classes_follow_vertical_orientation() {
#[test]
fn latin_is_rotated_and_runs_down_columns_right_to_left() {
let mut e = TextEngine::new();
let l = e.layout(&vertical("abc\nde", "Inter", 20.0), 72.0);
let l = e.layout(&rotated("abc\nde", "Inter", 20.0), 72.0);
assert!(l.vertical);
assert_eq!(l.lines.len(), 2);
assert!(l.glyphs.iter().all(|g| g.orient == GlyphOrient::Rotated));
@@ -67,16 +76,90 @@ fn latin_is_rotated_and_runs_down_columns_right_to_left() {
// Rotated text is centred on the column through the anchor (x = 0): its baseline sits left.
assert!(a.x < 0.0 && a.x > -10.0, "{a:?}");
// Bounds: one column for "abc" is taller than wide.
let one = e.layout(&vertical("abcdef", "Inter", 20.0), 72.0);
let one = e.layout(&rotated("abcdef", "Inter", 20.0), 72.0);
let [x0, y0, x1, y1] = one.bounds().unwrap();
assert!((y1 - y0) > 2.0 * (x1 - x0), "{:?}", one.bounds());
assert!((x0 + 10.0).abs() < 1e-3 && (x1 - 10.0).abs() < 1e-3 && y0.abs() < 1e-3);
}
/// #9470: Photoshop's Vertical Type tool sets roman text upright, one character per em down the
/// column (`BaselineDirection` 1): a word is a stack of letters, not the word turned on its side.
#[test]
fn latin_stands_upright_one_per_em_by_default() {
let mut e = TextEngine::new();
let l = e.layout(&vertical("VERTICAL", "Inter", 36.0), 72.0);
assert!(l.vertical);
assert!(l.glyphs.iter().all(|g| g.orient == GlyphOrient::Upright), "{:?}", l.glyphs);
// One em (36 px) per character down a single column.
let steps: Vec<f32> = l.glyphs.windows(2).map(|w| w[1].y - w[0].y).collect();
assert!(steps.iter().all(|d| (d - 36.0).abs() < 0.5), "{steps:?}");
assert!(l.glyphs.windows(2).all(|w| (w[1].x - w[0].x).abs() < 6.0), "one column: {:?}", l.glyphs);
// Rendered: a narrow stack about 8 em tall, much taller than the rotated word.
let at = Affine::translate(200.0, 40.0);
let (_, up) = e.render(&TextLayer { transform: at, ..vertical("VERTICAL", "Inter", 36.0) }, 72.0, PixelFormat::RGBA8);
let (_, turned) = e.render(&TextLayer { transform: at, ..rotated("VERTICAL", "Inter", 36.0) }, 72.0, PixelFormat::RGBA8);
assert!(up.rect.width() < 40 && up.rect.height() > 7 * 36, "{:?}", up.rect);
assert!(up.rect.height() > turned.rect.height() + 50, "{:?} vs {:?}", up.rect, turned.rect);
}
/// An engine with an installed font that joins "fi" into one ligature glyph, and its family.
fn ligature_engine() -> Option<(TextEngine, String)> {
#[cfg(not(target_arch = "wasm32"))]
for path in [
"/System/Library/Fonts/Supplemental/Hoefler Text.ttc",
"/System/Library/Fonts/Supplemental/Baskerville.ttc",
"/System/Library/Fonts/Supplemental/Didot.ttc",
"/System/Library/Fonts/Times.ttc",
"/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
"/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf",
"C:\\Windows\\Fonts\\calibri.ttf",
"C:\\Windows\\Fonts\\cambria.ttc",
] {
let Ok(bytes) = std::fs::read(path) else { continue };
let mut e = TextEngine::new();
for fam in e.fonts.register_font_data(bytes) {
let flat = TextLayer { orientation: Orientation::Horizontal, ..vertical("fi", &fam, 30.0) };
if e.layout(&flat, 72.0).glyphs.len() == 1 {
return Some((e, fam));
}
}
}
eprintln!("no installed font with an fi ligature found: skipping");
None
}
/// CodeRabbit on #9478: upright roman letters never join into a ligature; "fi" and "ffl" are
/// one glyph per letter, one em apart.
#[test]
fn upright_roman_letters_stay_apart_without_ligatures() {
let Some((mut e, fam)) = ligature_engine() else { return };
for text in ["fi", "ffl", "office"] {
let l = e.layout(&vertical(text, &fam, 30.0), 72.0);
assert_eq!(l.glyphs.len(), text.chars().count(), "{fam} {text}: one glyph per letter: {:?}", l.glyphs);
let steps: Vec<f32> = l.glyphs.windows(2).map(|w| w[1].y - w[0].y).collect();
assert!(steps.iter().all(|d| (d - 30.0).abs() < 0.5), "{fam} {text}: one em apart: {steps:?}");
}
}
/// CodeRabbit on #9478: half-width katakana and Hangul keep their rotated setting; only roman
/// text stands upright by default (#9470 leaves CJK as it was).
#[test]
fn half_width_cjk_stays_rotated_beside_upright_roman() {
let mut e = TextEngine::new();
for text in ["アイウ", "ᄀᄁᆪ"] {
let l = e.layout(&vertical(text, "Inter", 24.0), 72.0);
assert!(!l.glyphs.is_empty());
assert!(l.glyphs.iter().all(|g| g.orient == GlyphOrient::Rotated), "{text}: {:?}", l.glyphs);
}
let l = e.layout(&vertical("A", "Inter", 24.0), 72.0);
assert!(l.glyphs.iter().all(|g| g.orient == GlyphOrient::Upright), "roman stays upright");
}
#[test]
fn rotated_render_ink_is_taller_than_wide() {
let mut e = TextEngine::new();
let horizontal = TextLayer { orientation: Orientation::Horizontal, ..vertical("Vertical", "Inter", 30.0) };
let horizontal = TextLayer { orientation: Orientation::Horizontal, ..rotated("Vertical", "Inter", 30.0) };
let (_, h) = e.render(&TextLayer { transform: Affine::translate(100.0, 50.0), ..horizontal.clone() }, 72.0, PixelFormat::RGBA8);
let (_, v) = e.render(&TextLayer { transform: Affine::translate(100.0, 50.0), orientation: Orientation::Vertical, ..horizontal }, 72.0, PixelFormat::RGBA8);
assert!(h.rect.width() > h.rect.height());
@@ -109,7 +192,7 @@ fn caret_hit_test_and_arrow_geometry_follow_columns() {
#[test]
fn box_text_wraps_columns_within_the_box_height() {
let mut e = TextEngine::new();
let t = TextLayer { shape: TextShape::Box { x: 10.0, y: 20.0, width: 200.0, height: 60.0 }, ..vertical("ab cd ef gh ij kl mn op", "Inter", 20.0) };
let t = TextLayer { shape: TextShape::Box { x: 10.0, y: 20.0, width: 200.0, height: 60.0 }, ..rotated("ab cd ef gh ij kl mn op", "Inter", 20.0) };
let l = e.layout(&t, 72.0);
assert!(l.lines.len() >= 3, "{}", l.lines.len());
let [x0, y0, x1, y1] = l.bounds().unwrap();
@@ -163,8 +246,11 @@ fn cjk_is_upright_centred_with_vertical_alternates() {
} else {
assert_eq!(dash.orient, GlyphOrient::Rotated);
}
// Latin inside vertical CJK runs rotated.
assert_eq!(g[9].orient, GlyphOrient::Rotated);
// Latin inside vertical CJK stands upright (Photoshop's Vertical Type tool), or rotated when
// its style says so.
assert_eq!(g[9].orient, GlyphOrient::Upright);
let r = e.layout(&rotated(text, &fam, 40.0), 72.0);
assert_eq!(r.glyphs[9].orient, GlyphOrient::Rotated);
// Punctuation squeeze: 、「 takes 1.5 em down the column, ト、 keeps full cells.
let s = e.layout(&vertical("ト、「東", &fam, 40.0), 72.0);
let cx: Vec<f32> = s.clusters.iter().map(|c| c.x).collect();