Skip to content

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

CJK: kenten settings, shatai, auto tate-chu-yoko, rotate roman, roman word break and grid references

aiongg31a58a850118
diff --git a/crates/compose/src/grid.rs b/crates/compose/src/grid.rs
new file mode 100644
index 000000000..4bd2305e7
--- /dev/null
+++ b/crates/compose/src/grid.rs
@@ -0,0 +1,131 @@
+//! Grid Settings (グリッド設定) against the baseline grid: which point of a line sits on a grid
+//! line (grid alignment), how many grid lines a line takes (gyoudori, 行取り), and paragraph
+//! gyoudori, where the paragraph as a whole takes them.
+//!
+//! The document has a baseline grid (document or frame), not a frame grid of character cells, so
+//! each grid line stands for one line slot. A line that takes `n` grid lines holds its reference
+//! point on the first of them (em box or ICF top), midway (em box centre) or on the last (roman
+//! baseline, em box or ICF bottom); a paragraph-gyoudori block is placed the same way, measured
+//! from its first line's reference to its last's. The next line starts on the grid line after the
+//! band.
+
+use designcraft_doc::cjk::CharacterAlignment as Reference;
+
+use crate::shape::Glyph;
+
+/// Most grid lines one line or paragraph takes (input-derived).
+pub(crate) const MAX_GYOUDORI: u32 = 100;
+
+/// The ideographic character face's inset from the em box, top and bottom, as a share of the em.
+/// An approximation: fonts with a `BASE` table give `icft` / `icfb`, which aren't read yet.
+const ICF_INSET: f64 = 0.05;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+enum Anchor {
+ First,
+ Middle,
+ Last,
+}
+
+fn anchor(r: Reference) -> Anchor {
+ match r {
+ Reference::EmTop | Reference::IcfTop => Anchor::First,
+ Reference::EmCenter => Anchor::Middle,
+ Reference::Baseline | Reference::EmBottom | Reference::IcfBottom => Anchor::Last,
+ }
+}
+
+/// The line's grid reference point below its baseline (negative = above), from its largest
+/// character's em box ([`crate::cjk_em_box`], as the leading model measures it).
+pub(crate) fn reference_offset(line: &[Glyph], r: Reference) -> f64 {
+ if r == Reference::Baseline {
+ return 0.0;
+ }
+ let Some(g) = line.iter().filter(|g| g.adv > 0.0).max_by(|a, b| a.size.total_cmp(&b.size)) else { return 0.0 };
+ let (top, bottom) = crate::cjk_em_box(g);
+ let inset = (bottom - top) * ICF_INSET;
+ match r {
+ Reference::Baseline => 0.0,
+ Reference::EmTop => top,
+ Reference::EmCenter => (top + bottom) / 2.0,
+ Reference::EmBottom => bottom,
+ Reference::IcfTop => top + inset,
+ Reference::IcfBottom => bottom - inset,
+ }
+}
+
+/// Index of the first grid line at or below `y`.
+fn index_at(y: f64, start: f64, inc: f64) -> f64 {
+ ((y - start) / inc - 1e-6).ceil()
+}
+
+/// Grid lines a block of reference points `span` apart needs, at least `n`.
+pub(crate) fn lines_for(span: f64, inc: f64, n: u32) -> u32 {
+ let need = if inc > 0.0 && span.is_finite() && span > 0.0 { (span / inc + 1e-6).floor() + 1.0 } else { 1.0 };
+ let need = need.min(f64::from(MAX_GYOUDORI)) as u32;
+ need.max(n).clamp(1, MAX_GYOUDORI)
+}
+
+/// What a band of grid lines asks of [`place`].
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct Band {
+ /// The block's first reference point without the grid.
+ pub natural: f64,
+ /// First grid line not taken by earlier lines of the column (`None` at its top).
+ pub free: Option<f64>,
+ /// Space before still to add (paragraph space before, rounded up to whole grid lines).
+ pub pending: f64,
+ /// Gyoudori is set: the band starts right after the previous one, whatever the leading.
+ pub fixed: bool,
+ /// Grid lines the band takes (1 for an ordinary line).
+ pub lines: u32,
+ /// From the block's first reference point to its last (0 for one line).
+ pub span: f64,
+}
+
+/// Place a band on the grid `(start, increment)`: the block's first reference point, and the grid
+/// line after the band (the next line's first free grid line).
+pub(crate) fn place(grid: (f64, f64), r: Reference, band: Band) -> (f64, f64) {
+ let (start, inc) = grid;
+ let from_natural = index_at(band.natural, start, inc);
+ let k = match band.free {
+ Some(y) if band.fixed => index_at(y + band.pending.max(0.0), start, inc),
+ Some(y) => from_natural.max(index_at(y, start, inc)),
+ None => from_natural,
+ };
+ let first = start + k * inc;
+ let lines = f64::from(band.lines.clamp(1, MAX_GYOUDORI));
+ let room = ((lines - 1.0) * inc - band.span).max(0.0);
+ let y = match anchor(r) {
+ Anchor::First => first,
+ Anchor::Middle => first + room / 2.0,
+ Anchor::Last => first + room,
+ };
+ (y, first + lines * inc)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn bands_hold_their_reference_first_midway_or_last() {
+ let band = Band { natural: 25.0, free: None, pending: 0.0, fixed: false, lines: 1, span: 0.0 };
+ // One line: the next grid line at or below the natural position, whatever the reference.
+ assert_eq!(place((0.0, 12.0), Reference::Baseline, band), (36.0, 48.0));
+ assert_eq!(place((0.0, 12.0), Reference::EmTop, band), (36.0, 48.0));
+ let two = Band { lines: 2, ..band };
+ assert_eq!(place((0.0, 12.0), Reference::EmTop, two), (36.0, 60.0));
+ assert_eq!(place((0.0, 12.0), Reference::EmCenter, two), (42.0, 60.0));
+ assert_eq!(place((0.0, 12.0), Reference::Baseline, two), (48.0, 60.0));
+ // Gyoudori starts on the first free grid line, not where its leading would put it.
+ let fixed = Band { natural: 70.0, free: Some(48.0), fixed: true, ..two };
+ assert_eq!(place((0.0, 12.0), Reference::EmCenter, fixed).0, 54.0);
+ // A block of two lines 14 pt apart in three grid lines: centred in the room left.
+ let block = Band { lines: lines_for(14.0, 12.0, 3), span: 14.0, ..band };
+ assert_eq!(block.lines, 3);
+ assert_eq!(place((0.0, 12.0), Reference::EmCenter, block).0, 36.0 + 5.0);
+ assert_eq!(lines_for(1e300, 12.0, 0), MAX_GYOUDORI);
+ assert_eq!(lines_for(f64::NAN, 12.0, 0), 1);
+ }
+}
diff --git a/crates/compose/src/kenten.rs b/crates/compose/src/kenten.rs
new file mode 100644
index 000000000..7fdb3be3b
--- /dev/null
+++ b/crates/compose/src/kenten.rs
@@ -0,0 +1,191 @@
+//! Kenten (圏点): emphasis marks set beside each character of a run, over it in horizontal text
+//! and to its right in vertical text (where the frame's turn carries "above"), or under it / to
+//! its left. They don't change line breaks or leading.
+//!
+//! Placement follows W3C JLReq (emphasis dots) and JIS X 4051: each mark is centred in its own em
+//! box, that box sits next to the character's em box (plus the kenten distance) and is centred on
+//! the character, or starts with it when the alignment is Start (肩付き).
+
+use designcraft_doc::CharProps;
+use designcraft_fonts::{FaceRef, FontDb, ScopedFonts};
+use designcraft_geom::{Rect, Shape as _};
+
+use crate::{PlacedGlyph, RunStyle, upright_in_vertical};
+
+/// A run's kenten, resolved for layout ([`RunStyle::kenten_mark`]).
+#[derive(Clone, Debug, PartialEq)]
+pub struct KentenMark {
+ /// The mark: one character, or a short custom string.
+ pub text: String,
+ /// Family and style of a custom mark's font (`None` = the character's font).
+ pub font: Option<(String, String)>,
+ /// Size in points, and horizontal / vertical scale (1.0 = 100%).
+ pub size: f64,
+ pub x_scale: f64,
+ pub y_scale: f64,
+ /// Points between the character's em box and the mark's.
+ pub distance: f64,
+ /// Under the character (to its left in vertical text) rather than over it (to its right).
+ pub below: bool,
+ /// At the character's start rather than centred on it.
+ pub start: bool,
+ /// The marks' run style (their colour) in the composed story's style table.
+ pub style: u32,
+}
+
+/// Largest mark size and distance, in points (the largest type size).
+const MAX_POINTS: f64 = 1296.0;
+
+fn finite_or(v: f64, default: f64) -> f64 {
+ if v.is_finite() { v } else { default }
+}
+
+/// The mark size: the set size, else half the text size.
+fn mark_size(p: &CharProps) -> f64 {
+ p.kenten_size.filter(|v| v.is_finite() && *v > 0.0).unwrap_or(finite_or(p.size, 12.0) * 0.5).clamp(0.1, MAX_POINTS)
+}
+
+impl KentenMark {
+ /// The kenten of text formatted with `p`, drawn in run style `style`.
+ pub(crate) fn of(p: &CharProps, style: u32) -> KentenMark {
+ use designcraft_doc::cjk_settings::{KentenAlignment, KentenKind, KentenPosition, kenten_mark};
+ let custom_font = p.kenten_kind == KentenKind::Custom && !p.kenten_font.trim().is_empty();
+ let font_style = if p.kenten_font_style.trim().is_empty() { "Regular".to_string() } else { p.kenten_font_style.clone() };
+ KentenMark {
+ text: kenten_mark(p.kenten_kind, &p.kenten_character),
+ font: custom_font.then(|| (p.kenten_font.clone(), font_style)),
+ size: mark_size(p),
+ x_scale: finite_or(p.kenten_x_scale, 1.0).clamp(0.01, 10.0),
+ y_scale: finite_or(p.kenten_y_scale, 1.0).clamp(0.01, 10.0),
+ distance: finite_or(p.kenten_distance, 0.0).clamp(-MAX_POINTS, MAX_POINTS),
+ below: p.kenten_position == KentenPosition::BelowLeft,
+ start: p.kenten_alignment == KentenAlignment::Start,
+ style,
+ }
+ }
+}
+
+/// The marks' own character format (interned as their run style): Kenten Color over the text's
+/// colour, at the mark size, without the text's decorations.
+pub(crate) fn mark_props(p: &CharProps) -> CharProps {
+ let tint = |t: Option<f32>, text: f32| t.filter(|t| t.is_finite()).map_or(text, |t| t.clamp(0.0, 1.0));
+ let mut m = p.clone();
+ m.kenten = false;
+ m.size = mark_size(p);
+ if !p.kenten_fill.is_empty() {
+ m.fill.clone_from(&p.kenten_fill);
+ }
+ m.fill_tint = tint(p.kenten_fill_tint, p.fill_tint);
+ if !p.kenten_stroke.is_empty() {
+ m.stroke.clone_from(&p.kenten_stroke);
+ }
+ m.stroke_tint = tint(p.kenten_stroke_tint, p.stroke_tint);
+ if let Some(w) = p.kenten_stroke_weight.filter(|w| w.is_finite()) {
+ m.stroke_weight = w.clamp(0.0, 1000.0);
+ }
+ m.underline = false;
+ m.strikethrough = false;
+ m.skew = 0.0;
+ m.shatai_magnification = 0.0;
+ m.ruby = String::new();
+ m.warichu = false;
+ m.xml_tag = String::new();
+ m
+}
+
+/// Add the kenten of a laid-out line's characters. `glyph_fallback`: the document draws missing
+/// glyphs from fallback fonts (a missing font's substitute always does).
+pub(crate) fn annotate(db: &ScopedFonts<'_>, styles: &[RunStyle], line: &mut Vec<PlacedGlyph>, glyph_fallback: bool) {
+ if !line.iter().any(|g| styles.get(g.style as usize).is_some_and(|s| s.kenten_mark.is_some())) {
+ return;
+ }
+ let outlines = FontDb::global();
+ let mut extra = Vec::new();
+ for b in line.iter() {
+ let Some(st) = styles.get(b.style as usize) else { continue };
+ let Some(m) = &st.kenten_mark else { continue };
+ // Characters only: not generated glyphs (ruby, labels), controls or spaces.
+ if b.len == 0 || !b.visible || b.adv <= 0.0 || outlines.outline(&b.face, b.gid).elements().is_empty() {
+ continue;
+ }
+ extra.extend(marks(db, b, m, glyph_fallback || st.missing_font));
+ }
+ line.extend(extra);
+}
+
+/// `text` shaped in `face` at the mark's size and scales, from x = 0 on the baseline.
+fn shape_mark(face: FaceRef, text: &str, m: &KentenMark, b: &PlacedGlyph) -> Vec<PlacedGlyph> {
+ let k = m.size / face.units_per_em().max(1.0);
+ let (sx, sy) = (k * m.x_scale, k * m.y_scale);
+ let mut x = 0.0;
+ let mut out = Vec::new();
+ for sg in designcraft_fonts::shape(&face, text, &[], |c| c) {
+ let ch = text.get(sg.cluster..).and_then(|t| t.chars().next()).unwrap_or(' ');
+ let adv = f64::from(sg.x_advance) * sx;
+ out.push(PlacedGlyph {
+ face,
+ gid: sg.gid,
+ x: x + f64::from(sg.x_offset) * sx,
+ y: -f64::from(sg.y_offset) * sy,
+ adv,
+ sx,
+ sy,
+ style: m.style,
+ byte: b.byte,
+ len: 0,
+ visible: true,
+ upright: upright_in_vertical(ch),
+ tcy: None,
+ rtl: false,
+ });
+ x += adv;
+ }
+ out
+}
+
+/// The marks beside base character `b`. A mark the font lacks is its missing-glyph box, unless
+/// `fallback`: then a fallback font draws it, or failing that a bullet.
+fn marks(db: &ScopedFonts<'_>, b: &PlacedGlyph, m: &KentenMark, fallback: bool) -> Vec<PlacedGlyph> {
+ let mut face = match &m.font {
+ Some((family, style)) => FaceRef::of(&db.face(family, style)),
+ None => b.face,
+ };
+ if fallback
+ && let Some(c) = m.text.chars().next()
+ && !face.covers(c)
+ && let Some(f) = db.fallback_for(c, face.id(), None)
+ {
+ face = FaceRef::of(&f);
+ }
+ let mut glyphs = shape_mark(face, &m.text, m, b);
+ if fallback && glyphs.first().is_some_and(|d| d.gid == 0) {
+ glyphs = shape_mark(b.face, "\u{2022}", m, b);
+ }
+ // The character's em box across the line (y down from the line's baseline).
+ let (em_top, em_bottom) = b.face.em_box();
+ let (base_top, base_bottom) = (b.y - em_top * b.sy, b.y - em_bottom * b.sy);
+ let (w, h) = (m.size * m.x_scale, m.size * m.y_scale);
+ let (box_top, box_bottom) =
+ if m.below { (base_bottom + m.distance, base_bottom + m.distance + h) } else { (base_top - m.distance - h, base_top - m.distance) };
+ let centre_x = if m.start { b.x + w / 2.0 } else { b.x + b.adv / 2.0 };
+ let centre_y = (box_top + box_bottom) / 2.0;
+ // Centre the marks' ink in their em box (a mark's advance and baseline may hold it off centre).
+ let outlines = FontDb::global();
+ let ink = glyphs
+ .iter()
+ .map(|g| {
+ let r = outlines.outline(&g.face, g.gid).bounding_box();
+ Rect::new(g.x + r.x0 * g.sx, g.y + r.y0 * g.sy, g.x + r.x1 * g.sx, g.y + r.y1 * g.sy)
+ })
+ .filter(|r| r.width() > 0.0 && r.height() > 0.0)
+ .reduce(|a, r| a.union(r));
+ let (dx, dy) = match ink {
+ Some(r) => (centre_x - (r.x0 + r.x1) / 2.0, centre_y - (r.y0 + r.y1) / 2.0),
+ None => (centre_x - glyphs.iter().map(|g| g.adv).sum::<f64>() / 2.0, box_bottom),
+ };
+ for g in &mut glyphs {
+ g.x += dx;
+ g.y += dy;
+ }
+ glyphs
+}
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 3dd7c25b3..655b60db6 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -13,11 +13,14 @@
mod bidi;
pub mod breaker;
mod cache;
+mod grid;
pub mod hyphen;
+pub mod kenten;
mod notes;
mod overlay;
mod ruby;
pub mod shape;
+pub mod shatai;
pub mod table;
pub mod vars;
mod warichu;
@@ -67,10 +70,8 @@ pub struct RunStyle {
pub inserted: bool,
/// XML element the text is tagged with (tag markers on screen).
pub xml_tag: Option<String>,
- /// Ruby over the run, and kenten (emphasis dots).
+ /// Ruby over the run.
pub ruby: Option<String>,
- pub kenten: bool,
- pub kenten_character: String,
/// Warichu: stack this run in smaller lines inside the parent em.
pub warichu: bool,
pub warichu_lines: u32,
@@ -82,6 +83,10 @@ pub struct RunStyle {
pub warichu_align: designcraft_doc::cjk::WarichuAlignment,
pub warichu_chars_before: u32,
pub warichu_chars_after: u32,
+ /// Kenten Settings and Kenten Color resolved (`None` without kenten); see [`kenten`].
+ pub kenten_mark: Option<kenten::KentenMark>,
+ /// Shatai (`None` when off); see [`shatai`] and [`RunStyle::shatai_xf`].
+ pub shatai: Option<shatai::Shatai>,
}
/// An underline or strikethrough bar: its centre `offset` below the baseline (negative =
@@ -495,6 +500,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
limits: Rc::default(),
split: None,
split_limits: Rc::default(),
+ grid_next: None,
};
let para_ranges = story.para_ranges();
let np = para_ranges.len();
@@ -622,6 +628,9 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
vars: var_values,
hidden_conditions: doc.conditions.iter().filter(|c| !c.visible).map(|c| c.name.clone()).collect(),
vertical: cur_frame.is_some_and(|f| f.vertical),
+ auto_tcy: pp.auto_tcy.min(shape::AUTO_TCY_MAX),
+ auto_tcy_roman: pp.auto_tcy_include_roman,
+ rotate_roman: pp.rotate_roman,
..Default::default()
};
if !story.endnotes.is_empty() {
@@ -867,6 +876,8 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
let mut col_first_line = 0usize;
let has_tabs = glyphs.iter().any(|g| g.ch == '\t');
let mut first_line_rect: Option<(usize, f64, f64, f64)> = None; // frame, baseline, ascent, x-span
+ // Paragraph gyoudori: the (frame, column) of the block and the grid line after it.
+ let mut para_block: Option<((usize, usize), f64)> = None;
loop {
if cur.fi >= frames.len() {
if let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) {
@@ -919,13 +930,47 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
if cur.last_baseline.is_some() {
baseline += cur.last_reference - reference;
}
- // Baseline grid.
+ // Baseline grid: grid alignment and gyoudori (see `grid`).
+ let mut grid_end = None;
if let Some((g_start, inc)) = f.grid
&& (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))
&& inc > 0.0
+ && inc.is_finite()
{
- let n = ((baseline - g_start) / inc - 1e-6).ceil();
- baseline = g_start + n * inc;
+ let n = pp.grid_gyoudori.min(grid::MAX_GYOUDORI);
+ match para_block.filter(|(at, _)| line_no > 0 && *at == (cur.fi, cur.col)) {
+ // Inside a paragraph-gyoudori block, lines after the first keep their leading.
+ Some((_, end)) => grid_end = Some(end),
+ None => {
+ let r = grid::reference_offset(line_glyphs, pp.grid_reference);
+ let block = n > 0 && pp.paragraph_gyoudori && line_no == 0;
+ let span = if block {
+ // From this line's reference point to the paragraph's last line's.
+ let (mut down, mut prev, mut last_r) = (0.0, reference, r);
+ for nb in breaks.iter().skip(k + 1) {
+ let (ns, ne) = (g0 + nb.start, g0 + nb.end);
+ let lg = glyphs.get(ns..ne.max(ns)).unwrap_or_default();
+ let (_, _, nlead) = line_metrics(lg, &glyphs, ns, base_leading, base_chars.size, db, &base_chars);
+ let nref = cjk_line_reference(lg);
+ down += nlead + prev - nref;
+ prev = nref;
+ last_r = grid::reference_offset(lg, pp.grid_reference);
+ }
+ (down + last_r - r).max(0.0)
+ } else {
+ 0.0
+ };
+ let lines = if block { grid::lines_for(span, inc, n) } else { n.max(1) };
+ let free = cur.grid_next.filter(|(b, _)| cur.last_baseline == Some(*b)).map(|(_, y)| y);
+ let band = grid::Band { natural: baseline + r, free, pending: cur.pending, fixed: n > 0, lines, span };
+ let (y, end) = grid::place((g_start, inc), pp.grid_reference, band);
+ baseline = y - r;
+ grid_end = Some(end);
+ if block {
+ para_block = Some(((cur.fi, cur.col), end));
+ }
+ }
+ }
}
// Wrap: push the line down until a slot exists.
let (mut x0, mut x1) = (col.x0, col.x1);
@@ -1039,7 +1084,8 @@ 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(db, &styles_tab, &mut placed, doc.settings.glyph_fallback);
+ ruby::annotate(&styles_tab, &mut placed);
+ 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);
let range_start = if line_no == 0 { prange.start } else { range_start };
@@ -1089,6 +1135,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
cur.last_reference = reference;
cur.last_descent = desc;
cur.pending = 0.0;
+ cur.grid_next = grid_end.map(|end| (baseline, end));
line_no += 1;
// A column / frame / page break inside the paragraph: the rest of it continues in the
// new column/frame/page, re-broken there. (A break that ends the paragraph moves the
@@ -1512,6 +1559,10 @@ fn apply_desired_spacing(glyphs: &mut [Glyph], pp: &ParaProps) {
{
g.break_after = Some(false);
}
+ // Roman word break: a roman word may break between any two of its letters.
+ if pp.roman_word_break && g.break_after.is_none() && roman_letter(a) && roman_letter(b) {
+ g.break_after = Some(true);
+ }
}
}
}
@@ -1535,6 +1586,11 @@ fn apply_desired_spacing(glyphs: &mut [Glyph], pp: &ParaProps) {
}
}
+/// Letters of the roman scripts (Latin, Greek, Cyrillic), which Roman Word Break lets break.
+fn roman_letter(c: char) -> bool {
+ c.is_alphabetic() && matches!(c as u32, 0x41..=0x5A | 0x61..=0x7A | 0xC0..=0x24F | 0x370..=0x3FF | 0x400..=0x4FF | 0x1E00..=0x1EFF)
+}
+
/// Lengths of the composed output and the cursor before a paragraph (keep resolution re-lays
/// paragraphs from here). Only the cursor's frame and later ones can change afterwards.
struct Snapshot {
@@ -1732,6 +1788,9 @@ struct Cursor {
split: Option<SplitBlock>,
/// Bottoms that balance split blocks, by block part (kept by the compose loop).
split_limits: Rc<Vec<(SplitKey, f64)>>,
+ /// The first grid line after the last grid-aligned line's band, with that line's baseline (it
+ /// holds while `last_baseline` is still that baseline).
+ grid_next: Option<(f64, f64)>,
}
/// A band's frame and first paragraph.
@@ -3200,8 +3259,12 @@ pub fn path_glyphs(
} else {
designcraft_geom::Affine::IDENTITY
};
- let m =
- place * designcraft_geom::Affine::translate((g.x, l.baseline + g.y)) * skew * designcraft_geom::Affine::scale_non_uniform(g.sx, g.sy);
+ let shatai = style.shatai_xf(g, l.baseline).unwrap_or(designcraft_geom::Affine::IDENTITY);
+ let m = place
+ * shatai
+ * designcraft_geom::Affine::translate((g.x, l.baseline + g.y))
+ * skew
+ * designcraft_geom::Affine::scale_non_uniform(g.sx, g.sy);
let k = match runs.iter().position(|r| r.0 == g.style) {
Some(k) => k,
None => {
diff --git a/crates/compose/src/ruby.rs b/crates/compose/src/ruby.rs
index cea4a5545..2b2db84ef 100644
--- a/crates/compose/src/ruby.rs
+++ b/crates/compose/src/ruby.rs
@@ -1,12 +1,10 @@
-//! Ruby and kenten: 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.
-
-use designcraft_fonts::ScopedFonts;
-use designcraft_geom::Shape as _;
+//! 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`].
use crate::{PlacedGlyph, RunStyle, upright_in_vertical};
-/// Ruby and emphasis marks are half the base size.
+/// 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
@@ -40,42 +38,10 @@ fn set(base: &PlacedGlyph, text: &str, size: f64, base_size: f64) -> (Vec<Placed
(out, x)
}
-/// The emphasis `character` (a sesame dot when empty) centred over `b`, in `b`'s font. A
-/// character the font lacks is its missing-glyph box, unless `fallback` (fallback fonts draw
-/// missing glyphs): then a fallback font draws it, or failing that a bullet.
-fn kenten(db: &ScopedFonts<'_>, b: &PlacedGlyph, size: f64, character: &str, fallback: bool) -> Vec<PlacedGlyph> {
- let character = if character.is_empty() { "\u{FE45}" } else { character };
- let mut base = b.clone();
- if fallback
- && let Some(c) = character.chars().next()
- && !base.face.covers(c)
- && let Some(face) = db.fallback_for(c, base.face.id(), None)
- {
- base.face = designcraft_fonts::FaceRef::of(&face);
- }
- let (mut dot, mut w) = set(&base, character, size * SCALE, size);
- if fallback && dot.first().is_some_and(|d| d.gid == 0) {
- (dot, w) = set(b, "\u{2022}", size * SCALE, size);
- }
- // Centre the mark's ink (its advance may hold it off centre) and sit it just over the text.
- let ink = dot.first().map(|d| designcraft_fonts::FontDb::global().outline(&d.face, d.gid).bounding_box()).filter(|r| r.width() > 0.0);
- for d in &mut dot {
- match ink {
- Some(r) => {
- d.x = b.x + b.adv / 2.0 - (r.x0 + r.x1) / 2.0 * d.sx;
- d.y = -(size * 0.92) - r.y1 * d.sy;
- }
- None => d.x += b.x + (b.adv - w) / 2.0,
- }
- }
- dot
-}
-
-/// Add the ruby and kenten of a laid-out line's glyphs. `glyph_fallback`: the document draws
-/// missing glyphs from fallback fonts (a missing font's substitute always does).
-pub(crate) fn annotate(db: &ScopedFonts<'_>, styles: &[RunStyle], line: &mut Vec<PlacedGlyph>, glyph_fallback: bool) {
+/// 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() || s.kenten)) {
+ if !line.iter().any(|g| style(g).is_some_and(|s| s.ruby.is_some())) {
return;
}
let mut extra = Vec::new();
@@ -86,9 +52,6 @@ pub(crate) fn annotate(db: &ScopedFonts<'_>, styles: &[RunStyle], line: &mut Vec
i += 1;
continue;
};
- if st.kenten && g.adv > 0.0 {
- extra.extend(kenten(db, g, st.size, &st.kenten_character, glyph_fallback || st.missing_font));
- }
let Some(text) = &st.ruby else {
i += 1;
continue;
@@ -117,10 +80,6 @@ pub(crate) fn annotate(db: &ScopedFonts<'_>, styles: &[RunStyle], line: &mut Vec
}
}
extra.extend(glyphs);
- // Kenten on the rest of the group.
- for b in line[i + 1..j].iter().filter(|b| st.kenten && b.len > 0 && b.adv > 0.0) {
- extra.extend(kenten(db, b, st.size, &st.kenten_character, glyph_fallback || st.missing_font));
- }
i = j;
}
line.extend(extra);
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index 1e1af40a7..820f2cffe 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -105,8 +105,31 @@ pub struct SubstCtx {
/// Set in a Vertical Type frame: upright runs are shaped top to bottom (vertical forms and
/// metrics), the rest horizontally to be turned as a whole.
pub vertical: bool,
+ /// Auto tate-chu-yoko in vertical text: runs of up to this many half-width digits (with
+ /// `auto_tcy_roman`, also roman letters) are set across one em (0 = off).
+ pub auto_tcy: u32,
+ pub auto_tcy_roman: bool,
+ /// Half-width characters stand upright in vertical text (Rotate Roman Characters).
+ pub rotate_roman: bool,
}
+impl SubstCtx {
+ fn upright(&self) -> Upright {
+ Upright { vertical: self.vertical, rotate_roman: self.rotate_roman }
+ }
+}
+
+/// How a frame sets characters upright: in vertical text only, and with Rotate Roman also the
+/// half-width ones (see [`upright_runs`]).
+#[derive(Clone, Copy, Debug, Default)]
+pub(crate) struct Upright {
+ pub vertical: bool,
+ pub rotate_roman: bool,
+}
+
+/// Most characters auto tate-chu-yoko sets across one em (input-derived).
+pub const AUTO_TCY_MAX: u32 = 10;
+
/// The stand-in character of hidden conditional text: no width, no break, not drawn.
pub const HIDDEN: char = '\u{2060}';
@@ -132,6 +155,13 @@ pub(crate) struct StyleTable<'a> {
impl StyleTable<'_> {
fn intern(&mut self, db: &ScopedFonts<'_>, p: &CharProps) -> u32 {
+ // Kenten are drawn in a run style of their own (Kenten Color); it has no kenten itself.
+ let kenten_mark = if p.kenten {
+ let style = self.intern(db, &crate::kenten::mark_props(p));
+ Some(crate::kenten::KentenMark::of(p, style))
+ } else {
+ None
+ };
let rs = RunStyle {
fill: p.fill.clone(),
fill_tint: p.fill_tint,
@@ -160,8 +190,6 @@ impl StyleTable<'_> {
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()),
- kenten: p.kenten,
- kenten_character: p.kenten_character.clone(),
warichu: p.warichu,
warichu_lines: p.warichu_lines,
warichu_size: p.warichu_size,
@@ -169,6 +197,8 @@ impl StyleTable<'_> {
warichu_align: p.warichu_alignment,
warichu_chars_before: p.warichu_chars_before_break,
warichu_chars_after: p.warichu_chars_after_break,
+ kenten_mark,
+ shatai: crate::shatai::Shatai::of(p),
};
if let Some(i) = self.styles.iter().rposition(|s| *s == rs) {
return i as u32;
@@ -258,6 +288,9 @@ pub(crate) fn shape_para(
resolved.push((a, b, props, fmt, para_chars.clone()));
}
}
+ let auto_tcy =
+ if sub.vertical && sub.auto_tcy > 0 { auto_tcy_ranges(&story.text, range.clone(), sub.auto_tcy, sub.auto_tcy_roman) } else { Vec::new() };
+ let resolved = split_auto_tcy(resolved, &auto_tcy);
for (a, b, props, fmt, resolved_base) in resolved {
let style = table.intern(db, &props);
// A missing font's substitute stands in for the whole font: fallback fonts help it.
@@ -316,6 +349,7 @@ pub(crate) fn shape_para(
shape_run(db, &story.text, k..b, &props, auto_leading, style, sub, &mut glyphs);
}
}
+ fit_auto_tcy(&mut glyphs, &auto_tcy);
collapse_tcy(&mut glyphs, sub.vertical);
ShapedPara { glyphs, range }
}
@@ -460,6 +494,7 @@ fn shape_run(
g.dx += before - left * tsume;
g.adv += before + after - (left + right) * tsume;
}
+ crate::shatai::fit_advances(run, p);
if p.jidori > 0 && !run.is_empty() && !run.iter().any(|g| g.ch.is_control()) {
let clusters: Vec<usize> = run.iter().enumerate().filter(|(_, g)| g.len > 0).map(|(i, _)| i).collect();
let natural: f64 = run.iter().map(|g| g.adv).sum();
@@ -513,7 +548,7 @@ fn shape_run_raw(
let mut seg_face = primary.clone();
let flush = |a: usize, b: usize, face: &Arc<FontFace>, out: &mut Vec<Glyph>| {
if a < b {
- shape_segment(db, text, a..b, None, p, face, auto_leading, style, out, sub.vertical);
+ shape_segment(db, text, a..b, None, p, face, auto_leading, style, out, sub.upright());
}
};
for (i, c) in text[range.clone()].char_indices() {
@@ -538,7 +573,7 @@ fn shape_run_raw(
flush(seg_start, i, &seg_face, out);
seg_start = i + c.len_utf8();
let face = if primary.covers(d) { primary.clone() } else { fallback(d) };
- shape_segment(db, text, i..i + c.len_utf8(), Some(d.encode_utf8(&mut [0; 4])), p, &face, auto_leading, style, out, sub.vertical);
+ shape_segment(db, text, i..i + c.len_utf8(), Some(d.encode_utf8(&mut [0; 4])), p, &face, auto_leading, style, out, sub.upright());
continue;
}
}
@@ -570,7 +605,7 @@ fn shape_run_raw(
seg_start = i + c.len_utf8();
if let Some(vi) = designcraft_doc::vars::var_index(c) {
match sub.vars.get(vi).filter(|v| !v.is_empty()) {
- Some(v) => shape_segment(db, text, i..i + c.len_utf8(), Some(v), p, &primary, auto_leading, style, out, sub.vertical),
+ Some(v) => shape_segment(db, text, i..i + c.len_utf8(), Some(v), p, &primary, auto_leading, style, out, sub.upright()),
None => {
let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
g.adv = 0.0;
@@ -586,7 +621,7 @@ fn shape_run_raw(
} else {
sub.page_name.clone().unwrap_or_else(|| "#".into())
};
- shape_segment(db, text, i..i + c.len_utf8(), Some(&s), p, &primary, auto_leading, style, out, sub.vertical);
+ shape_segment(db, text, i..i + c.len_utf8(), Some(&s), p, &primary, auto_leading, style, out, sub.upright());
}
designcraft_doc::OBJECT_MARK => {
let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
@@ -609,7 +644,7 @@ fn shape_run_raw(
out.push(g);
}
designcraft_doc::XREF_MARK => match sub.xrefs.get(&i).filter(|t| !t.is_empty()) {
- Some(t) => shape_segment(db, text, i..i + c.len_utf8(), Some(t), p, &primary, auto_leading, style, out, sub.vertical),
+ Some(t) => shape_segment(db, text, i..i + c.len_utf8(), Some(t), p, &primary, auto_leading, style, out, sub.upright()),
None => {
let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
g.adv = 0.0;
@@ -618,7 +653,7 @@ fn shape_run_raw(
},
designcraft_doc::FOOTNOTE_REF | designcraft_doc::ENDNOTE_REF => {
let s = sub.notes.get(&i).map_or("#", String::as_str);
- shape_segment(db, text, i..i + c.len_utf8(), Some(s), p, &primary, auto_leading, style, out, sub.vertical);
+ shape_segment(db, text, i..i + c.len_utf8(), Some(s), p, &primary, auto_leading, style, out, sub.upright());
}
_ => {
// Zero-width control glyph carrying metrics (tabs get their width at line layout).
@@ -810,9 +845,10 @@ fn shape_segment(
auto_leading: TypeEnv,
style: u32,
out: &mut Vec<Glyph>,
- vertical: bool,
+ mode: Upright,
) {
let _ = db;
+ let vertical = mode.vertical;
let (size, k, ascent, descent, leading, cap, xh, shift) = metrics(face, p, auto_leading);
let hs = p.h_scale;
let tracking = p.tracking / 1000.0 * p.size;
@@ -834,7 +870,7 @@ fn shape_segment(
// Tate-chu-yoko is set across the line, so it stays horizontal.
let mut shaped: Vec<ShapedGlyph> = Vec::new();
let mut upright: Vec<bool> = Vec::new();
- for (r, up) in upright_runs(src, vertical && !p.tate_chu_yoko) {
+ for (r, up) in upright_runs(src, vertical && !p.tate_chu_yoko, mode.rotate_roman) {
let around = match replacement {
None => (text.get(..range.start + r.start).unwrap_or(""), text.get(range.start + r.end..).unwrap_or("")),
Some(_) => ("", ""),
@@ -922,13 +958,13 @@ fn shape_segment(
}
}
-/// `src` cut into runs set upright in vertical text (CJK) and runs that turn with the line, as
-/// (byte range, upright); combining marks stay with the run they follow. One horizontal run when
-/// `vertical` is false.
-fn upright_runs(src: &str, vertical: bool) -> Vec<(std::ops::Range<usize>, bool)> {
+/// `src` cut into runs set upright in vertical text (CJK, and with `rotate_roman` half-width
+/// characters too) and runs that turn with the line, as (byte range, upright); combining marks
+/// stay with the run they follow. One horizontal run when `vertical` is false.
+fn upright_runs(src: &str, vertical: bool, rotate_roman: bool) -> Vec<(std::ops::Range<usize>, bool)> {
let mut runs: Vec<(std::ops::Range<usize>, bool)> = Vec::new();
for (i, c) in src.char_indices() {
- let up = vertical && crate::upright_in_vertical(c);
+ let up = vertical && (crate::upright_in_vertical(c) || (rotate_roman && half_width_roman(c)));
match runs.last_mut() {
Some((r, u)) if *u == up || is_mark(c) => r.end = i + c.len_utf8(),
_ => runs.push((i..i + c.len_utf8(), up)),
@@ -937,6 +973,92 @@ fn upright_runs(src: &str, vertical: bool) -> Vec<(std::ops::Range<usize>, bool)
runs
}
+/// Half-width (single-byte) roman characters: what Rotate Roman Characters stands upright.
+fn half_width_roman(c: char) -> bool {
+ matches!(c, '!'..='~') || (matches!(c as u32, 0xC0..=0x24F) && c.is_alphabetic())
+}
+
+/// Auto tate-chu-yoko: the byte ranges in `range` of `text` that are runs of at most `max`
+/// half-width digits (with `roman`, digits and roman letters), each delimited by other characters.
+pub(crate) fn auto_tcy_ranges(text: &str, range: std::ops::Range<usize>, max: u32, roman: bool) -> Vec<std::ops::Range<usize>> {
+ let max = max.min(AUTO_TCY_MAX) as usize;
+ let takes = |c: char| c.is_ascii_digit() || (roman && c.is_ascii_alphabetic());
+ let mut out = Vec::new();
+ let Some(src) = text.get(range.clone()) else { return out };
+ let mut run: Option<(usize, usize)> = None; // (start byte, characters)
+ let close = |run: &mut Option<(usize, usize)>, end: usize, out: &mut Vec<std::ops::Range<usize>>| {
+ if let Some((start, n)) = run.take()
+ && n <= max
+ {
+ out.push(range.start + start..range.start + end);
+ }
+ };
+ for (i, c) in src.char_indices() {
+ if takes(c) {
+ run = Some(match run {
+ Some((start, n)) => (start, n + 1),
+ None => (i, 1),
+ });
+ } else {
+ close(&mut run, i, &mut out);
+ }
+ }
+ close(&mut run, src.len(), &mut out);
+ out
+}
+
+/// The resolved runs of a paragraph with auto tate-chu-yoko runs cut out and marked tate-chu-yoko
+/// (runs already tate-chu-yoko keep theirs).
+fn split_auto_tcy<'f>(
+ resolved: Vec<(usize, usize, CharProps, &'f designcraft_doc::CharFormat, CharProps)>,
+ auto: &[std::ops::Range<usize>],
+) -> Vec<(usize, usize, CharProps, &'f designcraft_doc::CharFormat, CharProps)> {
+ if auto.is_empty() {
+ return resolved;
+ }
+ let mut out = Vec::with_capacity(resolved.len() + 2 * auto.len());
+ for (a, b, props, fmt, base) in resolved {
+ if props.tate_chu_yoko {
+ out.push((a, b, props, fmt, base));
+ continue;
+ }
+ let mut at = a;
+ for r in auto.iter().filter(|r| r.start < b && r.end > a) {
+ let (s, e) = (r.start.max(a), r.end.min(b));
+ if at < s {
+ out.push((at, s, props.clone(), fmt, base.clone()));
+ }
+ let mut tcy = props.clone();
+ tcy.tate_chu_yoko = true;
+ out.push((s, e, tcy, fmt, base.clone()));
+ at = e;
+ }
+ if at < b {
+ out.push((at, b, props, fmt, base));
+ }
+ }
+ out
+}
+
+/// Auto tate-chu-yoko groups wider than their em are scaled across to fit it.
+fn fit_auto_tcy(glyphs: &mut [Glyph], auto: &[std::ops::Range<usize>]) {
+ for r in auto {
+ let group: Vec<usize> = glyphs.iter().enumerate().filter(|(_, g)| g.tcy.is_some() && r.contains(&g.byte)).map(|(i, _)| i).collect();
+ let width: f64 = group.iter().filter_map(|&i| glyphs.get(i)).map(|g| g.adv).sum();
+ let em = group.iter().filter_map(|&i| glyphs.get(i)).map(|g| g.size).fold(0.0, f64::max);
+ let k = if width > 0.0 { em / width } else { 1.0 };
+ if k > 0.0 && k < 1.0 {
+ for &i in &group {
+ if let Some(g) = glyphs.get_mut(i) {
+ g.adv *= k;
+ g.sx *= k;
+ g.dx *= k;
+ }
+ }
+ }
+ }
+}
+
/// A hyphen glyph in the face/size of `g`, placed after it (zero source length).
pub(crate) fn hyphen_after(g: &Glyph) -> Glyph {
let gid = designcraft_fonts::first_glyph(&g.face, &['-', '\u{2010}']);
diff --git a/crates/compose/src/shatai.rs b/crates/compose/src/shatai.rs
new file mode 100644
index 000000000..99e45d44b
--- /dev/null
+++ b/crates/compose/src/shatai.rs
@@ -0,0 +1,110 @@
+//! Shatai (斜体): the oblique of Japanese phototypesetting. The character's em box is compressed
+//! by the magnification across the direction at the shatai angle and kept at full size along it,
+//! about the em box centre, which slants the character. Adjust Rotation turns the result back so
+//! the em box edge along the line stays along the line; Adjust Tsume fits the advance to the
+//! compressed em box.
+//!
+//! The matrix matches what InDesign prints (measured from a public sample and its print PDF, as
+//! recorded by the clean-room `indd-to-idml` format notes): 20 % at 60° gives the text matrix
+//! (0.850, 0.0866, 0.0866, 0.950); 10 % at 60° with Adjust Rotation in vertical text gives
+//! (0.9222, 0.0843, 0, 0.9759). The pivot (em box centre) and the horizontal-text rotation (the
+//! glyph's horizontal axis stays horizontal) are not measured.
+
+use designcraft_doc::CharProps;
+use designcraft_geom::{Affine, Point};
+
+use crate::{PlacedGlyph, RunStyle};
+
+/// A run's shatai, resolved for layout ([`RunStyle::shatai`]).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Shatai {
+ /// Compression across the angle, as a fraction of the em (0 < m ≤ 0.9).
+ pub magnification: f64,
+ /// Degrees counter-clockwise from the line direction, in [0, 180).
+ pub angle: f64,
+ pub adjust_rotation: bool,
+ pub adjust_tsume: bool,
+}
+
+/// Largest compression kept: the em box never collapses to a line.
+const MAX_MAGNIFICATION: f64 = 0.9;
+
+impl Shatai {
+ /// The shatai of text with `p` (`None` when off).
+ pub fn of(p: &CharProps) -> Option<Shatai> {
+ let m = p.shatai_magnification;
+ if !m.is_finite() || m <= 0.0 {
+ return None;
+ }
+ let angle = if p.shatai_angle.is_finite() { p.shatai_angle.rem_euclid(180.0) } else { 45.0 };
+ Some(Shatai {
+ magnification: (m / 100.0).min(MAX_MAGNIFICATION),
+ angle,
+ adjust_rotation: p.shatai_adjust_rotation,
+ adjust_tsume: p.shatai_adjust_tsume,
+ })
+ }
+
+ /// The linear part in glyph space, y up, as PDF matrix values `[a, b, c, d]` (x' = a·x + c·y,
+ /// y' = b·x + d·y). `along_y`: the line runs along the glyph's y axis (an upright glyph in
+ /// vertical text), which Adjust Rotation keeps vertical; otherwise it keeps the x axis
+ /// horizontal.
+ pub fn linear(&self, along_y: bool) -> [f64; 4] {
+ let (s, c) = self.angle.to_radians().sin_cos();
+ let m = self.magnification;
+ // Identity minus m·v·vᵀ, v the unit normal of the angle's direction.
+ let (a, b, cc, d) = (1.0 - m * s * s, m * s * c, m * s * c, 1.0 - m * c * c);
+ if !self.adjust_rotation {
+ return [a, b, cc, d];
+ }
+ // Turn by φ so the chosen axis' image lies on that axis again.
+ let phi = if along_y { cc.atan2(d) } else { -b.atan2(a) };
+ let (sp, cp) = phi.sin_cos();
+ [cp * a - sp * b, sp * a + cp * b, cp * cc - sp * d, sp * cc + cp * d]
+ }
+
+ /// The em box's extent along the line after the transform, over its extent before: the
+ /// advance factor of Adjust Tsume. `w`, `h`: the em box's width and height.
+ pub fn extent(&self, along_y: bool, w: f64, h: f64) -> f64 {
+ let [a, b, c, d] = self.linear(along_y);
+ if along_y {
+ if h <= 0.0 { 1.0 } else { (b.abs() * w + d.abs() * h) / h }
+ } else if w <= 0.0 {
+ 1.0
+ } else {
+ (a.abs() * w + c.abs() * h) / w
+ }
+ }
+}
+
+impl RunStyle {
+ /// Shatai of glyph `g` on a line at `baseline`, in the line's space (y down): applied after
+ /// the glyph is drawn at its place and before a vertical frame's upright turn. `None` without
+ /// shatai.
+ pub fn shatai_xf(&self, g: &PlacedGlyph, baseline: f64) -> Option<Affine> {
+ let sh = self.shatai?;
+ let [a, b, c, d] = sh.linear(g.upright);
+ // y up → y down: negate the off-diagonal terms.
+ let lin = Affine::new([a, -b, -c, d, 0.0, 0.0]);
+ let (top, bottom) = g.face.em_box();
+ let centre = Point::new(g.x + g.face.advance(g.gid) * g.sx / 2.0, baseline + g.y - (top + bottom) / 2.0 * g.sy);
+ Some(Affine::translate(centre.to_vec2()) * lin * Affine::translate(-centre.to_vec2()))
+ }
+}
+
+/// Adjust Tsume: each shaped glyph of a shatai run takes the compressed em box's extent along the
+/// line, centred in it.
+pub(crate) fn fit_advances(run: &mut [crate::shape::Glyph], p: &CharProps) {
+ let Some(sh) = Shatai::of(p).filter(|s| s.adjust_tsume) else { return };
+ for g in run.iter_mut().filter(|g| g.adv > 0.0 && !g.ch.is_control() && !g.ch.is_whitespace()) {
+ let (top, bottom) = g.face.em_box();
+ let w = g.face.advance(g.gid) * g.sx;
+ let h = (top - bottom) * g.sy;
+ let along = if g.upright { h } else { w };
+ let delta = along * (sh.extent(g.upright, w, h) - 1.0);
+ if delta.is_finite() {
+ g.adv = (g.adv + delta).max(0.0);
+ g.dx += delta / 2.0;
+ }
+ }
+}
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 0d1fe2d27..ea344ce2d 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -2771,3 +2771,284 @@ fn empty_paragraphs_get_no_bullet_or_number() {
assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.", "", "2.", ""], "list `{name}`");
}
}
+
+// Kenten settings, shatai, auto tate-chu-yoko, rotate roman, roman word break and grid settings.
+
+/// The centre of a placed glyph's ink, relative to its line's baseline.
+fn ink_centre(g: &PlacedGlyph) -> Point {
+ let r = designcraft_geom::Shape::bounding_box(&*FontDb::global().outline(&g.face, g.gid));
+ Point::new(g.x + (r.x0 + r.x1) / 2.0 * g.sx, g.y + (r.y0 + r.y1) / 2.0 * g.sy)
+}
+
+#[test]
+fn kenten_sit_above_or_below_at_their_size_and_distance() {
+ use designcraft_doc::cjk_settings::{KentenKind, KentenPosition};
+ let (mut d, sid, _) = doc_with("AB", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());
+ let plain = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.len();
+ let set = |d: &mut Document, position: KentenPosition| {
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {
+ f.over.kenten = Some(true);
+ f.over.kenten_kind = Some(KentenKind::BlackCircle);
+ f.over.kenten_size = Some(Some(8.0));
+ f.over.kenten_x_scale = Some(1.5);
+ f.over.kenten_distance = Some(2.0);
+ f.over.kenten_position = Some(position);
+ });
+ };
+ for position in [KentenPosition::AboveRight, KentenPosition::BelowLeft] {
+ set(&mut d, position);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let marks = &l.glyphs[plain..];
+ assert_eq!(marks.len(), 2, "one mark per character");
+ for (b, m) in l.glyphs[..plain].iter().zip(marks) {
+ // 8 pt, 150% wide, in a run style of its own.
+ assert!((m.sx - 8.0 / m.face.units_per_em() * 1.5).abs() < 1e-9 && (m.sy - 8.0 / m.face.units_per_em()).abs() < 1e-9);
+ assert_ne!(m.style, b.style);
+ assert_eq!(cs.styles[m.style as usize].size, 8.0);
+ let (top, bottom) = b.face.em_box();
+ let want_y = match position {
+ KentenPosition::AboveRight => b.y - top * b.sy - 2.0 - 4.0,
+ KentenPosition::BelowLeft => b.y - bottom * b.sy + 2.0 + 4.0,
+ };
+ let c = ink_centre(m);
+ assert!((c.y - want_y).abs() < 1e-6, "{position:?}: {} vs {want_y}", c.y);
+ assert!((c.x - (b.x + b.adv / 2.0)).abs() < 1e-6, "centred on its character");
+ }
+ }
+}
+
+#[test]
+fn kenten_colour_is_its_own_run_style() {
+ let (mut d, sid, _) = doc_with("AB", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {
+ f.over.kenten = Some(true);
+ f.over.kenten_fill = Some("[Registration]".into());
+ f.over.kenten_fill_tint = Some(Some(0.5));
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let mark = l.glyphs.last().unwrap();
+ let st = &cs.styles[mark.style as usize];
+ assert_eq!((st.fill.as_str(), st.fill_tint), ("[Registration]", 0.5));
+ assert!(st.kenten_mark.is_none() && !st.underline);
+ assert_eq!(cs.styles[l.glyphs[0].style as usize].fill, "[Black]", "the text keeps its colour");
+}
+
+#[test]
+fn shatai_matches_the_measured_matrices() {
+ use crate::shatai::Shatai;
+ let close = |a: [f64; 4], b: [f64; 4]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3);
+ let plain = Shatai { magnification: 0.2, angle: 60.0, adjust_rotation: false, adjust_tsume: false };
+ assert!(close(plain.linear(true), [0.850, 0.0866, 0.0866, 0.950]), "{:?}", plain.linear(true));
+ let turned = Shatai { magnification: 0.1, angle: 60.0, adjust_rotation: true, adjust_tsume: false };
+ assert!(close(turned.linear(true), [0.9222, 0.0843, 0.0, 0.9759]), "{:?}", turned.linear(true));
+ // In horizontal text the turn keeps the glyph's horizontal axis horizontal.
+ assert!(turned.linear(false)[1].abs() < 1e-12);
+}
+
+#[test]
+fn shatai_slants_glyphs_about_their_em_centre_and_fits_the_advance() {
+ let (mut d, sid, _) = doc_with("AB", Rect::new(36.0, 36.0, 300.0, 100.0), ParaAttrs::default());
+ let glyph = |d: &Document| {
+ let cs = compose_story(d, sid, &ComposeOptions::default());
+ let l = cs.frames[0].lines[0].clone();
+ (cs.styles[l.glyphs[0].style as usize].clone(), l.glyphs[0].clone(), l.baseline)
+ };
+ let (_, before, _) = glyph(&d);
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {
+ f.over.shatai_magnification = Some(20.0);
+ f.over.shatai_angle = Some(60.0);
+ f.over.shatai_adjust_tsume = Some(false);
+ });
+ let (style, g, baseline) = glyph(&d);
+ assert!((g.adv - before.adv).abs() < 1e-9, "without Adjust Tsume the advance stays");
+ let xf = style.shatai_xf(&g, baseline).unwrap();
+ // y down: the off-diagonal terms change sign.
+ let [a, b, c, dd, _, _] = xf.as_coeffs();
+ assert!((a - 0.85).abs() < 1e-3 && (b + 0.0866).abs() < 1e-3 && (c + 0.0866).abs() < 1e-3 && (dd - 0.95).abs() < 1e-3);
+ let (top, bottom) = g.face.em_box();
+ let centre = Point::new(g.x + g.face.advance(g.gid) * g.sx / 2.0, baseline + g.y - (top + bottom) / 2.0 * g.sy);
+ assert!((xf * centre - centre).hypot() < 1e-9, "the em box centre stays put");
+ // Adjust Tsume: the advance becomes the compressed em box's width.
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.shatai_adjust_tsume = Some(true));
+ let (style, fitted, _) = glyph(&d);
+ let sh = style.shatai.unwrap();
+ let w = g.face.advance(g.gid) * g.sx;
+ let want = before.adv + w * (sh.extent(false, w, (top - bottom) * g.sy) - 1.0);
+ assert!((fitted.adv - want).abs() < 1e-9, "{} vs {want}", fitted.adv);
+ // No shatai without magnification.
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.shatai_magnification = Some(0.0));
+ assert!(glyph(&d).0.shatai.is_none());
+}
+
+#[test]
+fn auto_tate_chu_yoko_takes_short_digit_runs_in_vertical_text() {
+ let text = "令和12年と1234年と123";
+ let (mut d, sid, _) = doc_with(text, Rect::new(100.0, 100.0, 200.0, 400.0), ParaAttrs { auto_tcy: Some(3), ..Default::default() });
+ let glyphs = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.clone();
+ assert!(glyphs(&d).iter().all(|g| g.tcy.is_none()), "horizontal text has none");
+ d.story_mut(sid).unwrap().vertical = true;
+ let gs = glyphs(&d);
+ let at = |s: &str| text.find(s).unwrap();
+ let tcy: Vec<&PlacedGlyph> = gs.iter().filter(|g| g.tcy.is_some()).collect();
+ let two = at("12年");
+ let three = text.rfind("123").unwrap();
+ assert_eq!(tcy.iter().map(|g| g.byte).collect::<Vec<_>>(), [two, two + 1, three, three + 1, three + 2], "2 and 3 digits, not 4");
+ // Each group takes one em along the line; three digits are narrowed to fit across it.
+ let em = tcy[0].tcy.unwrap()[2];
+ assert!((tcy[..2].iter().map(|g| g.adv).sum::<f64>() - em).abs() < 1e-6);
+ let plain = gs.iter().find(|g| g.byte == at("1234")).unwrap();
+ assert!(tcy[2].sx < plain.sx, "{} {}", tcy[2].sx, plain.sx);
+ let [_, left, _] = tcy[2].tcy.unwrap();
+ assert!(left >= -em / 2.0 - 1e-6, "the narrowed group stays within the em");
+ // Roman letters too, with Include Roman.
+ let text2 = "縦AB横";
+ let (mut d, sid, _) = doc_with(text2, Rect::new(100.0, 100.0, 200.0, 400.0), ParaAttrs { auto_tcy: Some(2), ..Default::default() });
+ d.story_mut(sid).unwrap().vertical = true;
+ let count = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].glyphs.iter().filter(|g| g.tcy.is_some()).count();
+ assert_eq!(count(&d), 0);
+ d.story_mut(sid).unwrap().paras[0].para.auto_tcy_include_roman = Some(true);
+ assert_eq!(count(&d), 2);
+}
+
+#[test]
+fn rotate_roman_stands_half_width_characters_upright() {
+ let (mut d, sid, _) = doc_with("縦書きLatin", Rect::new(100.0, 100.0, 200.0, 400.0), ParaAttrs::default());
+ d.story_mut(sid).unwrap().vertical = true;
+ let latin_upright = |d: &Document| {
+ let cs = compose_story(d, sid, &ComposeOptions::default());
+ cs.frames[0].lines[0].glyphs.iter().filter(|g| g.len > 0 && g.byte >= "縦書き".len()).all(|g| g.upright)
+ };
+ assert!(!latin_upright(&d));
+ d.story_mut(sid).unwrap().paras[0].para.rotate_roman = Some(true);
+ assert!(latin_upright(&d));
+}
+
+#[test]
+fn roman_word_break_breaks_inside_words_without_hyphens() {
+ let para = ParaAttrs { composer: Some(designcraft_doc::Composer::SingleLine), hyphenate: Some(false), ..Default::default() };
+ let first_line = |rwb: bool| {
+ let (d, sid, _) = doc_with("ab cdefghijklm", Rect::new(0.0, 0.0, 40.0, 300.0), ParaAttrs { roman_word_break: Some(rwb), ..para.clone() });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert!(lines.iter().all(|l| !l.hyphenated && l.end_x <= l.x1 + 0.5));
+ lines[0].range.clone()
+ };
+ assert_eq!(first_line(false), 0..3, "the word moves down whole");
+ assert!(first_line(true).end > 3, "the line fills with part of the word");
+}
+
+/// Composed lines of a story in a frame with a 12 pt baseline grid; returns them and the grid.
+fn grid_doc(text: &str, para: ParaAttrs, edit: impl FnOnce(&mut Document, StoryId)) -> (Vec<Line>, (f64, f64)) {
+ let (mut d, sid, fid) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 400.0), para);
+ if let Some(tf) = d.item_mut(fid).and_then(|i| i.text_frame_mut()) {
+ tf.options.baseline_grid = Some((12.0, 0.0));
+ }
+ edit(&mut d, sid);
+ // Vertical frames have no baseline grid.
+ let grid = frame_specs(&d, sid)[0].grid.unwrap_or((0.0, 12.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ (all_lines(&cs).into_iter().cloned().collect(), grid)
+}
+
+/// The em box centre of a line's first glyph (as the composer measures it), y down.
+fn em_centre(l: &Line) -> f64 {
+ let g = &l.glyphs[0];
+ let (a, b) = g.face.vertical_metrics();
+ l.baseline + g.y + (b - a) / (2.0 * (a + b)) * g.face.units_per_em() * g.sy
+}
+
+fn on_grid(y: f64, (start, inc): (f64, f64)) -> bool {
+ let n = (y - start) / inc;
+ (n - n.round()).abs() < 1e-6
+}
+
+#[test]
+fn grid_alignment_puts_the_chosen_point_on_the_grid() {
+ use designcraft_doc::cjk::CharacterAlignment as R;
+ let para = |r: R| ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), grid_reference: Some(r), ..Default::default() };
+ let (roman, grid) = grid_doc("AB\nCD", para(R::Baseline), |_, _| {});
+ assert!(roman.iter().all(|l| on_grid(l.baseline, grid)));
+ let (centred, grid) = grid_doc("AB\nCD", para(R::EmCenter), |_, _| {});
+ assert!(centred.iter().all(|l| on_grid(em_centre(l), grid)));
+ assert!(!on_grid(centred[0].baseline, grid), "the baseline moves off the grid by the em centre's offset");
+ let offset = em_centre(&centred[0]) - centred[0].baseline;
+ let shift = centred[0].baseline - roman[0].baseline;
+ assert!(on_grid(shift + offset, (0.0, grid.1)), "{shift} {offset}");
+}
+
+#[test]
+fn gyoudori_two_lines_centres_a_heading_in_two_grid_lines() {
+ use designcraft_doc::cjk::CharacterAlignment as R;
+ let para = ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), grid_reference: Some(R::EmCenter), ..Default::default() };
+ let (lines, grid) = grid_doc("Head\nBody text", para, |d, sid| {
+ let st = d.story_mut(sid).unwrap();
+ st.format_chars(0..4, |f| f.over.size = Some(18.0));
+ st.format_paras(0..4, |p| p.para.grid_gyoudori = Some(2));
+ });
+ let (head, body) = (em_centre(&lines[0]), em_centre(&lines[1]));
+ assert!(on_grid(head - grid.1 / 2.0, grid), "midway between two grid lines: {head}");
+ assert!(on_grid(body, grid));
+ assert!((body - head - 1.5 * grid.1).abs() < 1e-6, "the body takes the grid line after the heading's two: {head} {body}");
+}
+
+#[test]
+fn paragraph_gyoudori_centres_the_whole_paragraph() {
+ use designcraft_doc::cjk::CharacterAlignment as R;
+ let para = ParaAttrs {
+ grid_align: Some(designcraft_doc::GridAlign::AllLines),
+ grid_reference: Some(R::EmCenter),
+ grid_gyoudori: Some(4),
+ paragraph_gyoudori: Some(true),
+ ..Default::default()
+ };
+ let (lines, grid) = grid_doc("One\u{2028}Two\nNext", para, |d, sid| {
+ d.story_mut(sid).unwrap().format_paras(10..14, |p| {
+ p.para.grid_gyoudori = Some(0);
+ p.para.paragraph_gyoudori = Some(false);
+ });
+ });
+ let firsts: Vec<f64> = lines.iter().map(em_centre).collect();
+ assert_eq!(lines.len(), 3, "{firsts:?}");
+ // Two lines a leading apart, centred as a block in four grid lines; the next paragraph on the fifth.
+ let middle = (firsts[0] + firsts[1]) / 2.0;
+ assert!(on_grid(middle - 1.5 * grid.1, grid), "{firsts:?}");
+ assert!((firsts[2] - (middle - 1.5 * grid.1) - 4.0 * grid.1).abs() < 1e-6, "{firsts:?}");
+}
+
+#[test]
+fn hostile_cjk_settings_compose_without_panicking() {
+ let para = ParaAttrs {
+ auto_tcy: Some(u32::MAX),
+ auto_tcy_include_roman: Some(true),
+ rotate_roman: Some(true),
+ roman_word_break: Some(true),
+ grid_align: Some(designcraft_doc::GridAlign::AllLines),
+ grid_reference: Some(designcraft_doc::cjk::CharacterAlignment::IcfBottom),
+ grid_gyoudori: Some(u32::MAX),
+ paragraph_gyoudori: Some(true),
+ ..Default::default()
+ };
+ for vertical in [false, true] {
+ let (_, _) = grid_doc("縦12AB書き\nmore text here", para.clone(), |d, sid| {
+ let st = d.story_mut(sid).unwrap();
+ st.vertical = vertical;
+ let len = st.len();
+ st.format_chars(0..len, |f| {
+ f.over.kenten = Some(true);
+ f.over.kenten_kind = Some(designcraft_doc::cjk_settings::KentenKind::Custom);
+ f.over.kenten_character = Some("★".repeat(100_000));
+ f.over.kenten_font = Some("No Such Font".into());
+ f.over.kenten_size = Some(Some(1e308));
+ f.over.kenten_x_scale = Some(-1e308);
+ f.over.kenten_y_scale = Some(f64::NAN);
+ f.over.kenten_distance = Some(f64::INFINITY);
+ f.over.kenten_fill_tint = Some(Some(f32::NAN));
+ f.over.kenten_stroke_weight = Some(Some(-1e308));
+ f.over.shatai_magnification = Some(1e308);
+ f.over.shatai_angle = Some(f64::NEG_INFINITY);
+ });
+ });
+ }
+}
diff --git a/crates/doc/src/attrs.rs b/crates/doc/src/attrs.rs
index b99740e2c..3d2943115 100644
--- a/crates/doc/src/attrs.rs
+++ b/crates/doc/src/attrs.rs
@@ -722,7 +722,8 @@ attr_set! {
jidori: u32 = 0,
character_alignment: crate::cjk::CharacterAlignment = crate::cjk::CharacterAlignment::Baseline,
leading_model: crate::cjk::LeadingModel = crate::cjk::LeadingModel::Roman,
- /// Explicit emphasis character; empty uses the traditional sesame dot.
+ /// The kenten mark's text: a custom mark, or the preset of `kenten_kind` (see
+ /// [`crate::cjk_settings::kenten_mark`]); empty is the sesame dot.
kenten_character: String = String::new(),
/// Horizontal / vertical scale, 1.0 = 100%.
h_scale: f64 = 1.0,
@@ -774,6 +775,41 @@ attr_set! {
/// Minimum characters on a warichu line before a break, and on the line after it.
warichu_chars_before_break: u32 = 1,
warichu_chars_after_break: u32 = 1,
+ // Kenten Settings / Kenten Color (`kenten` switches the marks on).
+ /// The mark; [`crate::cjk_settings::KentenKind::Custom`] draws `kenten_character`.
+ kenten_kind: crate::cjk_settings::KentenKind = crate::cjk_settings::KentenKind::SesameDot,
+ /// Font of a custom mark (empty = the text's font) and its style.
+ kenten_font: String = String::new(),
+ kenten_font_style: String = String::new(),
+ /// Mark size in points; `None` is half the text size.
+ kenten_size: Option<f64> = None,
+ /// Horizontal / vertical scale of the mark, 1.0 = 100%.
+ kenten_x_scale: f64 = 1.0,
+ kenten_y_scale: f64 = 1.0,
+ /// Points between the text's em box and the mark's.
+ kenten_distance: f64 = 0.0,
+ kenten_position: crate::cjk_settings::KentenPosition = crate::cjk_settings::KentenPosition::AboveRight,
+ kenten_alignment: crate::cjk_settings::KentenAlignment = crate::cjk_settings::KentenAlignment::Center,
+ /// How a custom mark was entered (IDML `KentenCharacterSet`), kept for interchange.
+ kenten_character_set: String = String::new(),
+ /// Mark fill and stroke swatches (empty = the text's), tints and stroke weight (`None` =
+ /// the text's).
+ kenten_fill: String = String::new(),
+ kenten_fill_tint: Option<f32> = None,
+ kenten_stroke: String = String::new(),
+ kenten_stroke_tint: Option<f32> = None,
+ kenten_stroke_weight: Option<f64> = None,
+ kenten_overprint_fill: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto,
+ kenten_overprint_stroke: crate::cjk_settings::AdornmentOverprint = crate::cjk_settings::AdornmentOverprint::Auto,
+ // Shatai (斜体): the character is compressed across the direction at `shatai_angle`.
+ /// Compression in percent of the em (0 = off).
+ shatai_magnification: f64 = 0.0,
+ /// Degrees from the line direction, counter-clockwise.
+ shatai_angle: f64 = 45.0,
+ /// Turn the compressed character back so its edge along the line stays along the line.
+ shatai_adjust_rotation: bool = false,
+ /// Fit the advance to the compressed em box.
+ shatai_adjust_tsume: bool = true,
/// Digits (World-Ready): how 0–9 are drawn.
digits: Digits = Digits::Default,
character_direction: crate::arabic::CharacterDirection = crate::arabic::CharacterDirection::Default,
@@ -890,6 +926,24 @@ attr_set! {
bunri_kinshi: bool = false,
rensuuji: bool = true,
treat_ideographic_space_as_space: bool = false,
+ // Auto Tate-chu-yoko, Japanese Composition and Grid Settings.
+ /// Auto tate-chu-yoko: in vertical text, runs of up to this many half-width digits are set
+ /// across one em (0 = off).
+ auto_tcy: u32 = 0,
+ /// Auto tate-chu-yoko also takes runs of half-width roman letters.
+ auto_tcy_include_roman: bool = false,
+ /// Rotate Roman Characters in Vertical Text (縦組み中の欧文回転): half-width characters
+ /// stand upright one by one instead of lying along the line.
+ rotate_roman: bool = false,
+ /// Roman word break (欧文泣き別れ): roman words may break between any two letters,
+ /// without a hyphen.
+ roman_word_break: bool = false,
+ /// The point of a line that sits on the grid while `grid_align` is on.
+ grid_reference: crate::cjk::CharacterAlignment = crate::cjk::CharacterAlignment::Baseline,
+ /// Gyoudori (行取り): grid lines each line takes (0 = as many as its leading needs).
+ grid_gyoudori: u32 = 0,
+ /// Paragraph gyoudori: the paragraph as a whole, not each line, takes `grid_gyoudori` lines.
+ paragraph_gyoudori: bool = false,
/// Paragraph shading, and how far it reaches past the text: top, left, bottom, right.
shading_on: bool = false,
shading_color: String = "[Black]".into(),
diff --git a/crates/doc/src/cjk_settings.rs b/crates/doc/src/cjk_settings.rs
new file mode 100644
index 000000000..67269ddb9
--- /dev/null
+++ b/crates/doc/src/cjk_settings.rs
@@ -0,0 +1,126 @@
+//! Value types of the Japanese typesetting settings beyond the basic CJK attributes in
+//! [`crate::cjk`]: kenten (圏点, emphasis marks) and their colour, and the overprint choice they
+//! share with other adornments. Shatai, auto tate-chu-yoko and the grid settings are plain numbers
+//! and switches on [`crate::CharAttrs`] / [`crate::ParaAttrs`].
+use serde::{Deserialize, Serialize};
+
+/// The kenten mark set beside each character (Kenten Settings › Kenten Type).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum KentenKind {
+ /// Sesame dot (ゴマ), the usual Japanese mark.
+ #[default]
+ SesameDot,
+ /// White sesame dot (白ゴマ).
+ WhiteSesameDot,
+ /// Fisheye (蛇の目): a black circle in a ring.
+ Fisheye,
+ BlackCircle,
+ SmallBlackCircle,
+ /// Bullseye (二重丸): two rings.
+ Bullseye,
+ BlackTriangle,
+ WhiteTriangle,
+ WhiteCircle,
+ SmallWhiteCircle,
+ /// [`crate::CharProps::kenten_character`] in [`crate::CharProps::kenten_font`].
+ Custom,
+}
+
+impl KentenKind {
+ /// Every kind, in menu order.
+ pub const ALL: [KentenKind; 11] = [
+ KentenKind::SesameDot,
+ KentenKind::WhiteSesameDot,
+ KentenKind::Fisheye,
+ KentenKind::BlackCircle,
+ KentenKind::SmallBlackCircle,
+ KentenKind::Bullseye,
+ KentenKind::BlackTriangle,
+ KentenKind::WhiteTriangle,
+ KentenKind::WhiteCircle,
+ KentenKind::SmallWhiteCircle,
+ KentenKind::Custom,
+ ];
+
+ /// The character drawn for a preset kind (`None` for [`KentenKind::Custom`]). The marks are
+ /// the emphasis characters of JIS X 4051 / W3C JLReq; the small circles are the bullet forms.
+ pub fn mark(self) -> Option<&'static str> {
+ Some(match self {
+ KentenKind::SesameDot => "\u{FE45}",
+ KentenKind::WhiteSesameDot => "\u{FE46}",
+ KentenKind::Fisheye => "\u{25C9}",
+ KentenKind::BlackCircle => "\u{25CF}",
+ KentenKind::SmallBlackCircle => "\u{2022}",
+ KentenKind::Bullseye => "\u{25CE}",
+ KentenKind::BlackTriangle => "\u{25B2}",
+ KentenKind::WhiteTriangle => "\u{25B3}",
+ KentenKind::WhiteCircle => "\u{25CB}",
+ KentenKind::SmallWhiteCircle => "\u{25E6}",
+ KentenKind::Custom => return None,
+ })
+ }
+}
+
+/// The longest custom kenten mark kept, in characters.
+pub const KENTEN_MARK_MAX_CHARS: usize = 8;
+
+/// The text of the mark for `kind` and the stored `character`. A custom mark is `character`
+/// (cut to [`KENTEN_MARK_MAX_CHARS`]); an empty one falls back to the sesame dot. Documents made
+/// before [`KentenKind`] existed store a preset as its character with the default kind, so a
+/// non-empty `character` with [`KentenKind::SesameDot`] is drawn as that character.
+pub fn kenten_mark(kind: KentenKind, character: &str) -> String {
+ let custom = || -> String { character.chars().filter(|c| !c.is_control()).take(KENTEN_MARK_MAX_CHARS).collect() };
+ let text = match kind {
+ KentenKind::Custom => custom(),
+ KentenKind::SesameDot if !character.is_empty() => custom(),
+ k => k.mark().unwrap_or_default().to_string(),
+ };
+ if text.is_empty() { "\u{FE45}".to_string() } else { text }
+}
+
+/// Which side of the line kenten sit on: above in horizontal text and to the right in vertical
+/// text, or below / to the left.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum KentenPosition {
+ #[default]
+ AboveRight,
+ BelowLeft,
+}
+
+/// Where a mark sits along its character: centred on it (中付き), or at its start (肩付き).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum KentenAlignment {
+ #[default]
+ Center,
+ Start,
+}
+
+/// Overprint of an adornment's fill or stroke: as the text's (`Auto`), or set on or off.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub enum AdornmentOverprint {
+ #[default]
+ Auto,
+ On,
+ Off,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn kenten_marks_follow_the_kind_and_cap_custom_text() {
+ assert_eq!(kenten_mark(KentenKind::SesameDot, ""), "\u{FE45}");
+ assert_eq!(kenten_mark(KentenKind::WhiteCircle, "x"), "\u{25CB}");
+ assert_eq!(kenten_mark(KentenKind::SesameDot, "○"), "○", "documents that stored the mark as text");
+ assert_eq!(kenten_mark(KentenKind::Custom, ""), "\u{FE45}");
+ let long = "★".repeat(10_000);
+ assert_eq!(kenten_mark(KentenKind::Custom, &long).chars().count(), KENTEN_MARK_MAX_CHARS);
+ assert_eq!(kenten_mark(KentenKind::Custom, "\n\u{7}"), "\u{FE45}", "control characters are dropped");
+ assert!(KentenKind::ALL.iter().all(|k| (*k == KentenKind::Custom) == k.mark().is_none()));
+ }
+}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index c4b69e86d..e00c1557d 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -15,6 +15,7 @@ pub mod arrow;
pub mod attrs;
pub mod build;
pub mod cjk;
+pub mod cjk_settings;
pub mod datamerge;
mod edit;
pub mod endnotes;
diff --git a/crates/engine/src/cmd/paths.rs b/crates/engine/src/cmd/paths.rs
index b9d479067..2d4c27d4d 100644
--- a/crates/engine/src/cmd/paths.rs
+++ b/crates/engine/src/cmd/paths.rs
@@ -255,7 +255,8 @@ fn create_outlines(s: &mut Session, p: &Value) -> Result<Value> {
continue;
}
let skew = if st.skew != 0.0 { Affine::new([1.0, 0.0, -st.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
- let a = Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
+ let shatai = st.shatai_xf(g, l.baseline).unwrap_or(Affine::IDENTITY);
+ let a = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
let key = (st.fill.clone(), st.fill_tint, st.stroke.clone(), st.stroke_tint, st.stroke_weight);
let k = match runs.iter().position(|r| r.0 == key) {
Some(k) => k,
diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs
index 3fc061d7d..b24c695b3 100644
--- a/crates/engine/src/cmd/preflight.rs
+++ b/crates/engine/src/cmd/preflight.rs
@@ -116,6 +116,12 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
let mut fams = vec![base.font_family.clone()];
for (run, f) in story.runs().filter(|(run, _)| run.start < range.end && run.end > range.start) {
let props = d.styles.resolve_char(&base, f);
+ {
+ use designcraft_doc::cjk_settings::AdornmentOverprint as O;
+ if props.kenten && (props.kenten_overprint_fill != O::Auto || props.kenten_overprint_stroke != O::Auto) {
+ unsupported_typography.insert("Kenten overprint is preserved, but not applied".to_string());
+ }
+ }
if has_rtl
&& story.text.get(run.start.max(range.start)..run.end.min(range.end)).is_some_and(|t| t.chars().any(designcraft_fonts::is_rtl))
{
diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs
index 4950d82b9..67d544661 100644
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@ -192,19 +192,54 @@ pub fn specs() -> Vec<CommandSpec> {
"Kenten",
[],
None,
- "{on?: bool} — emphasis dots over the selected characters (toggles by default)",
+ "{on?: bool, kind?: sesameDot|whiteSesameDot|fisheye|blackCircle|smallBlackCircle|bullseye|blackTriangle|whiteTriangle|whiteCircle|smallWhiteCircle|custom, character?: text (custom kind), font?: family (custom kind), fontStyle?, size?: pt (null: half the text size), distance?: pt, position?: aboveRight|belowLeft, alignment?: center|start, xScale?: %, yScale?: %, fill?: swatch (\"\": the text's), fillTint?: %, stroke?: swatch, strokeTint?: %, strokeWeight?: pt, overprintFill?: auto|on|off, overprintStroke?: auto|on|off} — emphasis marks beside the selected characters (toggles by default; any setting turns them on)",
has_text_or_frames,
- |s, p| {
- let on = match p.get("on").and_then(Value::as_bool) {
- Some(v) => v,
- None => !format_targets(s).first().is_some_and(|t| {
- s.doc().ok().and_then(|d| d.doc.text_story(t.story, t.cell)).is_some_and(|st| {
- st.char_format_at(if t.range.is_empty() { t.range.start } else { t.range.start + 1 }).over.kenten == Some(true)
- })
- }),
- };
- format_chars(s, &json!({"kenten": on}))
- }
+ kenten_cmd
+ ),
+ cmd!(
+ "type.shatai",
+ "Shatai",
+ [],
+ None,
+ "{magnification?: % (0 = off), angle?: degrees, adjustRotation?: bool, adjustTsume?: bool} — slant the selected characters by compressing them across a direction",
+ has_text_or_frames,
+ shatai_cmd
+ ),
+ cmd!(
+ "type.autoTateChuYoko",
+ "Auto Tate-Chu-Yoko",
+ [],
+ None,
+ "{digits?: 0..10 (0 = off), includeRoman?: bool} — in vertical text, set runs of up to `digits` half-width digits (and roman letters) across one em, for the selected paragraphs",
+ has_text_or_frames,
+ auto_tcy_cmd
+ ),
+ cmd!(
+ "type.gridSettings",
+ "Grid Settings",
+ [],
+ None,
+ "{alignment?: none|romanBaseline|emTop|emCenter|emBottom|icfTop|icfBottom, firstLineOnly?: bool, gyoudori?: 0..100 (0 = auto), paragraphGyoudori?: bool} — how the selected paragraphs sit on the baseline grid",
+ has_text_or_frames,
+ grid_settings_cmd
+ ),
+ cmd!(
+ "type.rotateRoman",
+ "Rotate Roman Characters in Vertical Text",
+ [],
+ None,
+ "{on?: bool} — half-width characters stand upright in vertical text, for the selected paragraphs (toggles by default)",
+ has_text_or_frames,
+ |s, p| para_toggle(s, p, "type.rotateRoman", "rotateRoman", |pp| pp.rotate_roman)
+ ),
+ cmd!(
+ "type.romanWordBreak",
+ "Roman Word Break",
+ [],
+ None,
+ "{on?: bool} — roman words in the selected paragraphs may break between any two letters, without a hyphen (toggles by default)",
+ has_text_or_frames,
+ |s, p| para_toggle(s, p, "type.romanWordBreak", "romanWordBreak", |pp| pp.roman_word_break)
),
cmd!(
"type.warichu",
@@ -819,6 +854,229 @@ fn warichu_cmd(s: &mut Session, p: &Value) -> Result<Value> {
format_chars(s, &Value::Object(body))
}
+// Kenten, shatai, auto tate-chu-yoko and grid settings: validated settings for the CJK commands.
+
+/// Longest font, style or swatch name taken from parameters, in characters.
+const NAME_MAX_CHARS: usize = 256;
+
+/// A number parameter: absent or `null` → `None`; anything but a finite number is an error.
+fn finite_param(p: &Value, key: &str, cmd: &str) -> Result<Option<f64>> {
+ match p.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(v) => v.as_f64().filter(|v| v.is_finite()).map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be a finite number"))),
+ }
+}
+
+/// A text parameter, cut to `max` characters: absent or `null` → `None`; not text is an error.
+fn text_param(p: &Value, key: &str, cmd: &str, max: usize) -> Result<Option<String>> {
+ match p.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::String(t)) => Ok(Some(t.chars().take(max).collect())),
+ Some(_) => Err(bad(cmd, format!("`{key}` must be text"))),
+ }
+}
+
+/// A boolean parameter: absent or `null` → `None`; not a boolean is an error.
+fn bool_param(p: &Value, key: &str, cmd: &str) -> Result<Option<bool>> {
+ match p.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(cmd, format!("`{key}` must be true or false"))),
+ }
+}
+
+/// An enumeration parameter checked against `T`, as its JSON value.
+fn enum_param<T: serde::de::DeserializeOwned + serde::Serialize>(p: &Value, key: &str, cmd: &str) -> Result<Option<Value>> {
+ match p.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(v) => {
+ let t: T = serde_json::from_value(v.clone()).map_err(|e| bad(cmd, format!("`{key}`: {e}")))?;
+ serde_json::to_value(t).map(Some).map_err(|e| bad(cmd, format!("`{key}`: {e}")))
+ }
+ }
+}
+
+/// 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| {
+ s.doc()
+ .ok()
+ .and_then(|d| d.doc.text_story(t.story, t.cell))
+ .is_some_and(|st| flag(&st.char_format_at(if t.range.is_empty() { t.range.start } else { t.range.start + 1 }).over) == Some(true))
+ })
+}
+
+fn kenten_cmd(s: &mut Session, p: &Value) -> Result<Value> {
+ use designcraft_doc::cjk_settings::{AdornmentOverprint, KENTEN_MARK_MAX_CHARS, KentenAlignment, KentenKind, KentenPosition};
+ const CMD: &str = "type.kenten";
+ let mut body = serde_json::Map::new();
+ let mut set = |k: &str, v: Value| {
+ body.insert(k.to_string(), v);
+ };
+ // Validate every setting first, so a bad one changes nothing.
+ if let Some(v) = enum_param::<KentenKind>(p, "kind", CMD)? {
+ // A preset stores its mark as the character too, as IDML import does, so a custom
+ // character left from before isn't drawn in its place.
+ if let Some(mark) = serde_json::from_value::<KentenKind>(v.clone()).ok().and_then(KentenKind::mark) {
+ set("kentenCharacter", json!(mark));
+ }
+ set("kentenKind", v);
+ }
+ if let Some(c) = text_param(p, "character", CMD, KENTEN_MARK_MAX_CHARS)? {
+ set("kentenCharacter", json!(c.chars().filter(|c| !c.is_control()).collect::<String>()));
+ }
+ for (key, attr) in [("font", "kentenFont"), ("fontStyle", "kentenFontStyle"), ("fill", "kentenFill"), ("stroke", "kentenStroke")] {
+ if let Some(t) = text_param(p, key, CMD, NAME_MAX_CHARS)? {
+ set(attr, json!(t));
+ }
+ }
+ if let Some(v) = finite_param(p, "size", CMD)? {
+ set("kentenSize", json!(v.clamp(0.1, 1296.0)));
+ }
+ if let Some(v) = finite_param(p, "distance", CMD)? {
+ set("kentenDistance", json!(v.clamp(-1296.0, 1296.0)));
+ }
+ for (key, attr) in [("xScale", "kentenXScale"), ("yScale", "kentenYScale")] {
+ if let Some(v) = finite_param(p, key, CMD)? {
+ set(attr, json!(v.clamp(1.0, 1000.0) / 100.0));
+ }
+ }
+ for (key, attr) in [("fillTint", "kentenFillTint"), ("strokeTint", "kentenStrokeTint")] {
+ if let Some(v) = finite_param(p, key, CMD)? {
+ set(attr, json!(v.clamp(0.0, 100.0) / 100.0));
+ }
+ }
+ if let Some(v) = finite_param(p, "strokeWeight", CMD)? {
+ set("kentenStrokeWeight", json!(v.clamp(0.0, 1000.0)));
+ }
+ if let Some(v) = enum_param::<KentenPosition>(p, "position", CMD)? {
+ set("kentenPosition", v);
+ }
+ if let Some(v) = enum_param::<KentenAlignment>(p, "alignment", CMD)? {
+ set("kentenAlignment", v);
+ }
+ for (key, attr) in [("overprintFill", "kentenOverprintFill"), ("overprintStroke", "kentenOverprintStroke")] {
+ if let Some(v) = enum_param::<AdornmentOverprint>(p, key, CMD)? {
+ set(attr, v);
+ }
+ }
+ // `null` returns a setting to the style's (size: half the text size by default).
+ for (key, attr) in
+ [("size", "kentenSize"), ("fillTint", "kentenFillTint"), ("strokeTint", "kentenStrokeTint"), ("strokeWeight", "kentenStrokeWeight")]
+ {
+ if p.get(key).is_some_and(Value::is_null) {
+ set(attr, Value::Null);
+ }
+ }
+ let on = match bool_param(p, "on", CMD)? {
+ Some(v) => v,
+ None if !body.is_empty() => true,
+ None => !char_flag_on(s, |f| f.kenten),
+ };
+ if !on {
+ // Off keeps the settings for the next time kenten are switched on.
+ body = serde_json::Map::new();
+ }
+ body.insert("kenten".into(), json!(on));
+ format_chars(s, &Value::Object(body))
+}
+
+fn shatai_cmd(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "type.shatai";
+ let mut body = serde_json::Map::new();
+ if let Some(v) = finite_param(p, "magnification", CMD)? {
+ body.insert("shataiMagnification".into(), json!(v.clamp(0.0, 90.0)));
+ }
+ if let Some(v) = finite_param(p, "angle", CMD)? {
+ body.insert("shataiAngle".into(), json!(v.rem_euclid(180.0)));
+ }
+ if let Some(v) = bool_param(p, "adjustRotation", CMD)? {
+ body.insert("shataiAdjustRotation".into(), json!(v));
+ }
+ if let Some(v) = bool_param(p, "adjustTsume", CMD)? {
+ body.insert("shataiAdjustTsume".into(), json!(v));
+ }
+ if body.is_empty() {
+ return Err(bad(CMD, "nothing to set: magnification, angle, adjustRotation or adjustTsume"));
+ }
+ format_chars(s, &Value::Object(body))
+}
+
+fn auto_tcy_cmd(s: &mut Session, p: &Value) -> Result<Value> {
+ const CMD: &str = "type.autoTateChuYoko";
+ let mut body = serde_json::Map::new();
+ if let Some(v) = finite_param(p, "digits", CMD)? {
+ let max = f64::from(designcraft_compose::shape::AUTO_TCY_MAX);
+ body.insert("autoTcy".into(), json!(v.round().clamp(0.0, max) as u32));
+ }
+ if let Some(v) = bool_param(p, "includeRoman", CMD)? {
+ body.insert("autoTcyIncludeRoman".into(), json!(v));
+ }
+ if body.is_empty() {
+ return Err(bad(CMD, "nothing to set: digits or includeRoman"));
+ }
+ format_paras(s, &Value::Object(body))
+}
+
+fn grid_settings_cmd(s: &mut Session, p: &Value) -> Result<Value> {
+ use designcraft_doc::cjk::CharacterAlignment as R;
+ const CMD: &str = "type.gridSettings";
+ let mut body = serde_json::Map::new();
+ let first_only = bool_param(p, "firstLineOnly", CMD)?;
+ match text_param(p, "alignment", CMD, 32)?.as_deref() {
+ None => {
+ if let Some(f) = first_only {
+ body.insert("gridAlign".into(), json!(if f { "firstLineOnly" } else { "allLines" }));
+ }
+ }
+ Some("none") => {
+ body.insert("gridAlign".into(), json!("none"));
+ }
+ Some(name) => {
+ let reference = match name {
+ "romanBaseline" | "baseline" => R::Baseline,
+ "emTop" => R::EmTop,
+ "emCenter" => R::EmCenter,
+ "emBottom" => R::EmBottom,
+ "icfTop" => R::IcfTop,
+ "icfBottom" => R::IcfBottom,
+ other => return Err(bad(CMD, format!("unknown alignment `{other}`"))),
+ };
+ body.insert("gridAlign".into(), json!(if first_only == Some(true) { "firstLineOnly" } else { "allLines" }));
+ body.insert("gridReference".into(), json!(reference));
+ }
+ }
+ if let Some(v) = finite_param(p, "gyoudori", CMD)? {
+ let max = 100.0;
+ body.insert("gridGyoudori".into(), json!(v.round().clamp(0.0, max) as u32));
+ }
+ if let Some(v) = bool_param(p, "paragraphGyoudori", CMD)? {
+ body.insert("paragraphGyoudori".into(), json!(v));
+ }
+ if body.is_empty() {
+ return Err(bad(CMD, "nothing to set: alignment, firstLineOnly, gyoudori or paragraphGyoudori"));
+ }
+ format_paras(s, &Value::Object(body))
+}
+
+/// Switch a paragraph attribute of the selected paragraphs: `on`, else the opposite of the
+/// first one's.
+fn para_toggle(s: &mut Session, p: &Value, cmd: &str, attr: &str, get: impl Fn(&designcraft_doc::ParaProps) -> bool) -> Result<Value> {
+ let on = match bool_param(p, "on", cmd)? {
+ Some(v) => v,
+ None => !format_targets(s).first().is_some_and(|t| {
+ s.doc().ok().is_some_and(|d| {
+ d.doc
+ .text_story(t.story, t.cell)
+ .and_then(|st| st.paras.get(st.para_at(t.range.start)))
+ .is_some_and(|pf| get(&d.doc.styles.resolve_para(pf).0))
+ })
+ }),
+ };
+ let mut body = serde_json::Map::new();
+ body.insert(attr.to_string(), json!(on));
+ format_paras(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() {
@@ -1882,4 +2140,64 @@ mod story_query_contract_tests {
s.execute("text.select", &json!({"story":f["story"],"anchor":0})).unwrap();
assert_eq!(s.execute("story.get", &json!({})).unwrap()["text"], "");
}
+
+ #[test]
+ fn kenten_shatai_auto_tcy_and_grid_settings_take_checked_values() {
+ use designcraft_doc::cjk::CharacterAlignment;
+ use designcraft_doc::cjk_settings::{KentenKind, KentenPosition};
+ let mut s = crate::Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 200, 400], "content": "text", "text": "縦書き12年", "vertical": true})).unwrap();
+ let sid = designcraft_doc::StoryId(r["story"].as_u64().unwrap());
+ s.execute("text.select", &json!({"story": sid.0, "anchor": 0, "focus": "縦書き".len()})).unwrap();
+ let chars = |s: &crate::Session| s.doc().unwrap().doc.stories[&sid].char_format_at(1).over.clone();
+ let para = |s: &crate::Session| s.doc().unwrap().doc.stories[&sid].paras[0].para.clone();
+ // Any setting turns kenten on; values are clamped and text is capped.
+ let long = "★".repeat(10_000);
+ s.execute(
+ "type.kenten",
+ &json!({"kind": "custom", "character": long, "size": 1e300, "distance": -1e300, "xScale": 0, "fillTint": 250, "position": "belowLeft"}),
+ )
+ .unwrap();
+ let a = chars(&s);
+ assert_eq!((a.kenten, a.kenten_kind, a.kenten_position), (Some(true), Some(KentenKind::Custom), Some(KentenPosition::BelowLeft)));
+ assert_eq!(a.kenten_character.as_ref().map(|c| c.chars().count()), Some(designcraft_doc::cjk_settings::KENTEN_MARK_MAX_CHARS));
+ assert_eq!(
+ (a.kenten_size, a.kenten_distance, a.kenten_x_scale, a.kenten_fill_tint),
+ (Some(Some(1296.0)), Some(-1296.0), Some(0.01), Some(Some(1.0)))
+ );
+ // Bad values change nothing.
+ for bad in [json!({"kind": "sparkle"}), json!({"size": "big"}), json!({"character": 5}), json!({"on": "yes"}), json!({"overprintFill": 1})] {
+ assert!(s.execute("type.kenten", &bad).is_err(), "{bad}");
+ }
+ assert_eq!(chars(&s), a);
+ s.execute("type.kenten", &json!({"on": false})).unwrap();
+ assert_eq!((chars(&s).kenten, chars(&s).kenten_kind), (Some(false), Some(KentenKind::Custom)), "off keeps the settings");
+ // Shatai.
+ s.execute("type.shatai", &json!({"magnification": 1e9, "angle": -30, "adjustRotation": true})).unwrap();
+ let a = chars(&s);
+ assert_eq!((a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation), (Some(90.0), Some(150.0), Some(true)));
+ assert!(s.execute("type.shatai", &json!({})).is_err());
+ assert!(s.execute("type.shatai", &json!({"angle": [45]})).is_err());
+ // Paragraph settings.
+ s.execute("type.autoTateChuYoko", &json!({"digits": 1e12, "includeRoman": true})).unwrap();
+ assert_eq!((para(&s).auto_tcy, para(&s).auto_tcy_include_roman), (Some(designcraft_compose::shape::AUTO_TCY_MAX), Some(true)));
+ s.execute("type.gridSettings", &json!({"alignment": "emCenter", "firstLineOnly": true, "gyoudori": 1e12, "paragraphGyoudori": true}))
+ .unwrap();
+ let p = para(&s);
+ assert_eq!((p.grid_align, p.grid_reference), (Some(designcraft_doc::GridAlign::FirstLineOnly), Some(CharacterAlignment::EmCenter)));
+ assert_eq!((p.grid_gyoudori, p.paragraph_gyoudori), (Some(100), Some(true)));
+ assert!(s.execute("type.gridSettings", &json!({"alignment": "middle"})).is_err());
+ s.execute("type.gridSettings", &json!({"alignment": "none"})).unwrap();
+ assert_eq!(para(&s).grid_align, Some(designcraft_doc::GridAlign::None));
+ s.execute("type.rotateRoman", &json!({})).unwrap();
+ assert_eq!(para(&s).rotate_roman, Some(true));
+ s.execute("type.rotateRoman", &json!({})).unwrap();
+ assert_eq!(para(&s).rotate_roman, Some(false));
+ s.execute("type.romanWordBreak", &json!({"on": true})).unwrap();
+ assert_eq!(para(&s).roman_word_break, Some(true));
+ // The story still composes with every setting at its limit.
+ let cs = designcraft_compose::compose_story(&s.doc().unwrap().doc, sid, &Default::default());
+ assert!(!cs.frames.is_empty());
+ }
}
diff --git a/crates/idml/src/cjk.rs b/crates/idml/src/cjk.rs
index ae9f25892..df3bc530b 100644
--- a/crates/idml/src/cjk.rs
+++ b/crates/idml/src/cjk.rs
@@ -78,3 +78,118 @@ pub(crate) fn kenten_character(v: &str) -> Option<&'static str> {
_ => return None,
})
}
+
+// Kenten, shatai, auto tate-chu-yoko and grid settings.
+
+use designcraft_doc::cjk_settings::{AdornmentOverprint, KentenAlignment, KentenKind, KentenPosition};
+
+/// `KentenKind`. `None`, `KentenSesameDot` and `KentenSmallBlackCircle` are confirmed names; the
+/// others follow their pattern. `KentenBlackBullseye` / `KentenWhiteBullseye` are read as well.
+pub(crate) fn kenten_kind_in(v: &str) -> Option<KentenKind> {
+ Some(match v.trim() {
+ "KentenSesameDot" => KentenKind::SesameDot,
+ "KentenWhiteSesameDot" => KentenKind::WhiteSesameDot,
+ "KentenFisheye" | "KentenBlackBullseye" => KentenKind::Fisheye,
+ "KentenBlackCircle" => KentenKind::BlackCircle,
+ "KentenSmallBlackCircle" => KentenKind::SmallBlackCircle,
+ "KentenBullseye" | "KentenWhiteBullseye" => KentenKind::Bullseye,
+ "KentenBlackTriangle" => KentenKind::BlackTriangle,
+ "KentenWhiteTriangle" => KentenKind::WhiteTriangle,
+ "KentenWhiteCircle" => KentenKind::WhiteCircle,
+ "KentenSmallWhiteCircle" => KentenKind::SmallWhiteCircle,
+ "Custom" => KentenKind::Custom,
+ _ => return None,
+ })
+}
+
+pub(crate) fn kenten_kind_out(k: KentenKind) -> &'static str {
+ match k {
+ KentenKind::SesameDot => "KentenSesameDot",
+ KentenKind::WhiteSesameDot => "KentenWhiteSesameDot",
+ KentenKind::Fisheye => "KentenFisheye",
+ KentenKind::BlackCircle => "KentenBlackCircle",
+ KentenKind::SmallBlackCircle => "KentenSmallBlackCircle",
+ KentenKind::Bullseye => "KentenBullseye",
+ KentenKind::BlackTriangle => "KentenBlackTriangle",
+ KentenKind::WhiteTriangle => "KentenWhiteTriangle",
+ KentenKind::WhiteCircle => "KentenWhiteCircle",
+ KentenKind::SmallWhiteCircle => "KentenSmallWhiteCircle",
+ KentenKind::Custom => "Custom",
+ }
+}
+
+pub(crate) fn kenten_position_in(v: &str) -> Option<KentenPosition> {
+ match v.trim() {
+ "AboveRight" => Some(KentenPosition::AboveRight),
+ "BelowLeft" => Some(KentenPosition::BelowLeft),
+ _ => None,
+ }
+}
+
+pub(crate) fn kenten_position_out(v: KentenPosition) -> &'static str {
+ match v {
+ KentenPosition::AboveRight => "AboveRight",
+ KentenPosition::BelowLeft => "BelowLeft",
+ }
+}
+
+/// `KentenAlignment`: `AlignKentenCenter` is confirmed, `AlignKentenLeft` (肩付き) is a guess.
+pub(crate) fn kenten_alignment_in(v: &str) -> Option<KentenAlignment> {
+ match v.trim() {
+ "AlignKentenCenter" => Some(KentenAlignment::Center),
+ "AlignKentenLeft" | "AlignKentenStart" => Some(KentenAlignment::Start),
+ _ => None,
+ }
+}
+
+pub(crate) fn kenten_alignment_out(v: KentenAlignment) -> &'static str {
+ match v {
+ KentenAlignment::Center => "AlignKentenCenter",
+ KentenAlignment::Start => "AlignKentenLeft",
+ }
+}
+
+/// Adornment overprint: `Auto` is confirmed, `OverprintOn` / `OverprintOff` are guesses.
+pub(crate) fn overprint_in(v: &str) -> Option<AdornmentOverprint> {
+ match v.trim() {
+ "Auto" => Some(AdornmentOverprint::Auto),
+ "OverprintOn" | "true" => Some(AdornmentOverprint::On),
+ "OverprintOff" | "false" => Some(AdornmentOverprint::Off),
+ _ => None,
+ }
+}
+
+pub(crate) fn overprint_out(v: AdornmentOverprint) -> &'static str {
+ match v {
+ AdornmentOverprint::Auto => "Auto",
+ AdornmentOverprint::On => "OverprintOn",
+ AdornmentOverprint::Off => "OverprintOff",
+ }
+}
+
+/// `GridAlignment` other than `None`: the grid reference. Both `ICF` spellings are read; unknown
+/// values align the roman baseline.
+pub(crate) fn grid_reference_in(v: &str) -> A {
+ match v.trim() {
+ "AlignEmTop" => A::EmTop,
+ "AlignEmCenter" => A::EmCenter,
+ "AlignEmBottom" => A::EmBottom,
+ "AlignICFTop" | "AlignIcfTop" => A::IcfTop,
+ "AlignICFBottom" | "AlignIcfBottom" => A::IcfBottom,
+ _ => A::Baseline,
+ }
+}
+
+pub(crate) fn grid_reference_out(v: A) -> &'static str {
+ match v {
+ A::Baseline => "AlignBaseline",
+ A::EmTop => "AlignEmTop",
+ A::EmCenter => "AlignEmCenter",
+ A::EmBottom => "AlignEmBottom",
+ A::IcfTop => "AlignICFTop",
+ A::IcfBottom => "AlignICFBottom",
+ }
+}
+
+/// IDML writes `ShataiDegreeAngle` in hundredths of a degree (`4500` = 45°).
+pub(crate) const SHATAI_ANGLE_UNITS: f64 = 100.0;
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index 9d73562b9..b8f4a93a8 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -1229,6 +1229,7 @@ impl<'a> Ex<'a> {
if let Some(v) = a.warichu_chars_after_break {
el.set("WarichuCharsAfterBreak", v);
}
+ self.cjk_settings_chars(el, props, a);
if let Some(list) = &a.conditions {
el.set("AppliedConditions", list.iter().map(|c| format!("Condition/{}", escape_id(c))).collect::<Vec<_>>().join(" "));
}
@@ -1263,6 +1264,7 @@ impl<'a> Ex<'a> {
if let Some(v) = a.treat_ideographic_space_as_space {
el.set("TreatIdeographicSpaceAsSpace", bool_s(v));
}
+ cjk_settings_para(el, a);
if let Some(Some(k)) = &a.kinsoku {
props.push(p(
"KinsokuSet",
@@ -1371,14 +1373,17 @@ impl<'a> Ex<'a> {
n!(drop_cap_lines, "DropCapLines");
n!(drop_cap_chars, "DropCapCharacters");
if let Some(g) = a.grid_align {
+ // IDML has one attribute for on/off and the reference: a reference set without
+ // `grid_align` isn't written.
+ let reference = crate::cjk::grid_reference_out(a.grid_reference.unwrap_or_default());
match g {
designcraft_doc::GridAlign::None => el.set("GridAlignment", "None"),
designcraft_doc::GridAlign::AllLines => {
- el.set("GridAlignment", "AlignToBaseline");
+ el.set("GridAlignment", reference);
el.set("GridAlignFirstLineOnly", "false");
}
designcraft_doc::GridAlign::FirstLineOnly => {
- el.set("GridAlignment", "AlignToBaseline");
+ el.set("GridAlignment", reference);
el.set("GridAlignFirstLineOnly", "true");
}
}
@@ -2665,3 +2670,103 @@ fn topic_self(path: &[String]) -> String {
}
s
}
+
+/// Auto tate-chu-yoko, Japanese composition and grid settings of a paragraph range or style.
+fn cjk_settings_para(el: &mut El, a: &ParaAttrs) {
+ if let Some(v) = a.auto_tcy {
+ el.set("AutoTcy", v);
+ }
+ if let Some(v) = a.auto_tcy_include_roman {
+ el.set("AutoTcyIncludeRoman", bool_s(v));
+ }
+ if let Some(v) = a.rotate_roman {
+ el.set("RotateSingleByteCharacters", bool_s(v));
+ }
+ if let Some(v) = a.roman_word_break {
+ el.set("AllowArbitraryHyphenation", bool_s(v));
+ }
+ if let Some(v) = a.grid_gyoudori {
+ el.set("GridGyoudori", v);
+ }
+ if let Some(v) = a.paragraph_gyoudori {
+ el.set("ParagraphGyoudori", bool_s(v));
+ }
+}
+
+impl Ex<'_> {
+ /// Kenten Settings, Kenten Color and Shatai of a character range or style.
+ fn cjk_settings_chars(&self, el: &mut El, props: &mut Vec<El>, a: &CharAttrs) {
+ use designcraft_doc::cjk_settings::KentenKind;
+ if let Some(k) = a.kenten_kind
+ && a.kenten != Some(false)
+ {
+ el.set("KentenKind", crate::cjk::kenten_kind_out(k));
+ if k != KentenKind::Custom {
+ el.attrs.retain(|(n, _)| n != "KentenCustomCharacter");
+ } else if let Some(c) = &a.kenten_character {
+ el.set("KentenCustomCharacter", c);
+ }
+ }
+ if let Some(f) = &a.kenten_font {
+ props.push(p("KentenFont", "string", if f.is_empty() { "$ID/".to_string() } else { f.clone() }));
+ }
+ if let Some(st) = &a.kenten_font_style {
+ props.push(if st.is_empty() { p("KentenFontStyle", "enumeration", "Nothing") } else { p("KentenFontStyle", "string", st.clone()) });
+ }
+ if let Some(Some(v)) = a.kenten_size {
+ el.set("KentenFontSize", num(v));
+ }
+ if let Some(v) = a.kenten_x_scale {
+ el.set("KentenXScale", num(v * 100.0));
+ }
+ if let Some(v) = a.kenten_y_scale {
+ el.set("KentenYScale", num(v * 100.0));
+ }
+ if let Some(v) = a.kenten_distance {
+ el.set("KentenPlacement", num(v));
+ }
+ if let Some(v) = a.kenten_position {
+ el.set("KentenPosition", crate::cjk::kenten_position_out(v));
+ }
+ if let Some(v) = a.kenten_alignment {
+ el.set("KentenAlignment", crate::cjk::kenten_alignment_out(v));
+ }
+ if let Some(v) = &a.kenten_character_set {
+ el.set("KentenCharacterSet", v);
+ }
+ // The text's own colour is the string "Text Color" (a property); a swatch is a reference.
+ for (key, color) in [("KentenFillColor", &a.kenten_fill), ("KentenStrokeColor", &a.kenten_stroke)] {
+ match color {
+ Some(c) if c.is_empty() => props.push(p(key, "string", "Text Color")),
+ Some(c) => el.set(key, self.sw(c)),
+ None => {}
+ }
+ }
+ for (key, tint) in [("KentenTint", a.kenten_fill_tint), ("KentenStrokeTint", a.kenten_stroke_tint)] {
+ if let Some(t) = tint {
+ el.set(key, t.map_or_else(|| "-1".to_string(), |t| num(f64::from(t) * 100.0)));
+ }
+ }
+ if let Some(w) = a.kenten_stroke_weight {
+ el.set("KentenWeight", w.map_or_else(|| "-1".to_string(), num));
+ }
+ if let Some(v) = a.kenten_overprint_fill {
+ el.set("KentenOverprintFill", crate::cjk::overprint_out(v));
+ }
+ if let Some(v) = a.kenten_overprint_stroke {
+ el.set("KentenOverprintStroke", crate::cjk::overprint_out(v));
+ }
+ if let Some(v) = a.shatai_magnification {
+ el.set("ShataiMagnification", num(v));
+ }
+ if let Some(v) = a.shatai_angle {
+ el.set("ShataiDegreeAngle", num(v * crate::cjk::SHATAI_ANGLE_UNITS));
+ }
+ if let Some(v) = a.shatai_adjust_rotation {
+ el.set("ShataiAdjustRotation", bool_s(v));
+ }
+ if let Some(v) = a.shatai_adjust_tsume {
+ el.set("ShataiAdjustTsume", bool_s(v));
+ }
+ }
+}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index d85d9ee02..d22ae144f 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -1182,6 +1182,7 @@ impl<'r> Importer<'r> {
a.diacritic_x_offset = e.num("XOffsetDiacritic").filter(|v| v.is_finite());
a.diacritic_y_offset = e.num("YOffsetDiacritic").filter(|v| v.is_finite());
a.positional_form = e.prop("PositionalForm");
+ self.cjk_settings_chars(e, &mut a);
if let Some(v) = e.get("AppliedConditions").filter(|v| !v.trim().is_empty()) {
let names: Vec<String> = v.split_whitespace().filter_map(|r| self.condition_names.get(r).cloned()).collect();
if !names.is_empty() {
@@ -1208,6 +1209,7 @@ impl<'r> Importer<'r> {
a.bunri_kinshi = e.boolean("BunriKinshi");
a.rensuuji = e.boolean("Rensuuji");
a.treat_ideographic_space_as_space = e.boolean("TreatIdeographicSpaceAsSpace");
+ cjk_settings_para(e, &mut a);
if let Some(k) = e.prop("KinsokuSet") {
if k == "Nothing" || k == "None" {
a.kinsoku = Some(Some(Default::default()));
@@ -1281,13 +1283,16 @@ impl<'r> Importer<'r> {
a.drop_cap_lines = u("DropCapLines");
a.drop_cap_chars = u("DropCapCharacters");
if let Some(g) = e.prop("GridAlignment") {
- a.grid_align = Some(if g == "None" {
+ a.grid_align = Some(if g.trim() == "None" {
GridAlign::None
} else if e.boolean("GridAlignFirstLineOnly") == Some(true) {
GridAlign::FirstLineOnly
} else {
GridAlign::AllLines
});
+ if g.trim() != "None" {
+ a.grid_reference = Some(crate::cjk::grid_reference_in(&g));
+ }
}
a.composer = e
.prop("Composer")
@@ -2561,3 +2566,62 @@ pub(crate) fn uri_to_path(uri: &str) -> String {
}
String::from_utf8_lossy(&out).to_string()
}
+
+/// Auto tate-chu-yoko, Japanese composition and grid settings of a paragraph range or style.
+fn cjk_settings_para(e: &El, a: &mut ParaAttrs) {
+ let count = |k: &str| e.num(k).filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 1000.0) as u32);
+ a.auto_tcy = count("AutoTcy");
+ a.auto_tcy_include_roman = e.boolean("AutoTcyIncludeRoman");
+ a.rotate_roman = e.boolean("RotateSingleByteCharacters");
+ // 欧文泣き別れ: the name is inferred (it follows TreatIdeographicSpaceAsSpace).
+ a.roman_word_break = e.boolean("AllowArbitraryHyphenation");
+ a.grid_gyoudori = count("GridGyoudori");
+ a.paragraph_gyoudori = e.boolean("ParagraphGyoudori");
+}
+
+impl Importer<'_> {
+ /// Kenten Settings, Kenten Color and Shatai of a character range or style.
+ fn cjk_settings_chars(&mut self, e: &El, a: &mut CharAttrs) {
+ let finite = |k: &str| e.num(k).filter(|v| v.is_finite());
+ if let Some(kind) = e.get("KentenKind").and_then(crate::cjk::kenten_kind_in) {
+ a.kenten_kind = Some(kind);
+ if a.kenten_character.as_deref().is_none_or(str::is_empty)
+ && let Some(mark) = kind.mark()
+ {
+ a.kenten_character = Some(mark.to_string());
+ }
+ }
+ if let Some(f) = e.prop("KentenFont") {
+ let f = f.trim();
+ a.kenten_font = Some(if f == "$ID/" { String::new() } else { f.to_string() });
+ }
+ if let Some(st) = e.prop("KentenFontStyle") {
+ let st = st.trim();
+ a.kenten_font_style = Some(if st == "Nothing" { String::new() } else { st.to_string() });
+ }
+ a.kenten_size = finite("KentenFontSize").map(|v| (v > 0.0).then_some(v));
+ a.kenten_x_scale = finite("KentenXScale").map(|v| v / 100.0);
+ a.kenten_y_scale = finite("KentenYScale").map(|v| v / 100.0);
+ a.kenten_distance = finite("KentenPlacement");
+ a.kenten_position = e.prop("KentenPosition").and_then(|v| crate::cjk::kenten_position_in(&v));
+ a.kenten_alignment = e.prop("KentenAlignment").and_then(|v| crate::cjk::kenten_alignment_in(&v));
+ a.kenten_character_set = e.prop("KentenCharacterSet");
+ // "Text Color" is the text's own colour; it resets an inherited swatch.
+ if let Some(r) = e.prop("KentenFillColor") {
+ a.kenten_fill = Some(if r.trim() == "Text Color" { String::new() } else { self.swatch_ref(r.trim()) });
+ }
+ if let Some(r) = e.prop("KentenStrokeColor") {
+ a.kenten_stroke = Some(if r.trim() == "Text Color" { String::new() } else { self.swatch_ref(r.trim()) });
+ }
+ // Tints and weight: -1 is the text's.
+ a.kenten_fill_tint = finite("KentenTint").map(|v| (v >= 0.0).then(|| (v.min(100.0) / 100.0) as f32));
+ a.kenten_stroke_tint = finite("KentenStrokeTint").map(|v| (v >= 0.0).then(|| (v.min(100.0) / 100.0) as f32));
+ a.kenten_stroke_weight = finite("KentenWeight").map(|v| (v >= 0.0).then_some(v));
+ a.kenten_overprint_fill = e.prop("KentenOverprintFill").and_then(|v| crate::cjk::overprint_in(&v));
+ a.kenten_overprint_stroke = e.prop("KentenOverprintStroke").and_then(|v| crate::cjk::overprint_in(&v));
+ a.shatai_magnification = finite("ShataiMagnification");
+ a.shatai_angle = finite("ShataiDegreeAngle").map(|v| v / crate::cjk::SHATAI_ANGLE_UNITS);
+ a.shatai_adjust_rotation = e.boolean("ShataiAdjustRotation");
+ a.shatai_adjust_tsume = e.boolean("ShataiAdjustTsume");
+ }
+}
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index 7b747587a..6dcaa0440 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -1399,3 +1399,69 @@ fn list_numbering_format_expression_and_bullet_import_and_round_trip() {
check(&d);
check(&import_idml(&export_idml(&d)).unwrap());
}
+
+#[test]
+fn kenten_shatai_and_grid_settings_import_and_round_trip() {
+ use designcraft_doc::cjk::CharacterAlignment;
+ use designcraft_doc::cjk_settings::{AdornmentOverprint, KentenAlignment, KentenKind, KentenPosition};
+ 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]" AutoTcy="3" AutoTcyIncludeRoman="true" RotateSingleByteCharacters="true" AllowArbitraryHyphenation="true" GridAlignment="AlignEmCenter" GridAlignFirstLineOnly="true" GridGyoudori="2" ParagraphGyoudori="true">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="KentenSmallBlackCircle" KentenFontSize="6" KentenXScale="80" KentenYScale="120" KentenPlacement="1.5" KentenPosition="BelowLeft" KentenAlignment="AlignKentenLeft" KentenCharacterSet="CharacterInput" KentenTint="50" KentenStrokeTint="-1" KentenWeight="0.5" KentenOverprintFill="OverprintOn" KentenOverprintStroke="Auto" ShataiMagnification="20" ShataiDegreeAngle="6000" ShataiAdjustRotation="true" ShataiAdjustTsume="false"><Properties><KentenFont type="string">$ID/</KentenFont><KentenFontStyle type="enumeration">Nothing</KentenFontStyle><KentenFillColor type="string">Text Color</KentenFillColor></Properties><Content>甲乙</Content></CharacterStyleRange>
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="Custom" KentenCustomCharacter="★"><Content>丙</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let doc = import_idml(&fixture_with_story(story)).unwrap();
+ let st = doc.stories.values().find(|s| s.text.contains("甲乙")).unwrap();
+ let runs: Vec<CharAttrs> = st.runs().map(|(_, f)| f.over.clone()).collect();
+ let a = &runs[0];
+ assert_eq!((a.kenten, a.kenten_kind, a.kenten_character.as_deref()), (Some(true), Some(KentenKind::SmallBlackCircle), Some("\u{2022}")));
+ assert_eq!((a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance), (Some(Some(6.0)), Some(0.8), Some(1.2), Some(1.5)));
+ assert_eq!((a.kenten_position, a.kenten_alignment), (Some(KentenPosition::BelowLeft), Some(KentenAlignment::Start)));
+ assert_eq!((a.kenten_font.as_deref(), a.kenten_font_style.as_deref(), a.kenten_fill.as_deref()), (Some(""), Some(""), Some("")));
+ assert_eq!((a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight), (Some(Some(0.5)), Some(None), Some(Some(0.5))));
+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (Some(AdornmentOverprint::On), Some(AdornmentOverprint::Auto)));
+ assert_eq!(a.kenten_character_set.as_deref(), Some("CharacterInput"));
+ assert_eq!(
+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),
+ (Some(20.0), Some(60.0), Some(true), Some(false))
+ );
+ let custom = runs.iter().find(|r| r.kenten_kind == Some(KentenKind::Custom)).unwrap();
+ assert_eq!(custom.kenten_character.as_deref(), Some("★"));
+ let p = &st.paras[0].para;
+ assert_eq!((p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break), (Some(3), Some(true), Some(true), Some(true)));
+ assert_eq!((p.grid_align, p.grid_reference), (Some(designcraft_doc::GridAlign::FirstLineOnly), Some(CharacterAlignment::EmCenter)));
+ assert_eq!((p.grid_gyoudori, p.paragraph_gyoudori), (Some(2), Some(true)));
+
+ let back = import_idml(&export_idml(&doc)).unwrap();
+ let st2 = back.stories.values().find(|s| s.text.contains("甲乙")).unwrap();
+ let runs2: Vec<CharAttrs> = st2.runs().map(|(_, f)| f.over.clone()).collect();
+ for (a, b) in runs.iter().zip(&runs2) {
+ assert_eq!((a.kenten, a.kenten_kind, &a.kenten_character), (b.kenten, b.kenten_kind, &b.kenten_character));
+ assert_eq!(
+ (a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance),
+ (b.kenten_size, b.kenten_x_scale, b.kenten_y_scale, b.kenten_distance)
+ );
+ assert_eq!(
+ (a.kenten_position, a.kenten_alignment, &a.kenten_character_set),
+ (b.kenten_position, b.kenten_alignment, &b.kenten_character_set)
+ );
+ assert_eq!((&a.kenten_font, &a.kenten_font_style, &a.kenten_fill), (&b.kenten_font, &b.kenten_font_style, &b.kenten_fill));
+ assert_eq!(
+ (a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight),
+ (b.kenten_fill_tint, b.kenten_stroke_tint, b.kenten_stroke_weight)
+ );
+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (b.kenten_overprint_fill, b.kenten_overprint_stroke));
+ assert_eq!(
+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),
+ (b.shatai_magnification, b.shatai_angle, b.shatai_adjust_rotation, b.shatai_adjust_tsume)
+ );
+ }
+ let p2 = &st2.paras[0].para;
+ assert_eq!(
+ (p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break),
+ (p2.auto_tcy, p2.auto_tcy_include_roman, p2.rotate_roman, p2.roman_word_break)
+ );
+ assert_eq!(
+ (p.grid_align, p.grid_reference, p.grid_gyoudori, p.paragraph_gyoudori),
+ (p2.grid_align, p2.grid_reference, p2.grid_gyoudori, p2.paragraph_gyoudori)
+ );
+}
diff --git a/crates/pdf/src/text.rs b/crates/pdf/src/text.rs
index bf59efded..97b90a828 100644
--- a/crates/pdf/src/text.rs
+++ b/crates/pdf/src/text.rs
@@ -151,10 +151,12 @@ impl Exporter<'_> {
continue;
}
// Vertical type: an upright glyph turns back a quarter about its em box centre.
- if ft.vertical
- && let Some(turn) = g.vertical_xf(l.baseline)
- {
- s.push_transform(&crate::export::tf(turn));
+ // Shatai slants each glyph about its own em box centre first.
+ let turn = if ft.vertical { g.vertical_xf(l.baseline) } else { None };
+ let shatai = cs.styles.get(g.style as usize).and_then(|st| st.shatai_xf(g, l.baseline));
+ if turn.is_some() || shatai.is_some() {
+ let m = turn.unwrap_or(Affine::IDENTITY) * shatai.unwrap_or(Affine::IDENTITY);
+ s.push_transform(&crate::export::tf(m));
self.tagged_run(s, cs, &gs[i..i + 1], l.baseline, story);
s.pop();
i += 1;
diff --git a/crates/render/src/text.rs b/crates/render/src/text.rs
index 734ec275e..cc031cb5a 100644
--- a/crates/render/src/text.rs
+++ b/crates/render/src/text.rs
@@ -136,6 +136,9 @@ fn build_line(db: &FontDb, cs: &ComposedStory, l: &Line, vertical: bool) -> Line
}
let skew = if style.skew != 0.0 { Affine::new([1.0, 0.0, -style.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
let mut a = Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
+ if let Some(shatai) = style.shatai_xf(g, l.baseline) {
+ a = shatai * a;
+ }
if vertical && let Some(turn) = g.vertical_xf(l.baseline) {
// Upright in vertical text.
a = turn * a;
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 34dd61442..02c7cf1dd 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -1144,7 +1144,8 @@ fn draw_inverse_highlight(
let outline = db.outline(&g.face, g.gid);
let skew =
if style.skew != 0.0 { Affine::new([1.0, 0.0, -style.skew.to_radians().tan(), 1.0, 0.0, 0.0]) } else { Affine::IDENTITY };
- let ga = Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
+ let shatai = style.shatai_xf(g, l.baseline).unwrap_or(Affine::IDENTITY);
+ let ga = shatai * Affine::translate((g.x, l.baseline + g.y)) * skew * Affine::scale_non_uniform(g.sx, g.sy);
rc.set_transform(view * *m * ga);
rc.fill_path(&outline);
}