Skip to content

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

CJK-MOJI2: apply Mojikumi spacing and kinsoku priorities during composition

Shao Wenbinc66d502c7924
diff --git a/ROADMAP.md b/ROADMAP.md
index 2531871ea..77cfe7fd3 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,5 +1,7 @@
# DesignCraft roadmap
+- CJK-MOJI2: share Mojikumi pair and line-edge metrics between breaking and placement; honor spacing bounds, compression priorities, explicit aki and kinsoku policies.
+
- CJK-MOJI1: resolve Chinese and half-em Mojikumi presets and directional custom overrides; preserve IDML table references independently of display names.
- FONT7: replacement recommendations check the characters actually used; placeholder LastResort fonts and glyph-zero mappings cannot masquerade as glyph coverage or suppress missing-glyph diagnostics.
diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs
index 3b08e1050..8aec5df04 100644
--- a/crates/compose/src/breaker.rs
+++ b/crates/compose/src/breaker.rs
@@ -50,6 +50,8 @@ pub struct Spacing {
pub optical: bool,
/// Korean text breaks between syllables instead of at spaces.
pub korean_char_breaks: bool,
+ /// 0: minimum adjustment; 1: push in; 2: push out first; 3: push out only.
+ pub kinsoku_priority: u8,
}
impl Default for Spacing {
@@ -71,6 +73,7 @@ impl Default for Spacing {
hyph_zone: 0.0,
optical: false,
korean_char_breaks: false,
+ kinsoku_priority: 0,
}
}
}
@@ -78,13 +81,18 @@ impl Default for Spacing {
impl Spacing {
/// Per-tier (word, letter, glyph) stretch and shrink of glyph `g` as a box.
fn box_elastic(&self, g: &Glyph) -> ([f64; 3], [f64; 3]) {
- if !self.justify || g.locked_advance {
+ if g.locked_advance {
return ([0.0; 3], [0.0; 3]);
}
+ let moji_stretch = if self.justify { g.moji.stretch } else { 0.0 };
+ let moji_shrink = if self.kinsoku_priority == 3 { 0.0 } else { g.moji.shrink };
+ if !self.justify {
+ return ([0.0; 3], [moji_shrink, 0.0, 0.0]);
+ }
let natural = g.adv / self.glyph_desired.max(0.01);
(
- [0.0, g.space * (self.letter_max - self.letter_desired).max(0.0), natural * (self.glyph_max - self.glyph_desired).max(0.0)],
- [0.0, g.space * (self.letter_desired - self.letter_min).max(0.0), natural * (self.glyph_desired - self.glyph_min).max(0.0)],
+ [moji_stretch, g.space * (self.letter_max - self.letter_desired).max(0.0), natural * (self.glyph_max - self.glyph_desired).max(0.0)],
+ [moji_shrink, g.space * (self.letter_desired - self.letter_min).max(0.0), natural * (self.glyph_desired - self.glyph_min).max(0.0)],
)
}
/// Word-space stretch and shrink of space glyph `g` (only U+0020 is elastic).
@@ -146,6 +154,8 @@ struct Item {
auto: bool,
/// Breaks: optical hang of the glyph ending the line. Boxes: hang of the glyph starting one.
hang: f64,
+ edge_elastic: [f64; 2],
+ start_elastic: [f64; 2],
/// Auto hyphenation points: index of the break opportunity before the word (or `NONE`).
zone_from: usize,
}
@@ -154,13 +164,49 @@ const NONE: usize = usize::MAX;
impl Item {
fn boxed(w: f64, st: [f64; 3], sh: [f64; 3]) -> Item {
- Item { kind: Kind::Box, w, st, sh, p: 0.0, flagged: false, auto: false, hang: 0.0, zone_from: NONE }
+ Item {
+ kind: Kind::Box,
+ w,
+ st,
+ sh,
+ p: 0.0,
+ flagged: false,
+ auto: false,
+ hang: 0.0,
+ edge_elastic: [0.0; 2],
+ start_elastic: [0.0; 2],
+ zone_from: NONE,
+ }
}
fn glue(w: f64, st: f64, sh: f64) -> Item {
- Item { kind: Kind::Glue, w, st: [st, 0.0, 0.0], sh: [sh, 0.0, 0.0], p: 0.0, flagged: false, auto: false, hang: 0.0, zone_from: NONE }
+ Item {
+ kind: Kind::Glue,
+ w,
+ st: [st, 0.0, 0.0],
+ sh: [sh, 0.0, 0.0],
+ p: 0.0,
+ flagged: false,
+ auto: false,
+ hang: 0.0,
+ edge_elastic: [0.0; 2],
+ start_elastic: [0.0; 2],
+ zone_from: NONE,
+ }
}
fn penalty(w: f64, p: f64, flagged: bool) -> Item {
- Item { kind: Kind::Penalty, w, st: [0.0; 3], sh: [0.0; 3], p, flagged, auto: false, hang: 0.0, zone_from: NONE }
+ Item {
+ kind: Kind::Penalty,
+ w,
+ st: [0.0; 3],
+ sh: [0.0; 3],
+ p,
+ flagged,
+ auto: false,
+ hang: 0.0,
+ edge_elastic: [0.0; 2],
+ start_elastic: [0.0; 2],
+ zone_from: NONE,
+ }
}
}
@@ -235,7 +281,7 @@ fn hang_left(g: &Glyph) -> f64 {
}
fn right_hang(g: &Glyph, sp: &Spacing) -> f64 {
- g.cjk_hang.max(if sp.optical { hang_right(g) } else { 0.0 })
+ g.cjk_hang.max(if sp.optical { hang_right(g) } else { 0.0 }) - g.moji.end
}
fn hang_right(g: &Glyph) -> f64 {
@@ -287,6 +333,9 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> (Vec<Item>, Vec
ig.push(i);
let mut p = Item::penalty(0.0, -INF, false);
p.hang = prev_hang;
+ if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) {
+ p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3);
+ }
it.push(p);
ig.push(i + 1);
last_space = NONE;
@@ -298,6 +347,9 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> (Vec<Item>, Vec
let (st, sh) = sp.space_elastic(g);
let mut gl = Item::glue(w, st, sh);
gl.hang = prev_hang;
+ if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) {
+ gl.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3);
+ }
last_space = it.len();
it.push(gl);
ig.push(i);
@@ -307,6 +359,9 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> (Vec<Item>, Vec
ig.push(i);
let mut p = Item::penalty(0.0, 0.0, false);
p.hang = prev_hang;
+ if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) {
+ p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3);
+ }
last_space = it.len();
it.push(p);
ig.push(i);
@@ -328,9 +383,8 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> (Vec<Item>, Vec
}
let (st, sh) = sp.box_elastic(g);
let mut bx = Item::boxed(g.adv, st, sh);
- if sp.optical {
- bx.hang = hang_left(g);
- }
+ bx.hang = (if sp.optical { hang_left(g) } else { 0.0 }) - g.moji.start;
+ bx.start_elastic = crate::mojikumi::start_elastic(g, sp.justify, sp.kinsoku_priority != 3);
it.push(bx);
ig.push(i);
let next_is_space = glyphs.get(i + 1).is_none_or(|n| n.is_space());
@@ -338,10 +392,12 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> (Vec<Item>, Vec
if matches!(g.ch, '-' | '\u{2010}') {
let mut p = Item::penalty(0.0, 50.0, true);
p.hang = right_hang(g, sp);
+ p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3);
push_inword(&mut it, &mut ig, p, i + 1, sp);
} else if matches!(g.ch, '\u{2013}' | '\u{2014}' | '/') || g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp)) {
let mut p = Item::penalty(0.0, 0.0, false);
p.hang = right_hang(g, sp);
+ p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3);
push_inword(&mut it, &mut ig, p, i + 1, sp);
} else if hyph_after[i] {
let hw = hyphen_width(g, &mut hy_cache);
@@ -360,6 +416,9 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing) -> (Vec<Item>, Vec
ig.push(n);
let mut p = Item::penalty(0.0, -INF, false);
p.hang = if n > 0 { right_hang(&glyphs[n - 1], sp) } else { 0.0 };
+ if let Some(g) = glyphs.last() {
+ p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3);
+ }
it.push(p);
ig.push(n);
(it, ig)
@@ -422,9 +481,21 @@ fn kp_pass(
sz[i + 1][t] = sz[i][t] + z[t];
}
}
- let first_hang = items.iter().find(|i| i.kind == Kind::Box).map_or(0.0, |b| b.hang);
- let mut arena: Vec<Node> =
- vec![Node { pos: 0, line: 0, fitness: 1, tw: first_hang, ty: [0.0; 3], tz: [0.0; 3], demerits: 0.0, prev: None, hyphens: 0, flagged: false }];
+ let first_box = items.iter().find(|i| i.kind == Kind::Box);
+ let first_hang = first_box.map_or(0.0, |b| b.hang);
+ let first_elastic = first_box.map_or([0.0; 2], |b| b.start_elastic);
+ let mut arena: Vec<Node> = vec![Node {
+ pos: 0,
+ line: 0,
+ fitness: 1,
+ tw: first_hang,
+ ty: [-first_elastic[0], 0.0, 0.0],
+ tz: [-first_elastic[1], 0.0, 0.0],
+ demerits: 0.0,
+ prev: None,
+ hyphens: 0,
+ flagged: false,
+ }];
let limit = sp.hyphen_limit as usize;
let states = if limit == 0 { 2 } else { (limit + 1).min(MAX_HYPHEN_STATES) };
let mut active: Vec<usize> = vec![0];
@@ -454,6 +525,8 @@ fn kp_pass(
y[t] = sy[b][t] - n.ty[t];
z[t] = sz[b][t] - n.tz[t];
}
+ y[0] = (y[0] + it.edge_elastic[0]).max(0.0);
+ z[0] = (z[0] + it.edge_elastic[1]).max(0.0);
let (r, feasible) = tiered_ratio(target - l, y, z);
if feasible && !forced {
keep.push(a);
@@ -477,7 +550,12 @@ fn kp_pass(
}
}
}
- let bad = 100.0 * r.abs().powi(3);
+ let preference = match sp.kinsoku_priority {
+ 1 if r > 0.0 => 4.0,
+ 2 if r < 0.0 => 4.0,
+ _ => 1.0,
+ };
+ let bad = preference * 100.0 * r.abs().powi(3);
let lp = 10.0 + bad;
let mut d = if pp >= 0.0 {
lp * lp + pp * pp
@@ -531,6 +609,8 @@ fn kp_pass(
match x.kind {
Kind::Box => {
tw += x.hang;
+ ty[0] -= x.start_elastic[0];
+ tz[0] -= x.start_elastic[1];
break;
}
Kind::Glue => {
@@ -641,8 +721,9 @@ pub fn greedy(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn F
let may_hyphenate = |hyphens: u32| sp.hyphen_limit == 0 || hyphens < sp.hyphen_limit;
while start < n {
let w = width(line).max(1.0);
- let mut x = if sp.optical { -hang_left(&glyphs[start]) } else { 0.0 };
- let mut shrink = 0.0;
+ let mut x = (if sp.optical { -hang_left(&glyphs[start]) } else { 0.0 }) + glyphs[start].moji.start;
+ let mut shrink = crate::mojikumi::start_elastic(&glyphs[start], sp.justify, sp.kinsoku_priority != 3)[1];
+ let mut last_natural: Option<(usize, bool)> = None;
let mut last_ok: Option<(usize, bool)> = None; // (break position = end glyph, hyphen)
let mut last_space: Option<(usize, f64)> = None; // (break position, line width there)
let mut i = start;
@@ -658,13 +739,25 @@ pub fn greedy(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn F
shrink += sp.space_elastic(g).1;
}
last_ok = Some((i, false));
+ if x <= w {
+ last_natural = last_ok;
+ }
last_space = Some((i, x));
x += g.adv;
i += 1;
continue;
}
let hang_r = right_hang(g, sp);
- if x + g.adv - hang_r > w + shrink
+ let end_shrink = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3)[1];
+ let available = shrink + sp.box_elastic(g).1.iter().sum::<f64>() + end_shrink;
+ if sp.kinsoku_priority == 2
+ && x + g.adv - hang_r > w
+ && let Some((end, hyphen)) = last_natural
+ {
+ brk = Some((end, hyphen, false));
+ break;
+ }
+ if x + g.adv - hang_r > w + available.max(0.0)
&& i > start
&& (last_ok.is_some() || glyphs.get(i - 1).is_none_or(|p| p.break_after != Some(false) && !p.no_break))
{
@@ -680,14 +773,15 @@ pub fn greedy(glyphs: &[Glyph], hyph_after: &[bool], sp: &Spacing, width: &dyn F
break;
}
x += g.adv;
- if sp.justify {
- shrink += sp.box_elastic(g).1.iter().sum::<f64>();
- }
+ shrink += sp.box_elastic(g).1.iter().sum::<f64>();
if i + 1 < n && !glyphs[i + 1].is_space() && !g.no_break && g.break_after != Some(false) {
if matches!(g.ch, '-' | '\u{2010}' | '\u{2013}' | '\u{2014}' | '/')
|| g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp))
{
last_ok = Some((i + 1, false));
+ if x - hang_r <= w {
+ last_natural = last_ok;
+ }
} else if hyph_after[i] && may_hyphenate(hyphens) {
let hy = hyphen_width(g, &mut hy_cache) * if sp.optical { 1.0 - hang('-').1 } else { 1.0 };
if x + hy <= w + shrink {
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index 1ad7d0130..947ec97f6 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -14,6 +14,7 @@ mod bidi;
pub mod breaker;
mod cache;
pub mod hyphen;
+mod mojikumi;
mod notes;
mod overlay;
mod ruby;
@@ -616,6 +617,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
// The same spacing, hyphenation and breaker as the layout below.
let mut gl = sp.glyphs.clone();
apply_desired_spacing(&mut gl, &pp);
+ mojikumi::apply(&mut gl, &doc.styles, &pp.mojikumi);
let hy = hyphenation_points(&story.text, &gl, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars));
let breaks = if pp.composer == Composer::SingleLine || gl.iter().any(|g| g.ch == '\t') || gl.len() > 4000 {
breaker::greedy(&gl, &hy, &spacing, &width)
@@ -692,6 +694,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C
);
bidi::resolve_mirroring(&mut glyphs, &bidi_info);
apply_desired_spacing(&mut glyphs, &pp);
+ mojikumi::apply(&mut glyphs, &doc.styles, &pp.mojikumi);
let hyph_after = hyphenation_points(&story.text, &glyphs, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars));
let base_size = base_chars.size;
let base_leading = match base_chars.leading {
@@ -1166,6 +1169,12 @@ fn spacing_for(pp: &ParaProps, base_size: f64) -> Spacing {
hyph_zone: if pp.align.is_justified() { 0.0 } else { pp.hyph_zone },
optical: pp.optical_margin,
korean_char_breaks: pp.korean_char_breaks,
+ kinsoku_priority: match pp.kinsoku_type.as_str() {
+ "KinsokuPushInFirst" => 1,
+ "KinsokuPushOutFirst" => 2,
+ "KinsokuPushOutOnly" => 3,
+ _ => 0,
+ },
}
}
@@ -1568,6 +1577,7 @@ fn layout_line(
bidi_info: &unicode_bidi::BidiInfo<'_>,
) -> (Vec<PlacedGlyph>, f64, f64) {
let mut line: Vec<Glyph> = glyphs[s..e.max(s)].to_vec();
+ mojikumi::edges(&mut line);
let reference = line.iter().max_by(|a, b| a.size.total_cmp(&b.size)).cloned();
if let Some(reference) = reference {
for g in &mut line {
@@ -1658,7 +1668,7 @@ fn layout_line(
};
let justify_this = align.is_justified() && (!last || align == Align::FullyJustified || forced_mid) && !has_tab;
// A justified paragraph's last line may have been composed with shrunk spaces: shrink it too.
- let squeeze_last = align.is_justified() && !justify_this && !has_tab && extra < 0.0 && !spaces.is_empty();
+ let squeeze_last = !justify_this && !has_tab && extra < 0.0 && (align.is_justified() || line.iter().any(|g| g.moji.shrink > 0.0));
// Extra advance per glyph (word spaces and letter gaps) and horizontal scale per glyph.
let mut add = vec![0.0; line.len()];
let mut scale = vec![1.0; line.len()];
@@ -1677,6 +1687,9 @@ fn layout_line(
}
}
}
+ if (justify_this || squeeze_last) && (extra >= 0.0 || sp.kinsoku_priority != 3) {
+ extra = mojikumi::distribute(&mut line, extra, &mut add);
+ }
if (justify_this || squeeze_last) && !spaces.is_empty() {
distribute(&line, &spaces, extra, sp, &mut add, &mut scale);
} else if justify_this && spaces.is_empty() && line.len() > 1 && !last {
@@ -1687,13 +1700,13 @@ fn layout_line(
.iter()
.enumerate()
.take(line.len() - 1)
- .filter(|(_, g)| !g.locked_advance || g.break_after != Some(false))
+ .filter(|(_, g)| !g.moji.active && (!g.locked_advance || g.break_after != Some(false)))
.map(|(i, _)| i)
.collect();
if !gaps.is_empty() {
let per = extra / gaps.len() as f64;
for i in gaps {
- add[i] = per;
+ add[i] += per;
}
}
}
diff --git a/crates/compose/src/mojikumi.rs b/crates/compose/src/mojikumi.rs
new file mode 100644
index 000000000..339b60856
--- /dev/null
+++ b/crates/compose/src/mojikumi.rs
@@ -0,0 +1,178 @@
+//! Mojikumi boundary widths. The same values feed line selection and placement.
+use crate::shape::Glyph;
+use designcraft_doc::{
+ Styles,
+ mojikumi::{self as rules, Aki, Rules},
+};
+
+#[derive(Clone, Copy, Debug, Default)]
+pub struct Metrics {
+ pub active: bool,
+ /// Desired internal gap attached to this glyph's advance.
+ pub gap: f64,
+ pub stretch: f64,
+ pub shrink: f64,
+ pub priority: u8,
+ pub discrete: bool,
+ /// Width changes when this glyph starts / ends a line.
+ pub start: f64,
+ pub end: f64,
+ pub end_aki: Aki,
+ pub start_aki: Aki,
+ pub at_start: bool,
+ pub explicit_before: bool,
+ pub explicit_after: bool,
+}
+
+fn eligible(g: &Glyph) -> bool {
+ g.adv > 0.0
+ && !g.locked_advance
+ && !g.ch.is_control()
+ && (!g.ch.is_whitespace() || g.ch == '\u{3000}')
+ && !matches!(g.ch, '\u{e000}'..='\u{e1ff}')
+}
+fn em(g: &Glyph) -> f64 {
+ // Actual scaled em, including vertical and composite-font scaling.
+ g.face.units_per_em() * if g.upright { g.sy } else { g.sx }
+}
+
+pub fn apply(glyphs: &mut [Glyph], styles: &Styles, name: &str) {
+ let Ok(Some(table)) = Rules::resolve(styles, name) else { return };
+ // Remove punctuation's built-in blank half-body. The table then contributes
+ // the desired spacing once per boundary, rather than adding it twice.
+ for g in glyphs.iter_mut().filter(|g| eligible(g)) {
+ g.moji.active = true;
+ let class = rules::class(g.rendered_char);
+ let unit = em(g);
+ if g.adv >= unit * 0.8 {
+ let before = if g.moji.explicit_before { 0.0 } else { rules::leading(class) * unit };
+ let after = if g.moji.explicit_after { 0.0 } else { rules::trailing(class) * unit };
+ g.adv = (g.adv - before - after).max(0.0);
+ g.dx -= before;
+ }
+ }
+ for i in 0..glyphs.len() {
+ let (left, right) = glyphs.split_at_mut(i + 1);
+ let Some(g) = left.last_mut() else { continue };
+ if !g.moji.active {
+ continue;
+ }
+ let c = rules::class(g.rendered_char);
+ let unit = em(g);
+ let start = table.pair(if i == 0 { 23 } else { 22 }, c);
+ g.moji.start_aki = start;
+ g.moji.start = if g.moji.explicit_before { 0.0 } else { start.desired * unit };
+ g.moji.end_aki = table.pair(c, 22);
+ let mut gap = Aki::default();
+ if let Some(next) = right.first().filter(|n| n.moji.active && n.byte != g.byte)
+ && !g.moji.explicit_after
+ && !next.moji.explicit_before
+ {
+ gap = table.pair(c, rules::class(next.rendered_char));
+ }
+ let desired = (gap.desired * unit).max(-g.adv);
+ g.moji.gap = desired;
+ g.moji.stretch = (gap.max * unit - desired).max(0.0);
+ g.moji.shrink = (desired - gap.min * unit).max(0.0).min(g.adv + desired);
+ g.moji.priority = gap.priority;
+ g.moji.discrete = gap.discrete;
+ g.moji.end = if g.moji.explicit_after { 0.0 } else { g.moji.end_aki.desired * unit } - desired;
+ g.adv += desired;
+ }
+}
+
+pub fn edges(line: &mut [Glyph]) {
+ if let Some(g) = line.first_mut() {
+ g.moji.at_start = true;
+ g.adv += g.moji.start;
+ g.dx += g.moji.start;
+ }
+ if let Some(g) = line.iter_mut().rev().find(|g| !crate::breaker::is_forced(g.ch)) {
+ g.adv += g.moji.end;
+ // A line-end gap is not the internal gap that happened to follow it.
+ let unit = em(g);
+ let aki = g.moji.end_aki;
+ g.moji.stretch = if g.moji.explicit_after { 0.0 } else { (aki.max - aki.desired).max(0.0) * unit };
+ g.moji.shrink = if g.moji.explicit_after { 0.0 } else { (aki.desired - aki.min).max(0.0) * unit };
+ g.moji.priority = aki.priority;
+ g.moji.discrete = aki.discrete;
+ }
+}
+
+/// Consume spacing in priority order; discrete rules use an entire endpoint.
+/// Returns the residual for ordinary word/letter/glyph justification.
+pub fn distribute(line: &mut [Glyph], extra: f64, add: &mut [f64]) -> f64 {
+ let mut rem = extra.abs();
+ let sign = extra.signum();
+ for priority in 0..=10 {
+ // Start and following gaps share the same priority queue. Moving a
+ // leading gap also moves the glyph outline, not just the next glyph.
+ for before in [true, false] {
+ let properties = |g: &Glyph| {
+ if before {
+ let a = g.moji.start_aki;
+ let cap = if !g.moji.at_start || g.moji.explicit_before {
+ 0.0
+ } else if sign < 0.0 {
+ (a.desired - a.min).max(0.0) * em(g)
+ } else {
+ (a.max - a.desired).max(0.0) * em(g)
+ };
+ (a.priority, a.discrete, cap)
+ } else {
+ (g.moji.priority, g.moji.discrete, if sign < 0.0 { g.moji.shrink } else { g.moji.stretch })
+ }
+ };
+ for (g, a) in line.iter_mut().zip(add.iter_mut()) {
+ let (p, discrete, cap) = properties(g);
+ if p == priority && discrete && cap <= rem + 1e-9 {
+ *a += sign * cap;
+ if before {
+ g.dx += sign * cap;
+ }
+ rem = (rem - cap).max(0.0);
+ }
+ }
+ let total: f64 = line
+ .iter()
+ .map(|g| {
+ let (p, discrete, cap) = properties(g);
+ if p == priority && !discrete { cap } else { 0.0 }
+ })
+ .sum();
+ if total > 0.0 {
+ let take = rem.min(total);
+ for (g, a) in line.iter_mut().zip(add.iter_mut()) {
+ let (p, discrete, cap) = properties(g);
+ if p == priority && !discrete {
+ let amount = sign * take * cap / total;
+ *a += amount;
+ if before {
+ g.dx += amount;
+ }
+ }
+ }
+ rem -= take;
+ }
+ }
+ }
+ sign * rem
+}
+
+/// Replace the final internal gap's elasticity by its line-end elasticity.
+pub fn end_elastic(g: &Glyph, justify: bool, shrink: bool) -> [f64; 2] {
+ let unit = em(g);
+ let a = g.moji.end_aki;
+ [
+ if justify { (if g.moji.explicit_after { 0.0 } else { (a.max - a.desired).max(0.0) * unit }) - g.moji.stretch } else { 0.0 },
+ if shrink { (if g.moji.explicit_after { 0.0 } else { (a.desired - a.min).max(0.0) * unit }) - g.moji.shrink } else { 0.0 },
+ ]
+}
+
+pub fn start_elastic(g: &Glyph, justify: bool, shrink: bool) -> [f64; 2] {
+ let a = g.moji.start_aki;
+ if g.moji.explicit_before {
+ return [0.0; 2];
+ }
+ [if justify { (a.max - a.desired).max(0.0) * em(g) } else { 0.0 }, if shrink { (a.desired - a.min).max(0.0) * em(g) } else { 0.0 }]
+}
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index e698d76ab..9391f3a19 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -49,6 +49,7 @@ pub struct Glyph {
/// Resolved CJK boundary constraint, independent of glyph outlines.
pub break_after: Option<bool>,
pub cjk_hang: f64,
+ pub moji: crate::mojikumi::Metrics,
pub ideographic_space_elastic: bool,
pub character_alignment: designcraft_doc::cjk::CharacterAlignment,
pub leading_model: designcraft_doc::cjk::LeadingModel,
@@ -803,6 +804,7 @@ fn control_glyph(face: &Arc<FontFace>, p: &CharProps, auto_leading: TypeEnv, sty
space: face.advance(face.glyph_for(' ')) * k * p.h_scale,
break_after: None,
cjk_hang: 0.0,
+ moji: crate::mojikumi::Metrics { explicit_before: p.leading_aki.is_some(), explicit_after: p.trailing_aki.is_some(), ..Default::default() },
ideographic_space_elastic: false,
character_alignment: p.character_alignment,
leading_model: p.leading_model,
@@ -947,6 +949,11 @@ fn shape_segment(
space,
break_after: None,
cjk_hang: 0.0,
+ moji: crate::mojikumi::Metrics {
+ explicit_before: p.leading_aki.is_some(),
+ explicit_after: p.trailing_aki.is_some(),
+ ..Default::default()
+ },
ideographic_space_elastic: false,
character_alignment: p.character_alignment,
leading_model: p.leading_model,
@@ -994,5 +1001,7 @@ pub(crate) fn hyphen_after(g: &Glyph) -> Glyph {
h.byte = g.byte + g.len;
h.len = 0;
h.ch = '-';
+ h.rendered_char = '-';
+ h.moji = Default::default();
h
}
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 417adc61d..b9589b060 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -2014,3 +2014,217 @@ fn generated_note_labels_use_coverage_fallback() {
assert_ne!(glyph.gid, 0);
assert_eq!(glyph.face.family, "Generated Label Coverage");
}
+
+#[test]
+fn mojikumi_custom_pairs_change_positions_and_breaks_without_font_scaling() {
+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};
+ let (mut d, sid, _) = doc_with(
+ "A1A1A1",
+ Rect::new(0.0, 0.0, 55.0, 300.0),
+ ParaAttrs { hyphenate: Some(false), composer: Some(Composer::SingleLine), ..Default::default() },
+ );
+ let before = compose_story(&d, sid, &ComposeOptions::default());
+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {
+ name: "Synthetic".into(),
+ based_on: "SimpChineseDefault".into(),
+ overrides: vec![
+ MojikumiAki { target_class: 18, side_class: 25, after: true, minimum: 1.0, desired: 1.0, maximum: 1.0, ..Default::default() },
+ MojikumiAki { target_class: 25, side_class: 18, after: true, minimum: 1.0, desired: 1.0, maximum: 1.0, ..Default::default() },
+ ],
+ });
+ d.story_mut(sid).unwrap().paras[0].para.mojikumi = Some("MojikumiTable/Synthetic".into());
+ let after = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(all_lines(&after).len() > all_lines(&before).len());
+ let a = &all_lines(&after)[0].glyphs;
+ let b = &all_lines(&before)[0].glyphs;
+ assert!((a[1].x - b[1].x - 12.0).abs() < 0.001);
+ assert_eq!(a[0].sx, b[0].sx);
+ assert!(all_lines(&after).iter().all(|l| l.end_x <= l.x1 + 0.01));
+}
+
+#[test]
+fn mojikumi_paragraph_indent_adds_to_paragraph_settings_and_rounds_no_glyphs() {
+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};
+ let (mut d, sid, _) = doc_with(
+ "ABC",
+ Rect::new(0.0, 0.0, 200.0, 100.0),
+ ParaAttrs { first_line_indent: Some(7.0), mojikumi: Some("MojikumiTable/Indent".into()), ..Default::default() },
+ );
+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {
+ name: "Indent".into(),
+ based_on: "SimpChineseDefault".into(),
+ overrides: vec![MojikumiAki {
+ target_class: 18,
+ side_class: 23,
+ after: false,
+ minimum: 2.0,
+ desired: 2.0,
+ maximum: 2.0,
+ ..Default::default()
+ }],
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let line = all_lines(&cs)[0];
+ assert!((line.glyphs[0].x - 31.0).abs() < 0.001, "{}", line.glyphs[0].x);
+ assert_eq!(line.glyphs.len(), 3);
+}
+
+#[test]
+fn mojikumi_justifies_cjk_without_spaces_and_respects_fixed_spacing() {
+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};
+ let (mut d, sid, _) = doc_with(
+ "A1A1",
+ Rect::new(0.0, 0.0, 100.0, 100.0),
+ ParaAttrs { align: Some(Align::FullyJustified), mojikumi: Some("MojikumiTable/Elastic".into()), ..Default::default() },
+ );
+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {
+ name: "Elastic".into(),
+ based_on: "SimpChineseDefault".into(),
+ overrides: vec![MojikumiAki {
+ target_class: 18,
+ side_class: 25,
+ after: true,
+ minimum: 0.0,
+ desired: 0.0,
+ maximum: 5.0,
+ priority: 1,
+ ..Default::default()
+ }],
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!((all_lines(&cs)[0].end_x - 100.0).abs() < 0.001, "{}", all_lines(&cs)[0].end_x);
+}
+
+#[test]
+fn mojikumi_fixed_pairs_are_not_stretched_by_single_word_justification() {
+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};
+ let (mut d, sid, _) = doc_with(
+ "A1A1",
+ Rect::new(0.0, 0.0, 150.0, 100.0),
+ ParaAttrs { align: Some(Align::FullyJustified), mojikumi: Some("MojikumiTable/Fixed".into()), ..Default::default() },
+ );
+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {
+ name: "Fixed".into(),
+ based_on: "SimpChineseDefault".into(),
+ overrides: [(18, 25), (25, 18)]
+ .into_iter()
+ .map(|(target_class, side_class)| MojikumiAki {
+ target_class,
+ side_class,
+ after: true,
+ minimum: 0.25,
+ desired: 0.25,
+ maximum: 0.25,
+ ..Default::default()
+ })
+ .collect(),
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let line = all_lines(&cs)[0];
+ assert!(line.end_x < 100.0, "Fixed spacing was stretched: {}", line.end_x);
+ d.story_mut(sid).unwrap().paras[0].para.align = Some(Align::Left);
+ let ragged = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(line.end_x, all_lines(&ragged)[0].end_x);
+}
+
+#[test]
+fn mojikumi_kinsoku_push_in_and_push_out_select_different_legal_breaks() {
+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};
+ let text = "甲乙丙丁戊己庚辛";
+ let (mut d, sid, _) = doc_with(
+ text,
+ Rect::new(0.0, 0.0, 45.0, 300.0),
+ ParaAttrs {
+ composer: Some(Composer::SingleLine),
+ mojikumi: Some("MojikumiTable/Compress".into()),
+ kinsoku_type: Some("KinsokuPushInFirst".into()),
+ ..Default::default()
+ },
+ );
+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {
+ name: "Compress".into(),
+ based_on: "SimpChineseDefault".into(),
+ overrides: vec![MojikumiAki {
+ target_class: 12,
+ side_class: 12,
+ after: true,
+ minimum: 0.0,
+ desired: 1.0,
+ maximum: 1.0,
+ priority: 1,
+ ..Default::default()
+ }],
+ });
+ let inside = compose_story(&d, sid, &ComposeOptions::default());
+ d.story_mut(sid).unwrap().paras[0].para.kinsoku_type = Some("KinsokuPushOutFirst".into());
+ let outside = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(all_lines(&inside)[0].range.end > all_lines(&outside)[0].range.end);
+ for cs in [&inside, &outside] {
+ assert!(all_lines(cs).iter().all(|l| l.end_x <= l.x1 + 0.01));
+ }
+}
+
+#[test]
+fn mojikumi_priority_and_elastic_line_start_are_used_in_placement() {
+ use designcraft_doc::cjk::{MojikumiAki, MojikumiTable};
+ let (mut d, sid, _) = doc_with("A1B2", Rect::new(0.0, 0.0, 45.0, 100.0), ParaAttrs::default());
+ let natural = compose_story(&d, sid, &ComposeOptions::default());
+ let middle_gap = all_lines(&natural)[0].glyphs[2].x - all_lines(&natural)[0].glyphs[1].x;
+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {
+ name: "Priority".into(),
+ based_on: "SimpChineseDefault".into(),
+ overrides: vec![
+ MojikumiAki {
+ target_class: 18,
+ side_class: 25,
+ after: true,
+ minimum: 0.0,
+ desired: 0.0,
+ maximum: 10.0,
+ priority: 1,
+ ..Default::default()
+ },
+ MojikumiAki {
+ target_class: 25,
+ side_class: 18,
+ after: true,
+ minimum: 0.0,
+ desired: 0.0,
+ maximum: 10.0,
+ priority: 2,
+ ..Default::default()
+ },
+ ],
+ });
+ let para = &mut d.story_mut(sid).unwrap().paras[0].para;
+ para.mojikumi = Some("MojikumiTable/Priority".into());
+ para.align = Some(Align::FullyJustified);
+ let result = compose_story(&d, sid, &ComposeOptions::default());
+ let line = all_lines(&result)[0];
+ assert!((line.end_x - 45.0).abs() < 0.001);
+ assert!((line.glyphs[2].x - line.glyphs[1].x - middle_gap).abs() < 0.001, "Priority 2 was used before priority 1 was exhausted");
+
+ let (mut d, sid, _) = doc_with(
+ "A",
+ Rect::new(0.0, 0.0, 30.0, 100.0),
+ ParaAttrs { mojikumi: Some("MojikumiTable/Start".into()), align: Some(Align::FullyJustified), ..Default::default() },
+ );
+ Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable {
+ name: "Start".into(),
+ based_on: "SimpChineseDefault".into(),
+ overrides: vec![MojikumiAki {
+ target_class: 18,
+ side_class: 23,
+ after: false,
+ minimum: 0.0,
+ desired: 0.0,
+ maximum: 5.0,
+ priority: 1,
+ ..Default::default()
+ }],
+ });
+ let result = compose_story(&d, sid, &ComposeOptions::default());
+ let line = all_lines(&result)[0];
+ assert!((line.end_x - 30.0).abs() < 0.001);
+ assert!(line.glyphs[0].x > 10.0, "Leading gap must move the first outline too");
+}