Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Ruby: placement, spacing, font, size, overhang, scaling and colour settings with JLReq layout and IDML

aionggd9bc53d7f813
diff --git a/crates/compose/src/kenten.rs b/crates/compose/src/kenten.rs
index 7fdb3be3b..f32d95547 100644
--- a/crates/compose/src/kenten.rs
+++ b/crates/compose/src/kenten.rs
@@ -137,6 +137,7 @@ fn shape_mark(face: FaceRef, text: &str, m: &KentenMark, b: &PlacedGlyph) -> Vec
upright: upright_in_vertical(ch),
tcy: None,
rtl: false,
+ dx: 0.0,
});
x += adv;
}
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 655b60db6..8102f5aa2 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -72,6 +72,13 @@ pub struct RunStyle {
pub xml_tag: Option<String>,
/// Ruby over the run.
pub ruby: Option<String>,
+ /// The ruby's settings (set with `ruby`), and for per-character ruby the parent character's
+ /// place in its run (see `ruby::reserve`).
+ pub ruby_spec: Option<designcraft_doc::ruby::RubySpec>,
+ pub ruby_unit: Option<u32>,
+ /// Overprint the fill and stroke (ruby glyphs set to overprint).
+ pub overprint_fill: bool,
+ pub overprint_stroke: bool,
/// Warichu: stack this run in smaller lines inside the parent em.
pub warichu: bool,
pub warichu_lines: u32,
@@ -138,6 +145,9 @@ pub struct PlacedGlyph {
pub tcy: Option<[f64; 3]>,
/// Set right to left (an odd bidi level): the caret before it is at its right edge.
pub rtl: bool,
+ /// How far after its pen position the glyph is drawn (CJK aki, ruby parent spacing): its
+ /// advance starts at `x - dx`.
+ pub dx: f64,
}
impl PlacedGlyph {
@@ -1084,7 +1094,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, ends_para, forced_mid, f.left_page, &bidi_info);
// Warichu runs before ruby so a reading is placed over the stacked note.
let end_x = end_x + warichu::place(&styles_tab, &mut placed);
- ruby::annotate(&styles_tab, &mut placed);
+ ruby::annotate(db, &mut styles_tab, &story.text, &mut placed, doc.settings.glyph_fallback, f.vertical);
kenten::annotate(db, &styles_tab, &mut placed, doc.settings.glyph_fallback);
let range_end = if last { prange.end } else { glyphs.get(g0 + b.next).map(|g| g.byte).unwrap_or(prange.end) };
let range_start = glyphs.get(s).map(|g| g.byte).unwrap_or(prange.start).min(range_end);
@@ -2438,6 +2448,7 @@ fn layout_line(
if scale[i] != 1.0 {
p.sx *= scale[i];
p.x = x + g.dx * scale[i];
+ p.dx = g.dx * scale[i];
p.adv *= scale[i];
}
p.adv += add[i];
@@ -2471,7 +2482,7 @@ fn layout_line(
}
// One tatweel stretched over the gap (overlapping its neighbours a little).
let k = (l + 0.4) / w;
- out.push(PlacedGlyph { gid, x: at - 0.2, y: -g.shift, adv: 0.0, sx: g.sx * k, len: 0, upright: false, tcy: None, ..place(g, at) });
+ out.push(PlacedGlyph { gid, x: at - 0.2, y: -g.shift, adv: 0.0, sx: g.sx * k, len: 0, upright: false, tcy: None, dx: 0.0, ..place(g, at) });
}
(out, x, ratio)
}
@@ -2592,6 +2603,7 @@ fn tab_leader(tab: &Glyph, leader: &str, x: f64, w: f64, origin: f64, out: &mut
upright: false,
tcy: None,
rtl: false,
+ dx: 0.0,
});
at += adv;
}
@@ -2697,6 +2709,7 @@ fn place(g: &Glyph, x: f64) -> PlacedGlyph {
upright: g.upright,
tcy: g.tcy,
rtl: false,
+ dx: g.dx,
}
}
diff --git a/crates/compose/src/ruby.rs b/crates/compose/src/ruby.rs
index 2b2db84ef..e761f1689 100644
--- a/crates/compose/src/ruby.rs
+++ b/crates/compose/src/ruby.rs
@@ -1,86 +1,673 @@
//! Ruby: small glyphs set over laid-out text (to its right in vertical frames, where the frame's
-//! turn carries "above" there). They don't change line breaks or leading. Kenten are in
-//! [`crate::kenten`].
+//! turn carries "above" there), or under it (to its left). Kenten are in [`crate::kenten`].
+//!
+//! Ruby follows JIS X 4051 / JLReq §3.3. Before line breaking, [`reserve`] splits per-character
+//! ruby into one unit per parent character, keeps group ruby on one line, and spaces out parent
+//! characters whose ruby is longer than they are by what overhang onto the neighbours can't take.
+//! After line breaking, [`annotate`] sets the ruby glyphs with the same arithmetic on the placed
+//! line. Ruby doesn't change leading.
+use designcraft_doc::cjk_settings::AdornmentOverprint;
+use designcraft_doc::ruby::{MAX_RUBY_CHARS, RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubySpec, RubyType};
+use designcraft_fonts::{FaceRef, ScopedFonts};
+
+use crate::shape::Glyph;
use crate::{PlacedGlyph, RunStyle, upright_in_vertical};
-/// Ruby is half the base size.
-const SCALE: f64 = 0.5;
-
-/// A glyph of `text` set at `size` in `base`'s font from `x`, above the base text; returns them
-/// and their total advance.
-fn set(base: &PlacedGlyph, text: &str, size: f64, base_size: f64) -> (Vec<PlacedGlyph>, f64) {
- let face = &base.face;
- let k = size / face.units_per_em();
- // Its baseline clears the base text's em box top.
- let y = -(base_size * 0.88 + size * 0.2);
- let mut x = 0.0;
- let mut out = Vec::new();
- for sg in designcraft_fonts::shape(face, text, &[], |c| c) {
- let ch = text[sg.cluster..].chars().next().unwrap_or(' ');
- let adv = sg.x_advance as f64 * k;
- out.push(PlacedGlyph {
+/// `text` cut to the longest reading laid out, at a character boundary.
+pub(crate) fn capped(text: &str) -> &str {
+ match text.char_indices().nth(MAX_RUBY_CHARS) {
+ Some((i, _)) => text.get(..i).unwrap_or(text),
+ None => text,
+ }
+}
+
+// ---------- ruby text ----------
+
+/// A shaped ruby glyph, `x` from the ruby's start.
+#[derive(Clone, Debug)]
+struct RubyGlyph {
+ gid: u32,
+ ch: char,
+ x: f64,
+ y: f64,
+ adv: f64,
+ sx: f64,
+ sy: f64,
+ tcy: Option<[f64; 3]>,
+ /// Part of the tate-chu-yoko group the previous glyph started (spread as one character).
+ joined: bool,
+}
+
+/// A run's ruby, shaped in its font at its size.
+struct Shaped {
+ face: FaceRef,
+ glyphs: Vec<RubyGlyph>,
+ width: f64,
+ size: f64,
+ /// Width of one ruby character (the unit of overhang and of 1-aki alignment).
+ em: f64,
+}
+
+/// The ruby's face: its own font, else the parent glyph's. With `fallback`, a face that lacks a
+/// character of `text` gives way to a fallback font for it.
+fn ruby_face(db: &ScopedFonts<'_>, parent: FaceRef, spec: &RubySpec, text: &str, fallback: bool) -> FaceRef {
+ let face = if spec.font_family.is_empty() {
+ parent
+ } else {
+ let style = if spec.font_style.is_empty() { "Regular" } else { spec.font_style.as_str() };
+ FaceRef::of(&db.face(&spec.font_family, style))
+ };
+ if fallback
+ && let Some(c) = text.chars().find(|c| !c.is_whitespace() && !face.covers(*c))
+ && let Some(f) = db.fallback_for(c, face.id(), None)
+ {
+ return FaceRef::of(&f);
+ }
+ face
+}
+
+fn tcy_char(c: char, roman: bool) -> bool {
+ c.is_ascii_digit() || (roman && c.is_ascii_alphabetic())
+}
+
+/// Shape `text` as the ruby of parent text `parent_size` points big.
+fn shape_ruby(db: &ScopedFonts<'_>, parent: FaceRef, text: &str, spec: &RubySpec, parent_size: f64, fallback: bool, vertical: bool) -> Shaped {
+ let size = spec.size_for(parent_size);
+ let face = ruby_face(db, parent, spec, text, fallback);
+ let upem = face.units_per_em();
+ let k = if upem > 0.0 { size / upem } else { 0.0 };
+ let (sx, sy) = (k * spec.x_scale, k * spec.y_scale);
+ let features: Vec<designcraft_fonts::Feature> =
+ if spec.open_type_pro { designcraft_fonts::feature("ruby").into_iter().collect() } else { Vec::new() };
+ let mut glyphs: Vec<RubyGlyph> = designcraft_fonts::shape(&face, text, &features, |c| c)
+ .into_iter()
+ .map(|sg| RubyGlyph {
gid: sg.gid,
- x: x + sg.x_offset as f64 * k,
- y: y - sg.y_offset as f64 * k,
- adv,
- sx: k,
- sy: k,
- len: 0,
- visible: true,
- upright: upright_in_vertical(ch),
+ ch: text.get(sg.cluster..).and_then(|s| s.chars().next()).unwrap_or(' '),
+ x: sg.x_offset as f64 * sx,
+ y: -(sg.y_offset as f64) * sy,
+ adv: sg.x_advance as f64 * sx,
+ sx,
+ sy,
tcy: None,
- rtl: false,
- ..base.clone()
- });
- x += adv;
+ joined: false,
+ })
+ .collect();
+ // Tate-chu-yoko: short runs of digits (and Latin letters) take one ruby em along the line.
+ if vertical && spec.auto_tcy_digits > 0 {
+ let roman = spec.auto_tcy_include_roman;
+ let mut i = 0;
+ while i < glyphs.len() {
+ let j = i + glyphs.get(i..).unwrap_or_default().iter().take_while(|g| tcy_char(g.ch, roman)).count();
+ if j == i {
+ i += 1;
+ continue;
+ }
+ if u32::try_from(j - i).is_ok_and(|n| n <= spec.auto_tcy_digits)
+ && let Some(run) = glyphs.get_mut(i..j)
+ {
+ let total: f64 = run.iter().map(|g| g.adv).sum();
+ let f = if spec.auto_tcy_auto_scale && total > size && total > 0.0 { size / total } else { 1.0 };
+ let mut across = -total * f / 2.0;
+ for (n, g) in run.iter_mut().enumerate() {
+ g.tcy = Some([size / 2.0, across + g.x * f, size]);
+ across += g.adv * f;
+ g.sx *= f;
+ g.x = 0.0;
+ g.adv = if n == 0 { size } else { 0.0 };
+ g.joined = n > 0;
+ }
+ }
+ i = j;
+ }
+ }
+ // Pen positions: a joined glyph sits at its group's start.
+ let mut pen = 0.0;
+ let mut start = 0.0;
+ for g in &mut glyphs {
+ if !g.joined {
+ start = pen;
+ }
+ g.x += start;
+ pen += g.adv;
+ }
+ Shaped { face, glyphs, width: pen, size, em: size * spec.x_scale }
+}
+
+// ---------- overhang ----------
+
+/// What is next to a ruby's parent text along the line.
+#[derive(Clone, Copy, Debug)]
+enum Side {
+ /// The line's (or paragraph's) start or end.
+ Edge,
+ /// A character with no ruby.
+ Char { ch: char, adv: f64 },
+ /// A character with ruby: `free` is the room its ruby leaves on this side (only a
+ /// neighbouring per-character ruby unit leaves any, as in jukugo ruby).
+ Ruby { free: f64 },
+}
+
+fn is_kana(c: char) -> bool {
+ matches!(c, '\u{3041}'..='\u{309F}' | '\u{30A0}'..='\u{30FA}' | '\u{30FC}'..='\u{30FF}' | '\u{31F0}'..='\u{31FF}' | '\u{FF66}'..='\u{FF9F}')
+}
+
+/// Opening brackets (JLReq cl-01): their first half is blank.
+fn is_opening(c: char) -> bool {
+ matches!(
+ c,
+ '\u{2018}'
+ | '\u{201C}'
+ | '\u{3008}'
+ | '\u{300A}'
+ | '\u{300C}'
+ | '\u{300E}'
+ | '\u{3010}'
+ | '\u{3014}'
+ | '\u{3016}'
+ | '\u{3018}'
+ | '\u{301D}'
+ | '\u{FF08}'
+ | '\u{FF3B}'
+ | '\u{FF5B}'
+ | '\u{FF5F}'
+ )
+}
+
+/// Closing brackets, commas and full stops (JLReq cl-02, cl-06, cl-07): their second half is
+/// blank.
+fn is_closing(c: char) -> bool {
+ matches!(
+ c,
+ '\u{2019}'
+ | '\u{201D}'
+ | '\u{3001}'
+ | '\u{3002}'
+ | '\u{3009}'
+ | '\u{300B}'
+ | '\u{300D}'
+ | '\u{300F}'
+ | '\u{3011}'
+ | '\u{3015}'
+ | '\u{3017}'
+ | '\u{3019}'
+ | '\u{301F}'
+ | '\u{FF09}'
+ | '\u{FF0C}'
+ | '\u{FF0E}'
+ | '\u{FF3D}'
+ | '\u{FF5D}'
+ | '\u{FF60}'
+ )
+}
+
+/// Middle dots, colons and semicolons (JLReq cl-05): a quarter blank on each side.
+fn is_middle_dot(c: char) -> bool {
+ matches!(c, '\u{30FB}' | '\u{FF1A}' | '\u{FF1B}')
+}
+
+/// How far a ruby may extend over `side` (before the parent when `before`), in points. Ruby
+/// goes over kana and the blank part of punctuation, never over kanji or Latin text.
+fn allowance(spec: &RubySpec, ruby_em: f64, parent_em: f64, side: Side, before: bool) -> f64 {
+ let amount = match spec.overhang {
+ RubyOverhang::None => 0.0,
+ RubyOverhang::OneRuby => ruby_em,
+ RubyOverhang::HalfRuby => ruby_em / 2.0,
+ RubyOverhang::OneChar => parent_em,
+ RubyOverhang::HalfChar => parent_em / 2.0,
+ RubyOverhang::NoLimit => f64::INFINITY,
+ };
+ let cap = match side {
+ // Auto-align sets a longer ruby flush with the line's edge.
+ Side::Edge => {
+ if spec.auto_align {
+ 0.0
+ } else {
+ f64::INFINITY
+ }
+ }
+ Side::Ruby { free } => free,
+ Side::Char { ch, adv } => {
+ if is_kana(ch) {
+ adv
+ } else if (before && is_opening(ch)) || (!before && is_closing(ch)) {
+ adv / 2.0
+ } else if is_middle_dot(ch) {
+ adv / 4.0
+ } else {
+ 0.0
+ }
+ }
+ };
+ amount.min(cap).max(0.0)
+}
+
+/// The overhang allowances the alignment can use: flush-start ruby only extends after its
+/// parent, flush-end ruby only before it.
+fn usable(align: RubyAlignment, before: f64, after: f64) -> (f64, f64) {
+ match align {
+ RubyAlignment::Left => (0.0, after),
+ RubyAlignment::Right => (before, 0.0),
+ _ => (before, after),
+ }
+}
+
+/// The factor a longer ruby is narrowed by to fit its parent and overhang (1.0 = not at all).
+fn auto_scale(spec: &RubySpec, ruby: f64, parent: f64, room: f64) -> f64 {
+ if !spec.auto_scaling || ruby <= 0.0 || ruby <= parent + room {
+ return 1.0;
+ }
+ ((parent + room) / ruby).max(spec.scaling_min).min(1.0)
+}
+
+/// How far before its parent's start a ruby `excess` longer than the parent starts, given the
+/// overhang allowed `before` and `after`: centred where the neighbours allow it, else pushed
+/// towards the side that takes more.
+fn lead_overhang(align: RubyAlignment, excess: f64, before: f64, after: f64) -> f64 {
+ match align {
+ RubyAlignment::Left => 0.0,
+ RubyAlignment::Right => excess,
+ _ => {
+ let lo = (excess - after).max(0.0);
+ let hi = before.min(excess);
+ if lo <= hi { (excess / 2.0).max(lo).min(hi) } else { excess / 2.0 }
+ }
+ }
+}
+
+/// Offsets from the parent's start of the ruby's characters (`advs`, one per slot) over a parent
+/// `width` wide that is at least as wide as they are.
+fn spread(align: RubyAlignment, width: f64, advs: &[f64], ruby_em: f64) -> Vec<f64> {
+ let n = advs.len();
+ if n == 0 {
+ return Vec::new();
+ }
+ let w: f64 = advs.iter().sum();
+ let gap = (width - w).max(0.0);
+ let nf = n as f64;
+ let jis = (gap / (2.0 * nf), gap / nf);
+ let (lead, inner) = match align {
+ RubyAlignment::Left => (0.0, 0.0),
+ RubyAlignment::Center => (gap / 2.0, 0.0),
+ RubyAlignment::Right => (gap, 0.0),
+ RubyAlignment::FullJustify if n > 1 => (0.0, gap / (nf - 1.0)),
+ RubyAlignment::FullJustify => (gap / 2.0, 0.0),
+ RubyAlignment::Jis => jis,
+ RubyAlignment::EqualAki => (gap / (nf + 1.0), gap / (nf + 1.0)),
+ RubyAlignment::OneAki if n == 1 => (gap / 2.0, 0.0),
+ RubyAlignment::OneAki if gap >= ruby_em => (ruby_em / 2.0, (gap - ruby_em) / (nf - 1.0)),
+ RubyAlignment::OneAki => jis,
+ };
+ let mut out = Vec::with_capacity(n);
+ let mut x = lead;
+ for a in advs {
+ out.push(x);
+ x += a + inner;
+ }
+ out
+}
+
+/// The space to add around and between `n` parent characters to make them `need` wider: (before
+/// the first, between each two, after the last).
+fn parent_spacing(mode: RubyParentSpacing, n: usize, need: f64) -> Option<(f64, f64, f64)> {
+ if n == 0 || !need.is_finite() || need <= 1e-9 {
+ return None;
+ }
+ let nf = n as f64;
+ Some(match mode {
+ RubyParentSpacing::NoAdjustment => return None,
+ RubyParentSpacing::BothSides => (need / 2.0, 0.0, need / 2.0),
+ RubyParentSpacing::Aki121 => (need / (2.0 * nf), need / nf, need / (2.0 * nf)),
+ RubyParentSpacing::EqualAki => (need / (nf + 1.0), need / (nf + 1.0), need / (nf + 1.0)),
+ RubyParentSpacing::FullJustify if n > 1 => (0.0, need / (nf - 1.0), 0.0),
+ RubyParentSpacing::FullJustify => (need / 2.0, 0.0, need / 2.0),
+ })
+}
+
+fn intern(styles: &mut Vec<RunStyle>, rs: RunStyle) -> u32 {
+ if let Some(i) = styles.iter().rposition(|s| *s == rs) {
+ return u32::try_from(i).unwrap_or(u32::MAX);
+ }
+ styles.push(rs);
+ u32::try_from(styles.len().saturating_sub(1)).unwrap_or(u32::MAX)
+}
+
+/// What groups glyphs under one ruby: its reading and, for per-character ruby, its unit.
+fn ruby_key(st: &RunStyle) -> Option<(&str, Option<u32>)> {
+ st.ruby.as_deref().map(|t| (t, st.ruby_unit))
+}
+
+/// The room a per-character ruby unit's reading leaves on each side of its parent `adv` wide.
+fn unit_free(db: &ScopedFonts<'_>, face: FaceRef, adv: f64, st: &RunStyle, mono: bool, fallback: bool, vertical: bool) -> f64 {
+ match (mono, st.ruby_unit, st.ruby.as_deref(), st.ruby_spec.as_ref()) {
+ (true, Some(_), Some(t), Some(sp)) => {
+ let w = shape_ruby(db, face, t, sp, st.size, fallback || st.missing_font, vertical).width;
+ ((adv - w) / 2.0).max(0.0)
+ }
+ _ => 0.0,
+ }
+}
+
+// ---------- before line breaking ----------
+
+/// Prepare a shaped paragraph's ruby: one unit per parent character for per-character ruby,
+/// no breaks inside group ruby, and parent spacing where a longer ruby needs it. `fallback`: the
+/// document draws missing glyphs from fallback fonts.
+pub(crate) fn reserve(db: &ScopedFonts<'_>, styles: &mut Vec<RunStyle>, glyphs: &mut [Glyph], fallback: bool, vertical: bool) {
+ if !glyphs.iter().any(|g| styles.get(g.style as usize).is_some_and(|s| s.ruby.is_some())) {
+ return;
+ }
+ let in_group = |styles: &[RunStyle], g: &Glyph, key: (&str, Option<u32>)| {
+ g.len == 0 || styles.get(g.style as usize).and_then(ruby_key).is_some_and(|k| k == key)
+ };
+ // Per-character ruby: each parent character gets its own reading.
+ let mut i = 0;
+ while i < glyphs.len() {
+ let Some(st) = glyphs.get(i).and_then(|g| styles.get(g.style as usize)) else {
+ i += 1;
+ continue;
+ };
+ let Some(text) = st.ruby.clone() else {
+ i += 1;
+ continue;
+ };
+ let mono = st.ruby_unit.is_none() && st.ruby_spec.as_ref().is_some_and(|s| s.kind == RubyType::PerCharacter);
+ let mut j = i + 1;
+ while glyphs.get(j).is_some_and(|g| in_group(styles.as_slice(), g, (text.as_str(), None))) {
+ j += 1;
+ }
+ if mono {
+ let parents: Vec<usize> = (i..j).filter(|&k| glyphs.get(k).is_some_and(|g| g.len > 0)).collect();
+ if let Some(readings) = designcraft_doc::ruby::mono_readings(&text, parents.len()) {
+ for (u, (&k, reading)) in parents.iter().zip(readings).enumerate() {
+ let end = parents.get(u + 1).copied().unwrap_or(j);
+ let Some(mut rs) = glyphs.get(k).and_then(|g| styles.get(g.style as usize)).cloned() else { continue };
+ rs.ruby = (!reading.is_empty()).then(|| reading.to_string());
+ rs.ruby_unit = Some(u32::try_from(u).unwrap_or(u32::MAX));
+ let idx = intern(styles, rs);
+ for g in glyphs.get_mut(k..end).unwrap_or_default() {
+ g.style = idx;
+ }
+ }
+ }
+ }
+ i = j;
+ }
+ // Parent spacing and breaks, group by group.
+ let mut i = 0;
+ while i < glyphs.len() {
+ let Some(st) = glyphs.get(i).and_then(|g| styles.get(g.style as usize)) else {
+ i += 1;
+ continue;
+ };
+ let (Some((text, unit)), Some(spec)) = (ruby_key(st).map(|(t, u)| (t.to_string(), u)), st.ruby_spec.clone()) else {
+ i += 1;
+ continue;
+ };
+ let missing = st.missing_font;
+ let mut j = i + 1;
+ while glyphs.get(j).is_some_and(|g| in_group(styles.as_slice(), g, (text.as_str(), unit))) {
+ j += 1;
+ }
+ let parents: Vec<usize> = (i..j).filter(|&k| glyphs.get(k).is_some_and(|g| g.len > 0)).collect();
+ let (Some(&first), Some(&last)) = (parents.first(), parents.last()) else {
+ i = j;
+ continue;
+ };
+ let Some((face, parent_size)) = glyphs.get(first).map(|g| (g.face, g.size)) else {
+ i = j;
+ continue;
+ };
+ let shaped = shape_ruby(db, face, &text, &spec, parent_size, fallback || missing, vertical);
+ let width: f64 = glyphs.get(i..j).unwrap_or_default().iter().map(|g| g.adv).sum();
+ let mono = unit.is_some();
+ let side = |k: Option<usize>| -> Side {
+ let Some(g) = k.and_then(|k| glyphs.get(k)) else { return Side::Edge };
+ if g.ch.is_control() || g.ch == crate::shape::HIDDEN {
+ return Side::Edge;
+ }
+ match styles.get(g.style as usize) {
+ Some(s) if s.ruby.is_some() => Side::Ruby { free: unit_free(db, g.face, g.adv, s, mono, fallback, vertical) },
+ _ => Side::Char { ch: g.ch, adv: g.adv },
+ }
+ };
+ let before = allowance(&spec, shaped.em, parent_size, side(i.checked_sub(1)), true);
+ let after = allowance(&spec, shaped.em, parent_size, side(Some(j)), false);
+ let (before, after) = usable(spec.alignment, before, after);
+ let w = shaped.width * auto_scale(&spec, shaped.width, width, before + after);
+ if let Some((lead, inner, trail)) = parent_spacing(spec.parent_spacing, parents.len(), w - width - before - after) {
+ if let Some(g) = glyphs.get_mut(first) {
+ g.dx += lead;
+ g.adv += lead;
+ }
+ for pair in parents.windows(2) {
+ if let Some(g) = pair.get(1).and_then(|n| n.checked_sub(1)).and_then(|k| glyphs.get_mut(k)) {
+ g.adv += inner;
+ }
+ }
+ if let Some(g) = j.checked_sub(1).and_then(|k| glyphs.get_mut(k)) {
+ g.adv += trail;
+ }
+ }
+ // Group ruby keeps its parent on one line (JLReq 3.3).
+ if !mono {
+ for g in glyphs.get_mut(first..last).unwrap_or_default() {
+ g.break_after = Some(false);
+ }
+ }
+ i = j;
}
- (out, x)
}
-/// Add the ruby of a laid-out line's glyphs.
-pub(crate) fn annotate(styles: &[RunStyle], line: &mut Vec<PlacedGlyph>) {
- let style = |g: &PlacedGlyph| styles.get(g.style as usize);
- if !line.iter().any(|g| style(g).is_some_and(|s| s.ruby.is_some())) {
+// ---------- after line breaking ----------
+
+/// The run style ruby glyphs are drawn in: the parent's, with the ruby's colours and none of the
+/// parent's decorations.
+fn ruby_style(styles: &mut Vec<RunStyle>, base: &RunStyle, spec: &RubySpec, size: f64, missing: bool) -> u32 {
+ let mut rs = base.clone();
+ if spec.fill.is_empty() {
+ if let Some(t) = spec.fill_tint {
+ rs.fill_tint = t;
+ }
+ } else {
+ rs.fill.clone_from(&spec.fill);
+ rs.fill_tint = spec.fill_tint.unwrap_or(1.0);
+ }
+ if spec.stroke.is_empty() {
+ if let Some(t) = spec.stroke_tint {
+ rs.stroke_tint = t;
+ }
+ } else {
+ rs.stroke.clone_from(&spec.stroke);
+ rs.stroke_tint = spec.stroke_tint.unwrap_or(1.0);
+ }
+ if let Some(w) = spec.stroke_weight {
+ rs.stroke_weight = w;
+ }
+ // Text itself never overprints, so `Auto` (follow the text) is off.
+ rs.overprint_fill = spec.overprint_fill == AdornmentOverprint::On;
+ rs.overprint_stroke = spec.overprint_stroke == AdornmentOverprint::On;
+ rs.size = size;
+ rs.missing_font = missing;
+ rs.underline = false;
+ rs.strikethrough = false;
+ rs.custom_tracking = false;
+ rs.condition = None;
+ rs.xml_tag = None;
+ rs.ruby = None;
+ rs.ruby_spec = None;
+ rs.ruby_unit = None;
+ rs.kenten_mark = None;
+ rs.warichu = false;
+ intern(styles, rs)
+}
+
+/// Add the ruby of a laid-out line's glyphs. `text` is the story text the glyphs'
+/// bytes index; `glyph_fallback`: the document draws missing glyphs from fallback fonts (a
+/// missing font's substitute always does); `vertical`: the frame is vertical.
+pub(crate) fn annotate(
+ db: &ScopedFonts<'_>,
+ styles: &mut Vec<RunStyle>,
+ text: &str,
+ line: &mut Vec<PlacedGlyph>,
+ glyph_fallback: bool,
+ vertical: bool,
+) {
+ if !line.iter().any(|g| styles.get(g.style as usize).is_some_and(|s| s.ruby.is_some())) {
return;
}
let mut extra = Vec::new();
let mut i = 0;
while i < line.len() {
- let g = &line[i];
- let Some(st) = style(g).filter(|_| g.len > 0 && g.visible) else {
+ let Some(g) = line.get(i) else { break };
+ let Some(st) = styles.get(g.style as usize).filter(|_| g.len > 0 && g.visible).cloned() else {
i += 1;
continue;
};
- let Some(text) = &st.ruby else {
+ let fallback = glyph_fallback || st.missing_font;
+ let (Some(reading), Some(spec)) = (st.ruby.clone(), st.ruby_spec.clone()) else {
i += 1;
continue;
};
- // The group: following glyphs with the same ruby.
+ // The group: following glyphs with the same ruby (and unit).
+ let key = (reading.as_str(), st.ruby_unit);
let mut j = i + 1;
- while j < line.len() && (line[j].len == 0 || style(&line[j]).is_some_and(|s| s.ruby.as_ref() == Some(text))) {
+ while line.get(j).is_some_and(|b| b.len == 0 || styles.get(b.style as usize).and_then(ruby_key).is_some_and(|k| k == key)) {
j += 1;
}
- let base: Vec<&PlacedGlyph> = line[i..j].iter().filter(|b| b.len > 0).collect();
- let x0 = base.iter().map(|b| b.x).fold(f64::MAX, f64::min);
- let x1 = base.iter().map(|b| b.x + b.adv).fold(f64::MIN, f64::max);
- let (mut glyphs, w) = set(g, text, st.size * SCALE, st.size);
- let n = glyphs.len().max(1) as f64;
- if w < x1 - x0 {
- // Shorter than the base: spread out, half a gap at each end (the 1-2-1 rule).
- let gap = (x1 - x0 - w) / n;
- for (k, r) in glyphs.iter_mut().enumerate() {
- r.x += x0 + gap * (k as f64 + 0.5);
+ let group = line.get(i..j).unwrap_or_default();
+ let base: Vec<&PlacedGlyph> = group.iter().filter(|b| b.len > 0).collect();
+ let Some(&first) = base.first() else {
+ i = j;
+ continue;
+ };
+ // The parent's extent from its pen positions (parent spacing lies inside it).
+ let x0 = base.iter().map(|b| b.x - b.dx).fold(f64::MAX, f64::min);
+ let x1 = base.iter().map(|b| b.x - b.dx + b.adv).fold(f64::MIN, f64::max);
+ let width = (x1 - x0).max(0.0);
+ let shaped = shape_ruby(db, first.face, &reading, &spec, st.size, fallback, vertical);
+ let mono = st.ruby_unit.is_some();
+ let side = |b: Option<&PlacedGlyph>| -> Side {
+ let Some(b) = b.filter(|b| b.visible) else { return Side::Edge };
+ match styles.get(b.style as usize) {
+ Some(s) if s.ruby.is_some() => Side::Ruby { free: unit_free(db, b.face, b.adv, s, mono, glyph_fallback, vertical) },
+ _ => Side::Char { ch: text.get(b.byte..).and_then(|s| s.chars().next()).unwrap_or(' '), adv: b.adv },
}
- } else {
- // Longer: centred over the base.
- let start = (x0 + x1 - w) / 2.0;
- for r in &mut glyphs {
- r.x += start;
+ };
+ let prev = line.get(..i).unwrap_or_default().iter().rev().find(|b| b.len > 0);
+ let next = line.get(j..).unwrap_or_default().iter().find(|b| b.len > 0);
+ let before = allowance(&spec, shaped.em, st.size, side(prev), true);
+ let after = allowance(&spec, shaped.em, st.size, side(next), false);
+ let (before, after) = usable(spec.alignment, before, after);
+ let scale = auto_scale(&spec, shaped.width, width, before + after);
+ let w = shaped.width * scale;
+ // Each glyph's offset from the parent's start.
+ let offsets: Vec<f64> = if w <= width + 1e-9 {
+ let mut slots: Vec<f64> = Vec::new();
+ for r in &shaped.glyphs {
+ match slots.last_mut() {
+ Some(a) if r.joined => *a += r.adv,
+ _ => slots.push(r.adv),
+ }
}
+ let at = spread(spec.alignment, width, &slots, shaped.em);
+ let (mut slot, mut slot_x) = (0usize, 0.0);
+ let mut out = Vec::with_capacity(shaped.glyphs.len());
+ for (n, r) in shaped.glyphs.iter().enumerate() {
+ if !r.joined {
+ if n > 0 {
+ slot += 1;
+ }
+ slot_x = r.x;
+ }
+ out.push(at.get(slot).copied().unwrap_or(0.0) + (r.x - slot_x));
+ }
+ out
+ } else {
+ let lead = lead_overhang(spec.alignment, w - width, before, after);
+ shaped.glyphs.iter().map(|r| r.x * scale - lead).collect()
+ };
+ let tall = shaped.size * spec.y_scale;
+ let y = match spec.position {
+ // Its em box sits just clear of the parent's.
+ RubyPosition::AboveRight => -(st.size * 0.88 + tall * 0.2) - spec.y_offset,
+ RubyPosition::BelowLeft => st.size * 0.12 + tall * 0.96 + spec.y_offset,
+ };
+ let missing = if spec.font_family.is_empty() { st.missing_font } else { !db.has_family(&spec.font_family) };
+ let style = ruby_style(styles, &st, &spec, shaped.size, missing);
+ for (r, off) in shaped.glyphs.iter().zip(offsets) {
+ extra.push(PlacedGlyph {
+ face: shaped.face,
+ gid: r.gid,
+ x: x0 + off + spec.x_offset,
+ y: y + r.y,
+ adv: r.adv * scale,
+ sx: r.sx * scale,
+ sy: r.sy,
+ style,
+ byte: first.byte,
+ len: 0,
+ visible: true,
+ upright: r.tcy.is_none() && upright_in_vertical(r.ch),
+ tcy: r.tcy,
+ rtl: false,
+ dx: 0.0,
+ });
}
- extra.extend(glyphs);
i = j;
}
line.extend(extra);
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn shorter_ruby_spreads_by_its_alignment() {
+ // A 24 pt parent and three 6 pt ruby characters: 6 pt to spare.
+ assert_eq!(spread(RubyAlignment::Jis, 24.0, &[6.0, 6.0, 6.0], 6.0), [1.0, 9.0, 17.0]);
+ assert_eq!(spread(RubyAlignment::EqualAki, 24.0, &[6.0, 6.0, 6.0], 6.0), [1.5, 9.0, 16.5]);
+ assert_eq!(spread(RubyAlignment::OneAki, 24.0, &[6.0, 6.0, 6.0], 6.0), [3.0, 9.0, 15.0]);
+ assert_eq!(spread(RubyAlignment::FullJustify, 24.0, &[6.0, 6.0, 6.0], 6.0), [0.0, 9.0, 18.0]);
+ assert_eq!(spread(RubyAlignment::Right, 24.0, &[6.0, 6.0, 6.0], 6.0), [6.0, 12.0, 18.0]);
+ }
+
+ #[test]
+ fn longer_ruby_leans_to_the_side_it_may_overhang() {
+ // 6 pt too long; only the following kana takes overhang.
+ assert_eq!(lead_overhang(RubyAlignment::Jis, 6.0, 0.0, 6.0), 0.0);
+ assert_eq!(lead_overhang(RubyAlignment::Jis, 6.0, 6.0, 6.0), 3.0);
+ assert_eq!(lead_overhang(RubyAlignment::Jis, 6.0, 6.0, 0.0), 6.0);
+ // Neither side takes enough: centred.
+ assert_eq!(lead_overhang(RubyAlignment::Jis, 6.0, 1.0, 1.0), 3.0);
+ }
+
+ #[test]
+ fn overhang_goes_over_kana_and_the_blank_half_of_punctuation_only() {
+ let spec = RubySpec::of(&designcraft_doc::CharProps::default());
+ let kana = Side::Char { ch: 'で', adv: 12.0 };
+ let kanji = Side::Char { ch: '字', adv: 12.0 };
+ let stop = Side::Char { ch: '。', adv: 12.0 };
+ assert_eq!(allowance(&spec, 6.0, 12.0, kana, false), 6.0);
+ assert_eq!(allowance(&spec, 6.0, 12.0, kanji, false), 0.0);
+ assert_eq!(allowance(&spec, 6.0, 12.0, stop, false), 6.0);
+ assert_eq!(allowance(&spec, 6.0, 12.0, stop, true), 0.0);
+ assert_eq!(allowance(&spec, 6.0, 12.0, Side::Edge, true), 0.0);
+ }
+
+ #[test]
+ fn parent_spacing_splits_the_extra_room() {
+ assert_eq!(parent_spacing(RubyParentSpacing::Aki121, 2, 8.0), Some((2.0, 4.0, 2.0)));
+ assert_eq!(parent_spacing(RubyParentSpacing::FullJustify, 1, 8.0), Some((4.0, 0.0, 4.0)));
+ assert_eq!(parent_spacing(RubyParentSpacing::NoAdjustment, 2, 8.0), None);
+ assert_eq!(parent_spacing(RubyParentSpacing::Aki121, 2, f64::NAN), None);
+ }
+
+ #[test]
+ fn capped_cuts_long_readings_at_a_char_boundary() {
+ let long = "あ".repeat(MAX_RUBY_CHARS + 10);
+ assert_eq!(capped(&long).chars().count(), MAX_RUBY_CHARS);
+ }
+}
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index 820f2cffe..89ad0eab0 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -189,7 +189,11 @@ impl StyleTable<'_> {
condition: p.conditions.first().cloned(),
inserted: p.change == designcraft_doc::ChangeMark::Inserted,
xml_tag: (!p.xml_tag.is_empty()).then(|| p.xml_tag.clone()),
- ruby: (!p.ruby.is_empty()).then(|| p.ruby.clone()),
+ ruby: (!p.ruby.is_empty()).then(|| crate::ruby::capped(&p.ruby).to_string()),
+ ruby_spec: (!p.ruby.is_empty()).then(|| designcraft_doc::ruby::RubySpec::of(p)),
+ ruby_unit: None,
+ overprint_fill: false,
+ overprint_stroke: false,
warichu: p.warichu,
warichu_lines: p.warichu_lines,
warichu_size: p.warichu_size,
@@ -351,6 +355,7 @@ pub(crate) fn shape_para(
}
fit_auto_tcy(&mut glyphs, &auto_tcy);
collapse_tcy(&mut glyphs, sub.vertical);
+ crate::ruby::reserve(db, table.styles, &mut glyphs, auto_leading.glyph_fallback, sub.vertical);
ShapedPara { glyphs, range }
}
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index ea344ce2d..e43e004d3 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -1065,6 +1065,96 @@ fn ruby_and_kenten_sit_over_their_text() {
assert!((dot.x + dot.adv / 2.0 - (de.x + de.adv / 2.0)).abs() < 1.0 && dot.y < 0.0);
}
+/// `text` on one line, composed plain and then with the ruby attributes `set` on `range`: the
+/// plain glyphs, and the ruby line (its ruby glyphs follow the text's) with its story.
+fn ruby_compose(text: &str, range: std::ops::Range<usize>, set: impl Fn(&mut designcraft_doc::CharAttrs)) -> (Vec<PlacedGlyph>, Line, ComposedStory) {
+ let mut d = Document::new(&designcraft_doc::build::NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 200.0), lid, text, ParaFormat::default()).unwrap();
+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();
+ d.story_mut(sid).unwrap().format_chars(range, |f| set(&mut f.over));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let line = cs.frames[0].lines[0].clone();
+ (plain, line, cs)
+}
+
+#[test]
+fn group_ruby_spreads_1_2_1_over_the_word_and_mono_ruby_sits_over_each_character() {
+ let kanji = 0.."漢字".len();
+ // Group: three kana over two kanji, half a gap at each end (JIS 1-2-1).
+ let (plain, l, _) = ruby_compose("漢字です", kanji.clone(), |a| a.ruby = Some("かんじ".into()));
+ let ruby = &l.glyphs[plain.len()..];
+ assert_eq!(ruby.len(), 3);
+ let (x0, x1) = (l.glyphs[0].x, l.glyphs[1].x + l.glyphs[1].adv);
+ let w: f64 = ruby.iter().map(|g| g.adv).sum();
+ assert!(w < x1 - x0);
+ let gap = (x1 - x0 - w) / 3.0;
+ let mut x = x0 + gap / 2.0;
+ for g in ruby {
+ assert!((g.x - x).abs() < 1e-6, "{} != {x}", g.x);
+ x += g.adv + gap;
+ }
+ // Mono: かん over 漢 and じ centred on 字; the U+3000 separator isn't drawn.
+ let (plain, l, _) = ruby_compose("漢字です", kanji, |a| {
+ a.ruby = Some("かん\u{3000}じ".into());
+ a.ruby_type = Some(designcraft_doc::ruby::RubyType::PerCharacter);
+ });
+ let ruby = &l.glyphs[plain.len()..];
+ assert_eq!(ruby.len(), 3);
+ let (kan, ji) = (&l.glyphs[0], &l.glyphs[1]);
+ assert!((ruby[0].x - kan.x).abs() < 1e-6 && ruby[1].x + ruby[1].adv <= ji.x + 1e-6);
+ assert!((ruby[2].x + ruby[2].adv / 2.0 - (ji.x + ji.adv / 2.0)).abs() < 1e-6);
+}
+
+#[test]
+fn longer_ruby_overhangs_kana_and_spaces_out_kanji() {
+ let ji = "漢".len().."漢字".len();
+ // Over 字 before a kana: the ruby starts flush with 字 (never over the kanji before it) and
+ // hangs over で by one ruby character, so nothing moves.
+ let (plain, l, _) = ruby_compose("漢字で", ji.clone(), |a| a.ruby = Some("かんじ".into()));
+ let ruby = &l.glyphs[plain.len()..];
+ let w: f64 = ruby.iter().map(|g| g.adv).sum();
+ let parent = &l.glyphs[1];
+ assert!(w > parent.adv);
+ assert!((ruby[0].x - parent.x).abs() < 1e-6, "{} != {}", ruby[0].x, parent.x);
+ assert!((l.glyphs[2].x - plain[2].x).abs() < 1e-6, "で stays");
+ assert!(ruby[2].x + ruby[2].adv > l.glyphs[2].x, "over で");
+ // Between kanji there is nothing to overhang: 字 gets the difference as space on both sides
+ // and the ruby spans it.
+ let (plain, l, _) = ruby_compose("漢字漢", ji, |a| a.ruby = Some("かんじ".into()));
+ let ruby = &l.glyphs[plain.len()..];
+ let w: f64 = ruby.iter().map(|g| g.adv).sum();
+ let grow = l.glyphs[2].x - plain[2].x;
+ assert!((grow - (w - plain[1].adv)).abs() < 1e-6, "{grow} vs {w}");
+ assert!((l.glyphs[1].dx - grow / 2.0).abs() < 1e-6);
+ assert!((ruby[0].x - (l.glyphs[1].x - l.glyphs[1].dx)).abs() < 1e-6);
+}
+
+#[test]
+fn ruby_is_half_size_by_default_and_can_sit_below_in_its_own_colour() {
+ let kanji = 0.."漢字".len();
+ let (plain, l, cs) = ruby_compose("漢字です", kanji.clone(), |a| {
+ a.ruby = Some("かんじ".into());
+ a.ruby_position = Some(designcraft_doc::ruby::RubyPosition::BelowLeft);
+ });
+ let ruby = &l.glyphs[plain.len()..];
+ let size = cs.styles[l.glyphs[0].style as usize].size;
+ assert!(ruby.iter().all(|g| g.y > size * 0.12), "below the parent's em box");
+ assert!(ruby.iter().all(|g| (g.sy - l.glyphs[0].sy * 0.5).abs() < 1e-9), "half size");
+ assert!((cs.styles[ruby[0].style as usize].size - size * 0.5).abs() < 1e-9);
+ // Its own size and fill; the parent keeps its colour.
+ let (plain, l, cs) = ruby_compose("漢字です", kanji, |a| {
+ a.ruby = Some("かんじ".into());
+ a.ruby_font_size = Some(Some(4.0));
+ a.ruby_fill = Some("[Paper]".into());
+ });
+ let r = &l.glyphs[plain.len()];
+ assert!(r.y < -size * 0.8);
+ assert!((r.sy - l.glyphs[0].sy * 4.0 / size).abs() < 1e-9);
+ assert_eq!(cs.styles[r.style as usize].fill, "[Paper]");
+ assert_eq!(cs.styles[l.glyphs[0].style as usize].fill, "[Black]");
+}
+
#[test]
fn warichu_stacks_the_run_inside_the_line_and_closes_up() {
let text = "ABCDEFGHZ";
diff --git a/crates/doc/src/attrs.rs b/crates/doc/src/attrs.rs
index 3d2943115..3e0b622cc 100644
--- a/crates/doc/src/attrs.rs
+++ b/crates/doc/src/attrs.rs
@@ -758,8 +758,9 @@ attr_set! {
tate_chu_yoko: bool = false,
tate_chu_yoko_x_offset: f64 = 0.0,
tate_chu_yoko_y_offset: f64 = 0.0,
- /// Ruby: the reading set small above the text (to its right in vertical text), one group
- /// over each run that has it.
+ /// Ruby: the reading set small above the text (to its right in vertical text). Group ruby
+ /// sets it over the whole run; per-character ruby holds one reading per character,
+ /// separated by U+3000. Its other settings are the `ruby_*` fields below.
ruby: String = String::new(),
/// Kenten: an emphasis dot above each character.
kenten: bool = false,
@@ -810,6 +811,45 @@ attr_set! {
shatai_adjust_rotation: bool = false,
/// Fit the advance to the compressed em box.
shatai_adjust_tsume: bool = true,
+ // Ruby settings (see [`crate::ruby`]). Defaults are the IDML text defaults.
+ ruby_type: crate::ruby::RubyType = crate::ruby::RubyType::Group,
+ /// How a ruby shorter than its parent is spread over it.
+ ruby_alignment: crate::ruby::RubyAlignment = crate::ruby::RubyAlignment::Jis,
+ ruby_position: crate::ruby::RubyPosition = crate::ruby::RubyPosition::AboveRight,
+ /// Points along the line, and away from the parent text across it.
+ ruby_x_offset: f64 = 0.0,
+ ruby_y_offset: f64 = 0.0,
+ /// Empty: the parent's font and style.
+ ruby_font: String = String::new(),
+ ruby_font_style: String = String::new(),
+ /// Points; `None` is half the parent size.
+ ruby_font_size: Option<f64> = None,
+ /// 1.0 = 100%.
+ ruby_x_scale: f64 = 1.0,
+ ruby_y_scale: f64 = 1.0,
+ /// Use the font's ruby glyphs (OpenType `ruby`).
+ ruby_open_type_pro: bool = true,
+ /// Tate-chu-yoko in vertical ruby for runs of up to this many digits (0 = off).
+ ruby_auto_tcy_digits: u32 = 0,
+ ruby_auto_tcy_include_roman: bool = false,
+ ruby_auto_tcy_auto_scale: bool = true,
+ /// IDML `RubyOverhang`, kept for round trips; `ruby_overhang_amount` sets the overhang.
+ ruby_overhang: bool = false,
+ ruby_overhang_amount: crate::ruby::RubyOverhang = crate::ruby::RubyOverhang::OneRuby,
+ ruby_parent_spacing: crate::ruby::RubyParentSpacing = crate::ruby::RubyParentSpacing::Aki121,
+ /// A longer ruby at a line's start or end is set flush with the line edge.
+ ruby_auto_align: bool = true,
+ /// A longer ruby is narrowed first, down to `ruby_scaling_min` (1.0 = 100%).
+ ruby_auto_scaling: bool = false,
+ ruby_scaling_min: f64 = 0.66,
+ /// Ruby colour: empty is the text's colour; `None` tint and weight follow the text.
+ ruby_fill: String = String::new(),
+ ruby_fill_tint: Option<f32> = None,
+ ruby_stroke: String = String::new(),
+ ruby_stroke_tint: Option<f32> = None,
+ ruby_stroke_weight: Option<f64> = None,
+ ruby_overprint_fill: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto,
+ ruby_overprint_stroke: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto,
/// Digits (World-Ready): how 0–9 are drawn.
digits: Digits = Digits::Default,
character_direction: crate::arabic::CharacterDirection = crate::arabic::CharacterDirection::Default,
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index e00c1557d..f776ce176 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -25,6 +25,7 @@ pub mod item;
pub mod notes;
pub mod otf;
pub mod page;
+pub mod ruby;
pub mod selection;
mod slice;
pub mod story;
diff --git a/crates/doc/src/ruby.rs b/crates/doc/src/ruby.rs
new file mode 100644
index 000000000..bb8d4c6d5
--- /dev/null
+++ b/crates/doc/src/ruby.rs
@@ -0,0 +1,212 @@
+//! Ruby settings: the readings set beside parent text and how they are placed, sized and
+//! coloured (the four Ruby panes of the Character panel menu and of style options).
+//!
+//! The values live as `ruby*` fields of [`crate::CharAttrs`] so styles inherit them one by one.
+//! [`RubySpec`] gathers the resolved values of a run, clamped to safe ranges, for layout.
+use serde::{Deserialize, Serialize};
+
+use crate::CharProps;
+use crate::cjk_settings::AdornmentOverprint;
+
+/// Mono ruby gives each parent character its own reading; group ruby sets one reading over the
+/// whole run.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum RubyType {
+ #[default]
+ Group,
+ /// Per-character (mono) ruby: the readings of the parent characters, in order, separated by
+ /// U+3000 IDEOGRAPHIC SPACE (as IDML stores them).
+ PerCharacter,
+}
+
+/// How a ruby shorter than its parent is spread over it.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum RubyAlignment {
+ /// Flush with the parent's start (top in vertical text).
+ Left,
+ Center,
+ /// Flush with the parent's end (bottom in vertical text).
+ Right,
+ /// First and last ruby characters flush with the parent's ends, the rest spread evenly.
+ FullJustify,
+ /// JIS 1-2-1 rule: the space at each end is half the space between ruby characters.
+ #[default]
+ Jis,
+ /// The space at each end equals the space between ruby characters.
+ EqualAki,
+ /// Half a ruby character inset at each end, the rest spread between ruby characters.
+ OneAki,
+}
+
+/// Above the parent in horizontal text (right of it in vertical text), or below (left).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum RubyPosition {
+ #[default]
+ AboveRight,
+ BelowLeft,
+}
+
+/// How far a ruby longer than its parent may extend over the neighbouring characters.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum RubyOverhang {
+ None,
+ /// One ruby character.
+ #[default]
+ OneRuby,
+ HalfRuby,
+ /// One parent character.
+ OneChar,
+ HalfChar,
+ NoLimit,
+}
+
+/// How the parent characters are spaced out when the ruby is longer than they are.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum RubyParentSpacing {
+ NoAdjustment,
+ /// Space before the first and after the last parent character.
+ BothSides,
+ /// 1-2-1: the space at each end is half the space between parent characters.
+ #[default]
+ Aki121,
+ /// The space at each end equals the space between parent characters.
+ EqualAki,
+ /// Space only between parent characters.
+ FullJustify,
+}
+
+/// Longest ruby reading laid out, in characters.
+pub const MAX_RUBY_CHARS: usize = 256;
+
+/// A run's resolved ruby settings, every number finite and inside the range the controls allow.
+#[derive(Clone, Debug, PartialEq)]
+pub struct RubySpec {
+ pub kind: RubyType,
+ pub alignment: RubyAlignment,
+ pub position: RubyPosition,
+ /// Points along the line, and away from the parent text across it.
+ pub x_offset: f64,
+ pub y_offset: f64,
+ /// Empty: the parent's font. An empty style with a family set is that family's Regular.
+ pub font_family: String,
+ pub font_style: String,
+ /// Points; `None` is half the parent size.
+ pub size: Option<f64>,
+ /// 1.0 = 100 %.
+ pub x_scale: f64,
+ pub y_scale: f64,
+ /// Use the font's ruby glyphs (OpenType `ruby`).
+ pub open_type_pro: bool,
+ /// Tate-chu-yoko inside vertical ruby: runs of up to this many digits (0 = off), Latin
+ /// letters too when `auto_tcy_include_roman`, squeezed to one ruby em when
+ /// `auto_tcy_auto_scale`.
+ pub auto_tcy_digits: u32,
+ pub auto_tcy_include_roman: bool,
+ pub auto_tcy_auto_scale: bool,
+ pub overhang: RubyOverhang,
+ pub parent_spacing: RubyParentSpacing,
+ /// At a line's start or end, a longer ruby is set flush with the line edge.
+ pub auto_align: bool,
+ /// A longer ruby is first narrowed, down to `scaling_min` of its width.
+ pub auto_scaling: bool,
+ pub scaling_min: f64,
+ /// Empty: the text's colour (and its tint when the tint is `None`).
+ pub fill: String,
+ pub fill_tint: Option<f32>,
+ pub stroke: String,
+ pub stroke_tint: Option<f32>,
+ /// `None`: the text's stroke weight.
+ pub stroke_weight: Option<f64>,
+ pub overprint_fill: AdornmentOverprint,
+ pub overprint_stroke: AdornmentOverprint,
+}
+
+fn finite_or(v: f64, default: f64) -> f64 {
+ if v.is_finite() { v } else { default }
+}
+
+fn tint(v: Option<f32>) -> Option<f32> {
+ v.filter(|t| t.is_finite()).map(|t| t.clamp(0.0, 1.0))
+}
+
+impl RubySpec {
+ /// The ruby settings of resolved character properties.
+ pub fn of(p: &CharProps) -> RubySpec {
+ RubySpec {
+ kind: p.ruby_type,
+ alignment: p.ruby_alignment,
+ position: p.ruby_position,
+ x_offset: finite_or(p.ruby_x_offset, 0.0).clamp(-1000.0, 1000.0),
+ y_offset: finite_or(p.ruby_y_offset, 0.0).clamp(-1000.0, 1000.0),
+ font_family: p.ruby_font.clone(),
+ font_style: p.ruby_font_style.clone(),
+ size: p.ruby_font_size.filter(|s| s.is_finite() && *s > 0.0).map(|s| s.clamp(0.1, 1296.0)),
+ x_scale: finite_or(p.ruby_x_scale, 1.0).clamp(0.01, 10.0),
+ y_scale: finite_or(p.ruby_y_scale, 1.0).clamp(0.01, 10.0),
+ open_type_pro: p.ruby_open_type_pro,
+ auto_tcy_digits: p.ruby_auto_tcy_digits.min(9),
+ auto_tcy_include_roman: p.ruby_auto_tcy_include_roman,
+ auto_tcy_auto_scale: p.ruby_auto_tcy_auto_scale,
+ overhang: p.ruby_overhang_amount,
+ parent_spacing: p.ruby_parent_spacing,
+ auto_align: p.ruby_auto_align,
+ auto_scaling: p.ruby_auto_scaling,
+ scaling_min: finite_or(p.ruby_scaling_min, 0.66).clamp(0.1, 1.0),
+ fill: p.ruby_fill.clone(),
+ fill_tint: tint(p.ruby_fill_tint),
+ stroke: p.ruby_stroke.clone(),
+ stroke_tint: tint(p.ruby_stroke_tint),
+ stroke_weight: p.ruby_stroke_weight.filter(|w| w.is_finite()).map(|w| w.clamp(0.0, 800.0)),
+ overprint_fill: p.ruby_overprint_fill,
+ overprint_stroke: p.ruby_overprint_stroke,
+ }
+ }
+
+ /// The ruby size for parent text of `parent_size` points.
+ pub fn size_for(&self, parent_size: f64) -> f64 {
+ self.size.unwrap_or(parent_size * 0.5)
+ }
+}
+
+/// The readings of a mono ruby, one per parent character, or `None` when their number doesn't
+/// match `parents` (the ruby is then set as a group).
+pub fn mono_readings(text: &str, parents: usize) -> Option<Vec<&str>> {
+ let parts: Vec<&str> = text.split('\u{3000}').collect();
+ (parts.len() == parents && parents > 0).then_some(parts)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn spec_keeps_hostile_numbers_in_range() {
+ let p = CharProps {
+ ruby_font_size: Some(f64::NAN),
+ ruby_x_scale: f64::INFINITY,
+ ruby_y_scale: -3.0,
+ ruby_x_offset: 1e300,
+ ruby_scaling_min: 0.0,
+ ruby_auto_tcy_digits: u32::MAX,
+ ruby_fill_tint: Some(7.0),
+ ruby_stroke_weight: Some(f64::NEG_INFINITY),
+ ..CharProps::default()
+ };
+ let s = RubySpec::of(&p);
+ assert_eq!(s.size, None);
+ assert_eq!(s.size_for(12.0), 6.0);
+ assert_eq!((s.x_scale, s.y_scale, s.x_offset, s.scaling_min), (1.0, 0.01, 1000.0, 0.1));
+ assert_eq!((s.auto_tcy_digits, s.fill_tint, s.stroke_weight), (9, Some(1.0), None));
+ }
+
+ #[test]
+ fn mono_readings_need_one_per_character() {
+ assert_eq!(mono_readings("かん\u{3000}じ", 2), Some(vec!["かん", "じ"]));
+ assert_eq!(mono_readings("かんじ", 2), None);
+ }
+}
diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs
index 67d544661..7eca1625a 100644
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@ -183,9 +183,9 @@ pub fn specs() -> Vec<CommandSpec> {
"Ruby",
[],
None,
- "{text} — the reading set over the selected text (one group); empty removes it",
+ "{text?, type?: group|perCharacter, alignment?: left|center|right|fullJustify|jis|equalAki|oneAki, position?: aboveRight|belowLeft, xOffset?, yOffset? (pt), font?, fontStyle? (\"\" = the text's), size? (pt; null = half the text size), xScale?, yScale? (%), openTypePro?: bool, autoTcyDigits?: 0-9, autoTcyIncludeRoman?: bool, autoTcyAutoScale?: bool, overhang?: none|oneRuby|halfRuby|oneChar|halfChar|noLimit, parentSpacing?: noAdjustment|bothSides|aki121|equalAki|fullJustify, autoAlign?: bool, autoScaling?: bool, scalingPercent? (%), fill?, stroke? (swatch; \"\" = the text's), fillTint?, strokeTint? (%; null = the text's), strokeWeight? (pt; null = the text's), overprintFill?, overprintStroke?: auto|on|off} — the reading set over the selected text and how it is placed; empty text removes it. Per-character ruby separates the readings with U+3000",
has_text_or_frames,
- |s, p| { format_chars(s, &json!({"ruby": str_param(p, "text").unwrap_or("")})) }
+ ruby_cmd
),
cmd!(
"type.kenten",
@@ -895,6 +895,26 @@ fn enum_param<T: serde::de::DeserializeOwned + serde::Serialize>(p: &Value, key:
}
}
+/// A ruby enum parameter, checked against its type.
+fn ruby_enum<T: serde::de::DeserializeOwned>(p: &Value, key: &str) -> Result<Option<Value>> {
+ let Some(v) = p.get(key) else { return Ok(None) };
+ serde_json::from_value::<T>(v.clone()).map_err(|e| bad("type.ruby", format!("{key}: {e}")))?;
+ Ok(Some(v.clone()))
+}
+
+/// A ruby number parameter clamped to `lo..=hi`, then divided by `div` (100 for percentages);
+/// `null` gives `Value::Null` (automatic).
+fn ruby_num(p: &Value, key: &str, lo: f64, hi: f64, div: f64) -> Result<Option<Value>> {
+ match p.get(key) {
+ None => Ok(None),
+ Some(Value::Null) => Ok(Some(Value::Null)),
+ Some(v) => {
+ let x = v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("type.ruby", format!("{key}: expected a finite number")))?;
+ Ok(Some(json!(x.clamp(lo, hi) / div)))
+ }
+ }
+}
+
/// Is `flag` on in the character format at the start of the first formatting target?
fn char_flag_on(s: &Session, flag: impl Fn(&CharAttrs) -> Option<bool>) -> bool {
format_targets(s).first().is_some_and(|t| {
@@ -1077,6 +1097,71 @@ fn para_toggle(s: &mut Session, p: &Value, cmd: &str, attr: &str, get: impl Fn(&
format_paras(s, &Value::Object(body))
}
+fn ruby_text<'a>(p: &'a Value, key: &str) -> Result<Option<&'a str>> {
+ let Some(v) = p.get(key) else { return Ok(None) };
+ let t = v.as_str().ok_or_else(|| bad("type.ruby", format!("{key}: expected a string")))?;
+ if t.chars().count() > designcraft_doc::ruby::MAX_RUBY_CHARS {
+ return Err(bad("type.ruby", format!("{key}: longer than {} characters", designcraft_doc::ruby::MAX_RUBY_CHARS)));
+ }
+ Ok(Some(t))
+}
+
+fn ruby_cmd(s: &mut Session, p: &Value) -> Result<Value> {
+ use designcraft_doc::cjk_settings::AdornmentOverprint;
+ use designcraft_doc::ruby::{RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubyType};
+ let mut body = serde_json::Map::new();
+ let mut put = |attr: &str, v: Option<Value>| {
+ if let Some(v) = v {
+ body.insert(attr.into(), v);
+ }
+ };
+ put("ruby", ruby_text(p, "text")?.map(|t| json!(t)));
+ put("rubyType", ruby_enum::<RubyType>(p, "type")?);
+ put("rubyAlignment", ruby_enum::<RubyAlignment>(p, "alignment")?);
+ put("rubyPosition", ruby_enum::<RubyPosition>(p, "position")?);
+ put("rubyOverhangAmount", ruby_enum::<RubyOverhang>(p, "overhang")?);
+ put("rubyParentSpacing", ruby_enum::<RubyParentSpacing>(p, "parentSpacing")?);
+ put("rubyOverprintFill", ruby_enum::<AdornmentOverprint>(p, "overprintFill")?);
+ put("rubyOverprintStroke", ruby_enum::<AdornmentOverprint>(p, "overprintStroke")?);
+ put("rubyXOffset", ruby_num(p, "xOffset", -1000.0, 1000.0, 1.0)?.filter(|v| !v.is_null()));
+ put("rubyYOffset", ruby_num(p, "yOffset", -1000.0, 1000.0, 1.0)?.filter(|v| !v.is_null()));
+ put("rubyFontSize", ruby_num(p, "size", 0.1, 1296.0, 1.0)?);
+ put("rubyXScale", ruby_num(p, "xScale", 1.0, 1000.0, 100.0)?.filter(|v| !v.is_null()));
+ put("rubyYScale", ruby_num(p, "yScale", 1.0, 1000.0, 100.0)?.filter(|v| !v.is_null()));
+ put("rubyScalingMin", ruby_num(p, "scalingPercent", 10.0, 100.0, 100.0)?.filter(|v| !v.is_null()));
+ put("rubyFillTint", ruby_num(p, "fillTint", 0.0, 100.0, 100.0)?);
+ put("rubyStrokeTint", ruby_num(p, "strokeTint", 0.0, 100.0, 100.0)?);
+ put("rubyStrokeWeight", ruby_num(p, "strokeWeight", 0.0, 800.0, 1.0)?);
+ put(
+ "rubyAutoTcyDigits",
+ ruby_num(p, "autoTcyDigits", 0.0, 9.0, 1.0)?.filter(|v| !v.is_null()).and_then(|v| v.as_f64()).map(|v| json!(v.round() as u32)),
+ );
+ for (key, attr) in [
+ ("openTypePro", "rubyOpenTypePro"),
+ ("autoTcyIncludeRoman", "rubyAutoTcyIncludeRoman"),
+ ("autoTcyAutoScale", "rubyAutoTcyAutoScale"),
+ ("autoAlign", "rubyAutoAlign"),
+ ("autoScaling", "rubyAutoScaling"),
+ ] {
+ if let Some(v) = p.get(key) {
+ let b = v.as_bool().ok_or_else(|| bad("type.ruby", format!("{key}: expected true or false")))?;
+ put(attr, Some(json!(b)));
+ }
+ }
+ put("rubyFont", ruby_text(p, "font")?.map(|t| json!(t)));
+ put("rubyFontStyle", ruby_text(p, "fontStyle")?.map(|t| json!(t)));
+ for (key, attr) in [("fill", "rubyFill"), ("stroke", "rubyStroke")] {
+ if let Some(name) = ruby_text(p, key)? {
+ let known = name.is_empty() || name == designcraft_doc::color::swatch::NONE || s.doc()?.doc.swatch(name).is_some();
+ if !known {
+ return Err(bad("type.ruby", format!("{key}: no swatch `{name}`")));
+ }
+ put(attr, Some(json!(name)));
+ }
+ }
+ format_chars(s, &Value::Object(body))
+}
+
pub(crate) fn format_chars(s: &mut Session, attrs: &Value) -> Result<Value> {
let mut a = CharAttrs::default();
if let Some(o) = attrs.as_object() {
@@ -1878,6 +1963,50 @@ mod tcy_tests {
assert_eq!(f(&s).ruby.as_deref(), Some(""));
}
+ #[test]
+ fn ruby_options_are_checked_and_clamped() {
+ use designcraft_doc::ruby::{RubyAlignment, RubyPosition, RubyType};
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 400, 200], "content": "text", "text": "漢字です"})).unwrap();
+ let sid = r["story"].as_u64().unwrap();
+ s.execute("text.select", &json!({"story": sid, "anchor": 0, "focus": "漢字".len()})).unwrap();
+ let f = |s: &Session| s.doc().unwrap().doc.stories[&designcraft_doc::StoryId(sid)].char_format_at(1).over.clone();
+ s.execute(
+ "type.ruby",
+ &json!({"text": "かん\u{3000}じ", "type": "perCharacter", "alignment": "oneAki", "position": "belowLeft", "size": 1e9, "xScale": -50, "scalingPercent": 5, "autoTcyDigits": 99, "fillTint": 250, "yOffset": -1e12, "fill": "[Black]"}),
+ )
+ .unwrap();
+ let a = f(&s);
+ assert_eq!(
+ (a.ruby.as_deref(), a.ruby_type, a.ruby_position),
+ (Some("かん\u{3000}じ"), Some(RubyType::PerCharacter), Some(RubyPosition::BelowLeft))
+ );
+ assert_eq!(a.ruby_font_size, Some(Some(1296.0)));
+ assert_eq!(a.ruby_x_scale, Some(0.01));
+ assert_eq!(a.ruby_scaling_min, Some(0.1));
+ assert_eq!(a.ruby_auto_tcy_digits, Some(9));
+ assert_eq!(a.ruby_fill_tint, Some(Some(1.0)));
+ assert_eq!(a.ruby_y_offset, Some(-1000.0));
+ // Options alone keep the reading.
+ s.execute("type.ruby", &json!({"alignment": "center"})).unwrap();
+ assert_eq!((f(&s).ruby, f(&s).ruby_alignment), (a.ruby.clone(), Some(RubyAlignment::Center)));
+ // Refused, and nothing changes: unknown names, non-numbers, overlong text, unknown swatches.
+ let long = "あ".repeat(designcraft_doc::ruby::MAX_RUBY_CHARS + 1);
+ for p in [
+ json!({"alignment": "sideways"}),
+ json!({"size": "big"}),
+ json!({"text": long}),
+ json!({"fill": "Nope"}),
+ json!({"autoAlign": 1}),
+ json!({"text": 5}),
+ ] {
+ assert!(s.execute("type.ruby", &p).is_err(), "{p}");
+ }
+ assert_eq!(f(&s).ruby_alignment, Some(RubyAlignment::Center));
+ assert_eq!(f(&s).ruby, a.ruby);
+ }
+
#[test]
fn warichu_toggles_on_the_selection_and_undoes() {
let mut s = Session::new();
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index b8f4a93a8..af680afb1 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -1187,9 +1187,12 @@ impl<'a> Ex<'a> {
el.set("PositionalForm", v);
}
if let Some(r) = a.ruby.as_ref() {
- el.set("RubyFlag", bool_s(!r.is_empty()));
+ el.set("RubyFlag", if r.is_empty() { "0" } else { "1" });
el.set("RubyString", r.as_str());
}
+ if let Some((family, style)) = crate::ruby::write(el, props, a, |n| self.sw(n)) {
+ self.note_font(&family, &style);
+ }
if let Some(k) = a.kenten {
el.set("KentenKind", if k { "KentenSesameDot" } else { "None" });
}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index d22ae144f..9823b5650 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -1165,9 +1165,11 @@ impl<'r> Importer<'r> {
a.warichu_alignment = e.prop("WarichuAlignment").as_deref().and_then(crate::cjk::warichu_align_in);
a.warichu_chars_before_break = e.num("WarichuCharsBeforeBreak").map(|v| v.max(0.0) as u32);
a.warichu_chars_after_break = e.num("WarichuCharsAfterBreak").map(|v| v.max(0.0) as u32);
- if let Some(on) = e.boolean("RubyFlag") {
+ // InDesign writes the flag as a number (1); older writers wrote a boolean.
+ if let Some(on) = e.boolean("RubyFlag").or_else(|| e.num("RubyFlag").map(|v| v != 0.0)) {
a.ruby = Some(if on { e.prop("RubyString").unwrap_or_default() } else { String::new() });
}
+ crate::ruby::read(e, &mut a, |r| self.swatch_ref(r));
if let Some(k) = e.get("KentenKind") {
a.kenten = Some(k != "None");
a.kenten_character = crate::cjk::kenten_character(k).map(str::to_string);
diff --git a/crates/idml/src/lib.rs b/crates/idml/src/lib.rs
index 71d688255..84ec3dc7b 100644
--- a/crates/idml/src/lib.rs
+++ b/crates/idml/src/lib.rs
@@ -43,6 +43,7 @@ mod cjk;
mod export;
mod import;
mod names;
+mod ruby;
mod xml;
#[cfg(test)]
diff --git a/crates/idml/src/ruby.rs b/crates/idml/src/ruby.rs
new file mode 100644
index 000000000..601792f6c
--- /dev/null
+++ b/crates/idml/src/ruby.rs
@@ -0,0 +1,191 @@
+//! IDML ruby settings (`Ruby*` attributes of styles and character ranges). `RubyFlag` and
+//! `RubyString` are read and written with the other character attributes.
+use designcraft_doc::CharAttrs;
+use designcraft_doc::ruby::{RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubyType};
+
+use crate::cjk::{overprint_in, overprint_out};
+use crate::names::num;
+use crate::xml::El;
+
+const TYPES: &[(RubyType, &str)] = &[(RubyType::Group, "GroupRuby"), (RubyType::PerCharacter, "PerCharacterRuby")];
+
+const ALIGNMENTS: &[(RubyAlignment, &str)] = &[
+ (RubyAlignment::Left, "RubyLeft"),
+ (RubyAlignment::Center, "RubyCenter"),
+ (RubyAlignment::Right, "RubyRight"),
+ (RubyAlignment::FullJustify, "RubyFullJustify"),
+ (RubyAlignment::Jis, "RubyJIS"),
+ (RubyAlignment::EqualAki, "RubyEqualAki"),
+ (RubyAlignment::OneAki, "Ruby1Aki"),
+];
+
+const POSITIONS: &[(RubyPosition, &str)] = &[(RubyPosition::AboveRight, "AboveRight"), (RubyPosition::BelowLeft, "BelowLeft")];
+
+const OVERHANGS: &[(RubyOverhang, &str)] = &[
+ (RubyOverhang::None, "None"),
+ (RubyOverhang::OneRuby, "RubyOverhangOneRuby"),
+ (RubyOverhang::HalfRuby, "RubyOverhangHalfRuby"),
+ (RubyOverhang::OneChar, "RubyOverhangOneChar"),
+ (RubyOverhang::HalfChar, "RubyOverhangHalfChar"),
+ (RubyOverhang::NoLimit, "RubyOverhangNoLimit"),
+];
+
+const SPACINGS: &[(RubyParentSpacing, &str)] = &[
+ (RubyParentSpacing::NoAdjustment, "RubyParentNoAdjustment"),
+ (RubyParentSpacing::BothSides, "RubyParentBothSides"),
+ (RubyParentSpacing::Aki121, "RubyParent121Aki"),
+ (RubyParentSpacing::EqualAki, "RubyParentEqualAki"),
+ (RubyParentSpacing::FullJustify, "RubyParentFullJustify"),
+];
+
+/// The text colour as IDML names it in place of a swatch.
+const TEXT_COLOR: &str = "Text Color";
+
+fn lookup<T: Copy>(table: &[(T, &str)], v: &str) -> Option<T> {
+ let v = v.trim();
+ table.iter().find(|(_, n)| *n == v).map(|(t, _)| *t)
+}
+
+fn name<T: Copy + PartialEq>(table: &[(T, &'static str)], v: T) -> Option<&'static str> {
+ table.iter().find(|(t, _)| *t == v).map(|(_, n)| *n)
+}
+
+fn finite(e: &El, k: &str) -> Option<f64> {
+ e.num(k).filter(|v| v.is_finite())
+}
+
+/// Read the ruby settings of a style or range element into `a`. `swatch` maps a swatch
+/// reference to the document's swatch name.
+pub(crate) fn read(e: &El, a: &mut CharAttrs, mut swatch: impl FnMut(&str) -> String) {
+ a.ruby_type = e.prop("RubyType").and_then(|v| lookup(TYPES, &v));
+ a.ruby_alignment = e.prop("RubyAlignment").and_then(|v| lookup(ALIGNMENTS, &v));
+ a.ruby_position = e.prop("RubyPosition").and_then(|v| lookup(POSITIONS, &v));
+ a.ruby_x_offset = finite(e, "RubyXOffset").map(|v| v.clamp(-1000.0, 1000.0));
+ a.ruby_y_offset = finite(e, "RubyYOffset").map(|v| v.clamp(-1000.0, 1000.0));
+ if let Some(f) = e.prop("RubyFont") {
+ let f = f.trim();
+ let fam = f.split('\t').next().unwrap_or(f);
+ a.ruby_font = Some(if fam == "$ID/" { String::new() } else { fam.to_string() });
+ }
+ if let Some(s) = e.prop("RubyFontStyle") {
+ let s = s.trim();
+ a.ruby_font_style = Some(if s == "Nothing" { String::new() } else { s.to_string() });
+ }
+ // -1: automatic (half the parent size).
+ a.ruby_font_size = finite(e, "RubyFontSize").map(|v| (v > 0.0).then_some(v.clamp(0.1, 1296.0)));
+ a.ruby_x_scale = finite(e, "RubyXScale").map(|v| (v / 100.0).clamp(0.01, 10.0));
+ a.ruby_y_scale = finite(e, "RubyYScale").map(|v| (v / 100.0).clamp(0.01, 10.0));
+ a.ruby_open_type_pro = e.boolean("RubyOpenTypePro");
+ a.ruby_auto_tcy_digits = finite(e, "RubyAutoTcyDigits").map(|v| v.clamp(0.0, 9.0) as u32);
+ a.ruby_auto_tcy_include_roman = e.boolean("RubyAutoTcyIncludeRoman");
+ a.ruby_auto_tcy_auto_scale = e.boolean("RubyAutoTcyAutoScale");
+ a.ruby_overhang = e.boolean("RubyOverhang");
+ a.ruby_overhang_amount = e.prop("RubyParentOverhangAmount").and_then(|v| lookup(OVERHANGS, &v));
+ a.ruby_parent_spacing = e.prop("RubyParentSpacing").and_then(|v| lookup(SPACINGS, &v));
+ a.ruby_auto_align = e.boolean("RubyAutoAlign");
+ a.ruby_auto_scaling = e.boolean("RubyAutoScaling");
+ a.ruby_scaling_min = finite(e, "RubyParentScalingPercent").map(|v| (v / 100.0).clamp(0.1, 1.0));
+ let color = |r: String, swatch: &mut dyn FnMut(&str) -> String| if r.trim() == TEXT_COLOR { String::new() } else { swatch(r.trim()) };
+ a.ruby_fill = e.prop("RubyFill").map(|r| color(r, &mut swatch));
+ a.ruby_stroke = e.prop("RubyStroke").map(|r| color(r, &mut swatch));
+ // -1: automatic (the text's tint, stroke weight).
+ let tint = |v: f64| (v >= 0.0).then_some((v / 100.0).clamp(0.0, 1.0) as f32);
+ a.ruby_fill_tint = finite(e, "RubyTint").map(tint);
+ a.ruby_stroke_tint = finite(e, "RubyStrokeTint").map(tint);
+ a.ruby_stroke_weight = finite(e, "RubyWeight").map(|v| (v >= 0.0).then_some(v.min(800.0)));
+ let overprint = |k: &str| e.prop(k).and_then(|v| overprint_in(&v));
+ a.ruby_overprint_fill = overprint("RubyOverprintFill");
+ a.ruby_overprint_stroke = overprint("RubyOverprintStroke");
+}
+
+/// Write the ruby settings set in `a`: attributes on `el`, fonts and colours as `props`. `sw`
+/// maps a swatch name to its IDML reference. Returns the ruby font (family, style) to list in
+/// the fonts part.
+pub(crate) fn write(el: &mut El, props: &mut Vec<El>, a: &CharAttrs, sw: impl Fn(&str) -> String) -> Option<(String, String)> {
+ let b = |v: bool| if v { "true" } else { "false" };
+ let prop = |k: &str, ty: &str, v: String| El::new(k).attr("type", ty).text(v);
+ if let Some(v) = a.ruby_type.and_then(|v| name(TYPES, v)) {
+ el.set("RubyType", v);
+ }
+ if let Some(v) = a.ruby_alignment.and_then(|v| name(ALIGNMENTS, v)) {
+ el.set("RubyAlignment", v);
+ }
+ if let Some(v) = a.ruby_position.and_then(|v| name(POSITIONS, v)) {
+ el.set("RubyPosition", v);
+ }
+ if let Some(v) = a.ruby_x_offset {
+ el.set("RubyXOffset", num(v));
+ }
+ if let Some(v) = a.ruby_y_offset {
+ el.set("RubyYOffset", num(v));
+ }
+ if let Some(v) = &a.ruby_font {
+ props.push(prop("RubyFont", "string", if v.is_empty() { "$ID/".into() } else { v.clone() }));
+ }
+ if let Some(v) = &a.ruby_font_style {
+ props.push(if v.is_empty() { prop("RubyFontStyle", "enumeration", "Nothing".into()) } else { prop("RubyFontStyle", "string", v.clone()) });
+ }
+ if let Some(v) = a.ruby_font_size {
+ el.set("RubyFontSize", num(v.unwrap_or(-1.0)));
+ }
+ if let Some(v) = a.ruby_x_scale {
+ el.set("RubyXScale", num(v * 100.0));
+ }
+ if let Some(v) = a.ruby_y_scale {
+ el.set("RubyYScale", num(v * 100.0));
+ }
+ if let Some(v) = a.ruby_open_type_pro {
+ el.set("RubyOpenTypePro", b(v));
+ }
+ if let Some(v) = a.ruby_auto_tcy_digits {
+ el.set("RubyAutoTcyDigits", v);
+ }
+ if let Some(v) = a.ruby_auto_tcy_include_roman {
+ el.set("RubyAutoTcyIncludeRoman", b(v));
+ }
+ if let Some(v) = a.ruby_auto_tcy_auto_scale {
+ el.set("RubyAutoTcyAutoScale", b(v));
+ }
+ if let Some(v) = a.ruby_overhang {
+ el.set("RubyOverhang", b(v));
+ }
+ if let Some(v) = a.ruby_overhang_amount.and_then(|v| name(OVERHANGS, v)) {
+ el.set("RubyParentOverhangAmount", v);
+ }
+ if let Some(v) = a.ruby_parent_spacing.and_then(|v| name(SPACINGS, v)) {
+ el.set("RubyParentSpacing", v);
+ }
+ if let Some(v) = a.ruby_auto_align {
+ el.set("RubyAutoAlign", b(v));
+ }
+ if let Some(v) = a.ruby_auto_scaling {
+ el.set("RubyAutoScaling", b(v));
+ }
+ if let Some(v) = a.ruby_scaling_min {
+ el.set("RubyParentScalingPercent", num(v * 100.0));
+ }
+ for (k, c) in [("RubyFill", &a.ruby_fill), ("RubyStroke", &a.ruby_stroke)] {
+ if let Some(c) = c {
+ props.push(if c.is_empty() { prop(k, "string", TEXT_COLOR.into()) } else { prop(k, "object", sw(c.as_str())) });
+ }
+ }
+ if let Some(v) = a.ruby_fill_tint {
+ el.set("RubyTint", num(v.map_or(-1.0, |t| t as f64 * 100.0)));
+ }
+ if let Some(v) = a.ruby_stroke_tint {
+ el.set("RubyStrokeTint", num(v.map_or(-1.0, |t| t as f64 * 100.0)));
+ }
+ if let Some(v) = a.ruby_stroke_weight {
+ el.set("RubyWeight", num(v.unwrap_or(-1.0)));
+ }
+ if let Some(v) = a.ruby_overprint_fill.map(overprint_out) {
+ el.set("RubyOverprintFill", v);
+ }
+ if let Some(v) = a.ruby_overprint_stroke.map(overprint_out) {
+ el.set("RubyOverprintStroke", v);
+ }
+ a.ruby_font.as_ref().filter(|f| !f.is_empty()).map(|f| {
+ let style = a.ruby_font_style.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| "Regular".into());
+ (f.clone(), style)
+ })
+}
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index 6dcaa0440..80e7bd80b 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -1465,3 +1465,101 @@ fn kenten_shatai_and_grid_settings_import_and_round_trip() {
(p2.grid_align, p2.grid_reference, p2.grid_gyoudori, p2.paragraph_gyoudori)
);
}
+
+#[test]
+fn ruby_settings_import_from_idml_and_round_trip() {
+ use designcraft_doc::cjk_settings::AdornmentOverprint;
+ use designcraft_doc::ruby::{RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubyType};
+ // InDesign's names: RubyFlag is a number, colours and fonts are properties.
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" RubyFlag="1" RubyString="かん じ" RubyType="PerCharacterRuby" RubyAlignment="RubyCenter" RubyPosition="BelowLeft" RubyYOffset="-1.4173228" RubyFontSize="-1" RubyXScale="90" RubyParentOverhangAmount="RubyOverhangNoLimit" RubyParentSpacing="RubyParentBothSides" RubyAutoAlign="false" RubyAutoScaling="true" RubyParentScalingPercent="40" RubyAutoTcyDigits="2" RubyTint="-1" RubyOverprintFill="Auto"><Properties><RubyFont type="string">$ID/</RubyFont><RubyFontStyle type="enumeration">Nothing</RubyFontStyle><RubyFill type="string">Text Color</RubyFill></Properties><Content>漢字</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let doc = import_idml(&fixture_with_story(story)).unwrap();
+ let a = doc.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();
+ assert_eq!(a.ruby.as_deref(), Some("かん じ"));
+ assert_eq!(a.ruby_type, Some(RubyType::PerCharacter));
+ assert_eq!(a.ruby_alignment, Some(RubyAlignment::Center));
+ assert_eq!(a.ruby_position, Some(RubyPosition::BelowLeft));
+ assert_eq!(a.ruby_y_offset, Some(-1.4173228));
+ assert_eq!(a.ruby_font_size, Some(None));
+ assert_eq!(a.ruby_x_scale, Some(0.9));
+ assert_eq!(a.ruby_overhang_amount, Some(RubyOverhang::NoLimit));
+ assert_eq!(a.ruby_parent_spacing, Some(RubyParentSpacing::BothSides));
+ assert_eq!((a.ruby_auto_align, a.ruby_auto_scaling, a.ruby_scaling_min), (Some(false), Some(true), Some(0.4)));
+ assert_eq!(a.ruby_auto_tcy_digits, Some(2));
+ assert_eq!((a.ruby_font.as_deref(), a.ruby_font_style.as_deref(), a.ruby_fill.as_deref()), (Some(""), Some(""), Some("")));
+ assert_eq!((a.ruby_fill_tint, a.ruby_overprint_fill), (Some(None), Some(AdornmentOverprint::Auto)));
+
+ // Every setting survives export and import.
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 200.0), lid, "漢字", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().format_chars(0.."漢字".len(), |f| {
+ let o = &mut f.over;
+ o.ruby = Some("かん じ".into());
+ o.ruby_type = Some(RubyType::PerCharacter);
+ o.ruby_alignment = Some(RubyAlignment::OneAki);
+ o.ruby_position = Some(RubyPosition::BelowLeft);
+ o.ruby_x_offset = Some(1.5);
+ o.ruby_y_offset = Some(-1.25);
+ o.ruby_font = Some("Source Sans 3".into());
+ o.ruby_font_style = Some("Bold".into());
+ o.ruby_font_size = Some(Some(7.0));
+ o.ruby_x_scale = Some(0.9);
+ o.ruby_y_scale = Some(1.1);
+ o.ruby_open_type_pro = Some(false);
+ o.ruby_auto_tcy_digits = Some(3);
+ o.ruby_auto_tcy_include_roman = Some(true);
+ o.ruby_auto_tcy_auto_scale = Some(false);
+ o.ruby_overhang = Some(true);
+ o.ruby_overhang_amount = Some(RubyOverhang::HalfChar);
+ o.ruby_parent_spacing = Some(RubyParentSpacing::EqualAki);
+ o.ruby_auto_align = Some(false);
+ o.ruby_auto_scaling = Some(true);
+ o.ruby_scaling_min = Some(0.5);
+ o.ruby_fill = Some("[Black]".into());
+ o.ruby_fill_tint = Some(Some(0.5));
+ o.ruby_stroke = Some(String::new());
+ o.ruby_stroke_tint = Some(None);
+ o.ruby_stroke_weight = Some(Some(0.25));
+ o.ruby_overprint_fill = Some(AdornmentOverprint::On);
+ o.ruby_overprint_stroke = Some(AdornmentOverprint::Off);
+ });
+ let a = d.stories[&sid].runs().next().unwrap().1.over.clone();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let b = back.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();
+ macro_rules! same {
+ ($($f:ident),*) => { $( assert_eq!(a.$f, b.$f, stringify!($f)); )* };
+ }
+ same!(
+ ruby,
+ ruby_type,
+ ruby_alignment,
+ ruby_position,
+ ruby_x_offset,
+ ruby_y_offset,
+ ruby_font,
+ ruby_font_style,
+ ruby_font_size,
+ ruby_x_scale,
+ ruby_y_scale,
+ ruby_open_type_pro,
+ ruby_auto_tcy_digits,
+ ruby_auto_tcy_include_roman,
+ ruby_auto_tcy_auto_scale,
+ ruby_overhang,
+ ruby_overhang_amount,
+ ruby_parent_spacing,
+ ruby_auto_align,
+ ruby_auto_scaling,
+ ruby_scaling_min,
+ ruby_fill,
+ ruby_fill_tint,
+ ruby_stroke,
+ ruby_stroke_tint,
+ ruby_stroke_weight,
+ ruby_overprint_fill,
+ ruby_overprint_stroke
+ );
+}
diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs
index cc031cb5a..3e349a1a4 100644
--- a/crates/render/src/text.rs
+++ b/crates/render/src/text.rs
@@ -363,7 +363,7 @@ impl Renderer {
for (si, bp) in &lg.runs {
if let Some(c) = fill_of(*si) {
let st = &cs.styles[*si as usize];
- let op = crate::overprints(f, &st.fill, st.fill_tint, false);
+ let op = crate::overprints(f, &st.fill, st.fill_tint, st.overprint_fill);
if op {
ctx.push_layer(
None,
diff --git a/docs/cjk.md b/docs/cjk.md
index 5da0a74a8..58a322bed 100644
--- a/docs/cjk.md
+++ b/docs/cjk.md
@@ -39,7 +39,7 @@ presets or tables are copied. Our default mojikumi and kinsoku tables are built
| Aki, tsume, jidori | done ([cjk-typography.md](cjk-typography.md)) |
| Character alignment, leading model | em box top / centre / bottom, ICF from ascender and descender, roman baseline; aki above / below, centre (centre down as centre) |
| Tate-chu-yoko | manual, with offsets; no auto, 3+ digits overflow the em |
-| Ruby | group ruby only, fixed 50 % size, no options, doesn't affect leading |
+| Ruby | group and per-character (jukugo) ruby; alignment (shoulder, centre, end, justify, JIS 1-2-1, equal aki, 1 ruby-character aki); above/right or below/left with offsets; font, size (½ by default), scales, OpenType `ruby` glyphs, auto tate-chu-yoko of digits; overhang onto kana and punctuation; parent spacing and automatic narrowing when the ruby is longer; flush with the line edge; fill, stroke, tint, weight and overprint fill on screen; every setting through `type.ruby` and IDML. Doesn't affect leading; overprint stroke isn't drawn and PDF has no overprint |
| Kenten | the IDML kinds and a custom character, drawn as characters; no position, size, alignment, colour or font |
| Composite fonts | done: model, `style.compositeFont.*`, shaping, IDML, font list, replace and Preflight; no dialog |
| Languages | Japanese, Korean, Simplified and Traditional Chinese reach the shaper (`locl`), font fallback, line breaking and typographer's quotes; IDML language names are kept as written; locale codes (`ja_JP`, `ko-KR`, `de_DE_2006`) are their language and region, and Chinese is also recognised in its common spellings ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`) |