Skip to content

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

Merge feat/cjk-typography-ui: ruby, kenten, shatai, auto tate-chu-yoko, rotate roman, roman word break, grid references and the CJK style dialog panes

aiongg0f6f96ae6d31
diff --cc ROADMAP.md
index 8dcca99f3,cec5429e4..4ae32831b
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -24,10 -5,7 +24,10 @@@
- AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it.
- AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md.
+- FONT3: opening documents with unavailable font families or styles automatically offers Find/Replace Font. The dialog supports repeated replacements, refreshed inventory and visible validation errors; native builds without craft-fonts use system CJK fonts for readable names.
+- FONT2: font replacements validate available targets and resolve inherited formatting in nested text and empty paragraphs, with undo and composite component preservation.
+- FONT1: composite-font references resolve by resource identity, retain literal display names, and export as object references. Font inventory and preflight share the character-selected component fonts, including nested notes and cells.
- - CJK1: IDML composite fonts now retain character mappings and metrics; explicit aki, tsume, jidori, em alignment/leading, named/custom kinsoku boundaries, hanging punctuation, tate-chu-yoko offsets and kenten symbols flow through composition and IDML export. Automatic kerning no longer imports inactive numeric values as enormous manual spacing. Composite definitions are editable through commands with undo/cache invalidation. Mojikumi definitions are retained and unsupported spacing-table / push-in-push-out policies are reported by preflight. Full InDesign CJK composition parity, frame-grid layout and detailed ruby remain unfinished. Warichu sets the selected run in smaller lines inside the line after the line is broken.
+ - CJK1: IDML composite fonts now retain character mappings and metrics; explicit aki, tsume, jidori, em alignment/leading, named/custom kinsoku boundaries, hanging punctuation, tate-chu-yoko offsets and kenten symbols flow through composition and IDML export. Automatic kerning no longer imports inactive numeric values as enormous manual spacing. Composite definitions are editable through commands with undo/cache invalidation. Mojikumi definitions are retained and unsupported spacing-table / push-in-push-out policies are reported by preflight. Kenten settings (kind, custom mark and font, size, scale, distance, position, alignment, colour), shatai, auto tate-chu-yoko, rotate roman, roman word break and grid alignment references with gyoudori and paragraph gyoudori are composed and round-trip through IDML (`type.kenten`, `type.shatai`, `type.autoTateChuYoko`, `type.rotateRoman`, `type.romanWordBreak`, `type.gridSettings`); ICF top and bottom come from the font's `BASE` table. Full InDesign CJK composition parity and frame-grid layout remain unfinished. Warichu sets the selected run in smaller lines inside the line after the line is broken.
DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web.
@@@ -153,9 -119,9 +153,9 @@@
- Preferences: Dictionary (user dictionary; `spelling.setWords/words`), Spelling (Dynamic Spelling: red squiggles on the canvas, also Edit ▸ Spelling), Autocorrect (word list, applied as you type), Notes, Track Changes, Story Editor Display and File Handling (recovery interval) sections.
- Colour management exposed: Edit ▸ Color Settings (`color.settings`: RGB/CMYK working spaces, intent, black-point compensation; `color.loadProfile` for ICC files; `color.convert` through the working spaces, with gamut checks) and View ▸ Proof Setup / Proof Colors (press, sRGB, legacy Mac RGB, colour-blindness simulations, simulate paper) on the canvas.
- Keyboard: Tab / Shift+Tab hide and show all panels / all but Tools (`window.hidePanels`, `window.hidePanelsExceptTools`); Cmd+F6 / Cmd+Shift+F6 cycle documents; panel fields are reached with Tab and Escape returns to the layout.
-- Smart guides and snapping (View ▸ Snap to Guides / Snap to Document Grid / Smart Guides, `view.snapPreferences` and Preferences ▸ Guides & Pasteboard): moving, drawing, resizing, rotating and pen/anchor drags snap in order to the document and baseline grids, ruler guides, margins and columns, other objects' edges and centres (parent-page items too, by visible stroked bounds), equal spacing, matching dimensions and matching rotation, with guides, gap marks and measurements drawn on the canvas. Shift and Cmd constrain the gesture.
+- Smart guides and snapping (View ▸ Snap to Guides / Snap to Document Grid / Smart Guides, `view.snapPreferences` and Preferences ▸ Guides & Pasteboard): moving, drawing, resizing, rotating and pen/anchor drags snap in order to the document grid, ruler guides, margins and columns, other objects' edges and centres (parent-page items too, by visible stroked bounds), equal spacing (centred between two neighbours too), matching dimensions, the baseline grid and matching rotation, with guides, gap marks and measurements drawn on the canvas. Shift and Cmd constrain the gesture.
- View ▸ Rotate Spread (`view.rotateSpread`, `layout.rotateSpreadView`): the spread in view turns in quarter turns on screen (stored with the document; output is unaffected). The canvas maps each spread through its own transform, so tools, snapping, resize handles, guides, overlays and rendering all follow the turned spread.
- - Vertical type (Vertical Type Tool, Type ▸ Story Direction `type.storyDirection`, IDML StoryOrientation): the direction belongs to the story, so every frame of a thread is vertical or horizontal together and a frame threaded onto a story takes its direction (`object.textFrameOptions {vertical}` sets the frames' stories); lines run top to bottom and follow each other right to left; the arrow keys follow them (Down and Up along the line, Left and Right to the next and previous line, keeping the position along it); CJK characters stay upright and other text turns, on screen and in PDF; CJK line breaking with basic kinsoku (also in horizontal text); Korean breaks at spaces, word by word (Hangul in any language, hanja in Korean text), or between syllables when the paragraph asks for it (`type.para {koreanCharBreaks}`, Paragraph Style Options ▸ Justification; not written to IDML). Upright text is shaped top to bottom: punctuation and brackets take their vertical forms (OpenType `vert`; `vkrn` and `vpal` through OpenType features), glyphs advance by their vertical metrics (`vmtx`) and hang from their vertical origins (`VORG`) on the centre of the ideographic em box (`BASE`, else OS/2), which the first line's ascent follows; turned text keeps its horizontal forms. Tate-chu-yoko (Type ▸ Tate-Chu-Yoko, `type.tateChuYoko`, IDML `Tatechuyoko`) sets a run such as "12" side by side within one em of the line. Ruby (Type ▸ Ruby…, `type.ruby`, IDML RubyString; group ruby spread 1-2-1 or centred) and kenten emphasis dots (`type.kenten`, IDML KentenKind) are set over their text — to its right in vertical frames — without changing line breaks. Warichu and ruby options (per-character ruby, positions, overhang) aren't there yet.
+ - Vertical type (Vertical Type Tool, Type ▸ Story Direction `type.storyDirection`, IDML StoryOrientation): the direction belongs to the story, so every frame of a thread is vertical or horizontal together and a frame threaded onto a story takes its direction (`object.textFrameOptions {vertical}` sets the frames' stories); lines run top to bottom and follow each other right to left; the arrow keys follow them (Down and Up along the line, Left and Right to the next and previous line, keeping the position along it); CJK characters stay upright and other text turns, on screen and in PDF; CJK line breaking with basic kinsoku (also in horizontal text); Korean breaks at spaces, word by word (Hangul in any language, hanja in Korean text), or between syllables when the paragraph asks for it (`type.para {koreanCharBreaks}`, Paragraph Style Options ▸ Justification; not written to IDML). Upright text is shaped top to bottom: punctuation and brackets take their vertical forms (OpenType `vert`; `vkrn` and `vpal` through OpenType features), glyphs advance by their vertical metrics (`vmtx`) and hang from their vertical origins (`VORG`) on the centre of the ideographic em box (`BASE`, else OS/2), which the first line's ascent follows; turned text keeps its horizontal forms. Tate-chu-yoko (Type ▸ Tate-Chu-Yoko, `type.tateChuYoko`, IDML `Tatechuyoko`) sets a run such as "12" side by side within one em of the line. Ruby (Type ▸ Ruby…, `type.ruby`, IDML `Ruby*`): group and per-character (jukugo) ruby with every placement, font, overhang, parent-spacing, auto-scaling and colour setting of InDesign's four ruby panes, set over the text (to its right in vertical frames) or under it, and beyond kenten on the same side; longer ruby spaces its parent out before line breaking and keeps its group on the line of each neighbour it overhangs. Kenten emphasis marks (`type.kenten`, IDML `Kenten*`) are set beside their text. Ruby and kenten overprint shows in Overprint Preview; PDF export writes no overprint. With Show CJK Features on, Paragraph and Character Style Options list every Japanese section (Auto Tate-chu-yoko, Tate-chu-yoko, Ruby Placement and Spacing, Ruby Font and Size, Adjustment When Ruby Is Longer Than Parent, Ruby Color, Kenten Settings, Kenten Color, Shatai, Japanese Composition, Grid Settings, Warichu), and the Ruby dialog has the four ruby panes.
- Math expressions (Type ▸ Insert Math Expression…, `math.insert`, `math.svg`): a LaTeX subset (fractions, scripts, roots, big operators with limits, Greek, relations and operators with math spacing, `\left…\right`, `\text`) typeset by our own engine into SVG, placed inline at the cursor or as a frame; the LaTeX is kept as alt text and can be edited.
- Object Layer Options for placed PDFs (`object.pdfLayers`, `object.layerOptions`, Object ▸ Object Layer Options…): the file's optional-content layers listed and shown or hidden per frame on screen; in exported PDFs such graphics go out as 300 ppi images of their visible layers.
- Effects: Inner Glow (edge or centre), Bevel and Emboss (inner bevel lit from the light angle), Satin (`object.innerGlow`, `object.bevel`, `object.satin`); PDF export now keeps soft effects: objects with shadows, glows, feathers, bevels or satin go out as 300 ppi transparent images of their appearance (threaded text frames excepted).
diff --cc crates/compose/src/kenten.rs
index 000000000,f32d95547..c02880ab6
mode 000000,100644..100644
--- a/crates/compose/src/kenten.rs
+++ b/crates/compose/src/kenten.rs
@@@ -1,0 -1,192 +1,193 @@@
+ //! 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 {
++ rendered_char: ch,
+ 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,
+ dx: 0.0,
+ });
+ 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 --cc crates/compose/src/lib.rs
index d8f5d9330,fec45383b..c5fc92cb0
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@@ -13,14 -13,14 +13,17 @@@
mod bidi;
pub mod breaker;
mod cache;
+pub mod grep;
+ mod grid;
pub mod hyphen;
+ pub mod kenten;
+mod mojikumi;
mod notes;
mod overlay;
+mod parabox;
mod ruby;
pub mod shape;
+ pub mod shatai;
pub mod table;
pub mod vars;
mod warichu;
@@@ -989,7 -886,8 +1008,9 @@@ fn compose_with_db(doc: &Document, stor
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
+ let rtl = pp.direction == designcraft_doc::TextDirection::RightToLeft;
+ // 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) {
@@@ -1057,43 -934,75 +1078,90 @@@
for (k, b) in breaks.iter().enumerate() {
let (s, e) = (g0 + b.start, g0 + b.end);
let line_glyphs = &glyphs[s..e.max(s)];
- let (asc, desc, lead) = line_metrics(line_glyphs, &glyphs, s, base_leading, base_chars.size, db, &base_chars);
- let reference = cjk_line_reference(line_glyphs);
- let mut baseline = cur.next_baseline(f, col, lead, asc, &pp);
+ let (asc, tops, desc, lead) = line_metrics(line_glyphs, &glyphs, s, mark_leading, mark_chars.size, db, &mark_chars);
+ let lead = match last_line_mark {
+ Some(m) if k + 1 == breaks.len() => lead.max(m),
+ _ => lead,
+ };
+ let (reference, model) = cjk_line_reference(line_glyphs);
+ let advance = if cur.last_baseline.is_some() { cur.aki_below.unwrap_or(lead) } else { lead };
- // Baseline grid: the next grid line at or below.
- let grid = f.grid.filter(|&(_, inc)| {
- inc > 0.0 && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))
- });
- let snap = |y: f64| grid.map_or(y, |(g_start, inc)| g_start + ((y - g_start) / inc - 1e-6).ceil() * inc);
+ let mut baseline = cur.next_baseline(f, col, advance, asc, tops, &pp);
if cur.last_baseline.is_some() {
baseline += cur.last_reference - reference;
}
- baseline = snap(baseline);
+ // Baseline grid: grid alignment and gyoudori (see `grid`).
++ let grid = f.grid.filter(|&(_, inc)| {
++ inc > 0.0
++ && inc.is_finite()
++ && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))
++ });
+ 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()
- {
++ if let Some((g_start, inc)) = grid {
+ 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 aki_below = |model, lead| (model == designcraft_doc::cjk::LeadingModel::AkiBelow).then_some(lead);
++ let (mut down, mut prev, mut prev_aki, mut last_r) = (0.0, reference, aki_below(model, lead), r);
++ for (j, nb) in breaks.iter().enumerate().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;
++ let (_, _, _, nlead) = line_metrics(lg, &glyphs, ns, mark_leading, mark_chars.size, db, &mark_chars);
++ let nlead = match last_line_mark {
++ Some(m) if j + 1 == breaks.len() => nlead.max(m),
++ _ => nlead,
++ };
++ let (nref, nmodel) = cjk_line_reference(lg);
++ down += prev_aki.unwrap_or(nlead) + prev - nref;
+ prev = nref;
++ prev_aki = aki_below(nmodel, nlead);
+ 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.
++ // A line a wrap pushes down moves by whole grid lines, keeping its place in its band.
++ let on_grid = baseline;
++ let snap = |y: f64| grid.map_or(y, |(_, inc)| on_grid + ((y - on_grid) / inc - 1e-6).ceil().max(0.0) * inc);
+ // Wrap: push the line down to the first position with a slot (back on the grid).
let (mut x0, mut x1) = (col.x0, col.x1);
if !f.exclusions.is_empty() {
+ let jump = cur.jump(f, lead, asc, tops);
let mut tries = 0;
loop {
- match free_slot(f, col, baseline - asc, baseline + desc, base_size) {
- Some((a, b)) => {
- x0 = a;
- x1 = b;
- break;
- }
- None => {
- baseline += 1.0;
- tries += 1;
- if baseline > col.y1 || tries > 4000 {
- break;
- }
- }
+ let Some((nb, (a, z))) = wrap_slot(f, col, baseline, asc, desc, jump, base_size) else {
+ // No room in this column.
+ baseline = baseline.max(col.y1) + 1.0;
+ break;
+ };
+ let pushed = nb > baseline;
+ (baseline, x0, x1) = (nb, a, z);
+ tries += 1;
+ if !pushed || grid.is_none() || tries > 4000 {
+ break;
}
+ baseline = snap(baseline);
}
}
++ grid_end = grid_end.map(|end| end + baseline - on_grid);
let capped = cur.split.is_none() && line_cap[pi] == Some(line_no) && line_no > col_first_line;
// Footnotes referenced on this line need room at the bottom of the column too
// (a line at the top of a column is set anyway).
@@@ -1202,32 -1092,10 +1270,33 @@@
let forced_mid = brk == Some(story::FORCED_LINE_BREAK) && !last;
let (mut placed, end_x, ratio) =
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 = if line_no == 0 && s == 0 { align_label(&mut placed, label_aligned, label_tab, list_align, end_x) } else { end_x };
+ // Warichu runs before ruby so a reading is placed over the stacked note, and before
+ // the trimmed spaces and the drop cap join the line, so neither is stacked.
let end_x = end_x + warichu::place(&styles_tab, &mut placed);
+ // The spaces the break trimmed off the end follow the line undrawn, so the caret
+ // and the selection reach them; alignment and justification ignore them.
+ if pp.direction != designcraft_doc::TextDirection::RightToLeft && !placed.iter().any(|g| g.rtl) {
+ let mut x = end_x;
+ for g in glyphs.get(e..(g0 + b.next).min(glyphs.len())).unwrap_or(&[]).iter().filter(|g| g.is_space()) {
+ placed.push(PlacedGlyph { visible: false, ..place(g, x) });
+ x += g.adv;
+ }
+ }
+ let mut drop_box = None;
+ if line_no == 0
+ && let Some(dc) = &drop_cap
+ {
+ let at = if rtl { x1 - pp.right_indent - dc.width } else { x0 + pp.left_indent - dc.lsb };
+ placed.splice(0..0, place_drop_cap(dc, at, rtl));
+ drop_box = Some(DropCapBox {
+ end: dc.end,
+ baseline: baseline + dc.drop,
+ rect: Rect::new(at, baseline - asc, at + dc.width, baseline + dc.drop + desc),
+ });
+ }
- ruby::annotate(db, &styles_tab, &mut placed, doc.settings.glyph_fallback);
+ ruby::annotate(db, &mut styles_tab, &story.text, &mut placed, doc.settings.glyph_fallback, f.vertical);
+ kenten::annotate(db, &styles_tab, &mut placed, doc.settings.glyph_fallback);
let range_end = if last { prange.end } else { glyphs.get(g0 + b.next).map(|g| g.byte).unwrap_or(prange.end) };
let range_start = glyphs.get(s).map(|g| g.byte).unwrap_or(prange.start).min(range_end);
let range_start = if line_no == 0 { prange.start } else { range_start };
@@@ -1286,9 -1143,9 +1355,10 @@@
}
cur.last_baseline = Some(baseline);
cur.last_reference = reference;
+ cur.aki_below = (model == designcraft_doc::cjk::LeadingModel::AkiBelow).then_some(lead);
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
@@@ -2237,23 -2107,22 +2330,25 @@@ fn cjk_alignment_shift(g: &Glyph, refer
A::EmTop => t - rt,
A::EmCenter => (t + b - rt - rb) / 2.0,
A::EmBottom => b - rb,
- A::IcfTop => reference.ascent - g.ascent,
- A::IcfBottom => g.descent - reference.descent,
+ A::IcfTop => cjk_icf_box(g).0 - cjk_icf_box(reference).0,
+ A::IcfBottom => cjk_icf_box(g).1 - cjk_icf_box(reference).1,
}
}
-fn cjk_line_reference(line: &[Glyph]) -> f64 {
+/// The point leading measures a line from, relative to its baseline, and the leading model of
+/// the line's largest character, which sets both.
+fn cjk_line_reference(line: &[Glyph]) -> (f64, designcraft_doc::cjk::LeadingModel) {
use designcraft_doc::cjk::LeadingModel as L;
- let Some(g) = line.iter().max_by(|a, b| a.size.total_cmp(&b.size)) else { return 0.0 };
+ let Some(g) = line.iter().max_by(|a, b| a.size.total_cmp(&b.size)) else { return (0.0, L::Roman) };
let (top, bottom) = cjk_em_box(g);
- match g.leading_model {
+ let reference = match g.leading_model {
L::Roman => 0.0,
- L::AkiBelow => bottom,
- L::AkiAbove => top,
+ // "Space below" measures from the em box top (Em Box Top/Right), "space above" from its
+ // bottom (Em Box Bottom/Left).
+ L::AkiBelow => top,
+ L::AkiAbove => bottom,
L::Center | L::CenterDown => (top + bottom) / 2.0,
- }
+ };
+ (reference, g.leading_model)
}
fn line_metrics(
diff --cc crates/compose/src/ruby.rs
index b39f11eef,548e00701..0cddef5c6
--- a/crates/compose/src/ruby.rs
+++ b/crates/compose/src/ruby.rs
@@@ -94,33 -405,259 +405,260 @@@ pub(crate) fn reserve(db: &ScopedFonts<
i += 1;
continue;
};
- // The group: following glyphs with the same ruby.
+ let missing = st.missing_font;
let mut j = i + 1;
- while j < line.len() && (line[j].len == 0 || style(&line[j]).is_some_and(|s| s.ruby.as_ref() == Some(text))) {
+ while glyphs.get(j).is_some_and(|g| in_group(styles.as_slice(), g, (text.as_str(), unit))) {
j += 1;
}
- let base: Vec<&PlacedGlyph> = line[i..j].iter().filter(|b| b.len > 0).collect();
- let x0 = base.iter().map(|b| b.x).fold(f64::MAX, f64::min);
- let x1 = base.iter().map(|b| b.x + b.adv).fold(f64::MIN, f64::max);
- let (mut glyphs, w) = set(g, text, st.size * SCALE, st.size);
- let n = glyphs.len().max(1) as f64;
- if w < x1 - x0 {
- // Shorter than the base: spread out, half a gap at each end (the 1-2-1 rule).
- let gap = (x1 - x0 - w) / n;
- for (k, r) in glyphs.iter_mut().enumerate() {
- r.x += x0 + gap * (k as f64 + 0.5);
+ let parents: Vec<usize> = (i..j).filter(|&k| glyphs.get(k).is_some_and(|g| g.len > 0)).collect();
+ let (Some(&first), Some(&last)) = (parents.first(), parents.last()) else {
+ i = j;
+ continue;
+ };
+ let Some((face, parent_size)) = glyphs.get(first).map(|g| (g.face, g.size)) else {
+ i = j;
+ continue;
+ };
+ let shaped = shape_ruby(db, face, &text, &spec, parent_size, fallback || missing, vertical);
+ let width: f64 = glyphs.get(i..j).unwrap_or_default().iter().map(|g| g.adv).sum();
+ let mono = unit.is_some();
+ let side = |k: Option<usize>| -> Side {
+ let Some(g) = k.and_then(|k| glyphs.get(k)) else { return Side::Edge };
+ if g.ch.is_control() || g.ch == crate::shape::HIDDEN {
+ return Side::Edge;
}
- } else {
- // Longer: centred over the base.
- let start = (x0 + x1 - w) / 2.0;
- for r in &mut glyphs {
- r.x += start;
+ match styles.get(g.style as usize) {
+ Some(s) if s.ruby.is_some() => Side::Ruby { free: unit_free(db, g.face, g.adv, s, mono, fallback, vertical) },
+ _ => Side::Char { ch: g.ch, adv: g.adv },
+ }
+ };
+ let before = allowance(&spec, shaped.em, parent_size, side(i.checked_sub(1)), true);
+ let after = allowance(&spec, shaped.em, parent_size, side(Some(j)), false);
+ let (before, after) = usable(spec.alignment, before, after);
+ let w = shaped.width * auto_scale(&spec, shaped.width, width, before + after);
+ if let Some((lead, inner, trail)) = parent_spacing(spec.parent_spacing, parents.len(), w - width - before - after) {
+ if let Some(g) = glyphs.get_mut(first) {
+ g.dx += lead;
+ g.adv += lead;
+ }
+ for pair in parents.windows(2) {
+ if let Some(g) = pair.get(1).and_then(|n| n.checked_sub(1)).and_then(|k| glyphs.get_mut(k)) {
+ g.adv += inner;
+ }
+ }
+ if let Some(g) = j.checked_sub(1).and_then(|k| glyphs.get_mut(k)) {
+ g.adv += trail;
+ }
+ }
+ // The overhang this relies on needs the neighbour on the same line: at a line edge the
+ // edge takes none (auto-align) or only the overhang amount, so the group stays with each
+ // neighbour its ruby overhangs and the spacing reserved here is what `annotate` places.
+ let spaced: f64 = glyphs.get(i..j).unwrap_or_default().iter().map(|g| g.adv).sum();
+ let excess = w - spaced;
+ if excess > 1e-9 {
+ let lead = lead_overhang(spec.alignment, excess, before, after);
+ if lead > 1e-9
+ && let Some(g) = i.checked_sub(1).and_then(|k| glyphs.get_mut(k))
+ {
+ g.break_after = Some(false);
+ }
+ if excess - lead > 1e-9
+ && let Some(g) = j.checked_sub(1).and_then(|k| glyphs.get_mut(k))
+ {
+ g.break_after = Some(false);
}
}
- 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));
+ // Group ruby keeps its parent on one line (JLReq 3.3).
+ if !mono {
+ for g in glyphs.get_mut(first..last).unwrap_or_default() {
+ g.break_after = Some(false);
+ }
+ }
+ i = j;
+ }
+ }
+
+ // ---------- after line breaking ----------
+
+ /// The run style ruby glyphs are drawn in: the parent's, with the ruby's colours and none of the
+ /// parent's decorations.
+ fn ruby_style(styles: &mut Vec<RunStyle>, base: &RunStyle, spec: &RubySpec, size: f64, missing: bool) -> u32 {
+ let mut rs = base.clone();
+ if spec.fill.is_empty() {
+ if let Some(t) = spec.fill_tint {
+ rs.fill_tint = t;
+ }
+ } else {
+ rs.fill.clone_from(&spec.fill);
+ rs.fill_tint = spec.fill_tint.unwrap_or(1.0);
+ }
+ if spec.stroke.is_empty() {
+ if let Some(t) = spec.stroke_tint {
+ rs.stroke_tint = t;
+ }
+ } else {
+ rs.stroke.clone_from(&spec.stroke);
+ rs.stroke_tint = spec.stroke_tint.unwrap_or(1.0);
+ }
+ if let Some(w) = spec.stroke_weight {
+ rs.stroke_weight = w;
+ }
+ // Text itself never overprints, so `Auto` (follow the text) is off.
+ rs.overprint_fill = spec.overprint_fill == AdornmentOverprint::On;
+ rs.overprint_stroke = spec.overprint_stroke == AdornmentOverprint::On;
+ rs.size = size;
+ rs.missing_font = missing;
+ rs.underline = false;
+ rs.strikethrough = false;
+ rs.custom_tracking = false;
+ rs.condition = None;
+ rs.xml_tag = None;
+ rs.ruby = None;
+ rs.ruby_spec = None;
+ rs.ruby_unit = None;
+ rs.kenten_mark = None;
+ rs.warichu = false;
+ intern(styles, rs)
+ }
+
+ /// How far the ruby must move away from its parent (down for ruby below, up for ruby above: the
+ /// result is signed along y) so that it clears kenten set on the same side of the parent
+ /// characters. Kenten sit next to the parent (JIS X 4051, JLReq: emphasis dots go between the
+ /// base characters and ruby on the same side); the ruby's em box then starts where the marks' em
+ /// box ends. `y` is the ruby's baseline without kenten and `tall` its em height.
+ fn kenten_clearance(styles: &[RunStyle], base: &[&PlacedGlyph], shaped: &Shaped, tall: f64, position: RubyPosition, y: f64) -> f64 {
+ let below = position == RubyPosition::BelowLeft;
+ let (ruby_top, ruby_bottom) = shaped.face.em_box();
+ let k = tall / shaped.face.units_per_em().max(1.0);
+ let overlap = base
+ .iter()
+ .filter_map(|b| {
+ let m = styles.get(b.style as usize)?.kenten_mark.as_ref().filter(|m| m.below == below)?;
+ let (top, bottom) = b.face.em_box();
+ let h = m.size * m.y_scale;
+ Some(if below {
+ (b.y - bottom * b.sy + m.distance + h) - (y - ruby_top * k)
+ } else {
+ (y - ruby_bottom * k) - (b.y - top * b.sy - m.distance - h)
+ })
+ })
+ .fold(0.0, f64::max);
+ if below { overlap } else { -overlap }
+ }
+
+ /// Add the ruby of a laid-out line's glyphs. `text` is the story text the glyphs'
+ /// bytes index; `glyph_fallback`: the document draws missing glyphs from fallback fonts (a
+ /// missing font's substitute always does); `vertical`: the frame is vertical.
+ pub(crate) fn annotate(
+ db: &ScopedFonts<'_>,
+ styles: &mut Vec<RunStyle>,
+ text: &str,
+ line: &mut Vec<PlacedGlyph>,
+ glyph_fallback: bool,
+ vertical: bool,
+ ) {
+ if !line.iter().any(|g| styles.get(g.style as usize).is_some_and(|s| s.ruby.is_some())) {
+ return;
+ }
+ let mut extra = Vec::new();
+ let mut i = 0;
+ while i < line.len() {
+ let Some(g) = line.get(i) else { break };
+ let Some(st) = styles.get(g.style as usize).filter(|_| g.len > 0 && g.visible).cloned() else {
+ i += 1;
+ continue;
+ };
+ let fallback = glyph_fallback || st.missing_font;
+ let (Some(reading), Some(spec)) = (st.ruby.clone(), st.ruby_spec.clone()) else {
+ i += 1;
+ continue;
+ };
+ // The group: following glyphs with the same ruby (and unit).
+ let key = (reading.as_str(), st.ruby_unit);
+ let mut j = i + 1;
+ while line.get(j).is_some_and(|b| b.len == 0 || styles.get(b.style as usize).and_then(ruby_key).is_some_and(|k| k == key)) {
+ j += 1;
+ }
+ let group = line.get(i..j).unwrap_or_default();
+ let base: Vec<&PlacedGlyph> = group.iter().filter(|b| b.len > 0).collect();
+ let Some(&first) = base.first() else {
+ i = j;
+ continue;
+ };
+ // The parent's extent from its pen positions (parent spacing lies inside it).
+ let x0 = base.iter().map(|b| b.x - b.dx).fold(f64::MAX, f64::min);
+ let x1 = base.iter().map(|b| b.x - b.dx + b.adv).fold(f64::MIN, f64::max);
+ let width = (x1 - x0).max(0.0);
+ let shaped = shape_ruby(db, first.face, &reading, &spec, st.size, fallback, vertical);
+ let mono = st.ruby_unit.is_some();
+ let side = |b: Option<&PlacedGlyph>| -> Side {
+ let Some(b) = b.filter(|b| b.visible) else { return Side::Edge };
+ match styles.get(b.style as usize) {
+ Some(s) if s.ruby.is_some() => Side::Ruby { free: unit_free(db, b.face, b.adv, s, mono, glyph_fallback, vertical) },
+ _ => Side::Char { ch: text.get(b.byte..).and_then(|s| s.chars().next()).unwrap_or(' '), adv: b.adv },
+ }
+ };
+ let prev = line.get(..i).unwrap_or_default().iter().rev().find(|b| b.len > 0);
+ let next = line.get(j..).unwrap_or_default().iter().find(|b| b.len > 0);
+ let before = allowance(&spec, shaped.em, st.size, side(prev), true);
+ let after = allowance(&spec, shaped.em, st.size, side(next), false);
+ let (before, after) = usable(spec.alignment, before, after);
+ let scale = auto_scale(&spec, shaped.width, width, before + after);
+ let w = shaped.width * scale;
+ // Each glyph's offset from the parent's start.
+ let offsets: Vec<f64> = if w <= width + 1e-9 {
+ let mut slots: Vec<f64> = Vec::new();
+ for r in &shaped.glyphs {
+ match slots.last_mut() {
+ Some(a) if r.joined => *a += r.adv,
+ _ => slots.push(r.adv),
+ }
+ }
+ let at = spread(spec.alignment, width, &slots, shaped.em);
+ let (mut slot, mut slot_x) = (0usize, 0.0);
+ let mut out = Vec::with_capacity(shaped.glyphs.len());
+ for (n, r) in shaped.glyphs.iter().enumerate() {
+ if !r.joined {
+ if n > 0 {
+ slot += 1;
+ }
+ slot_x = r.x;
+ }
+ out.push(at.get(slot).copied().unwrap_or(0.0) + (r.x - slot_x));
+ }
+ out
+ } else {
+ let lead = lead_overhang(spec.alignment, w - width, before, after);
+ shaped.glyphs.iter().map(|r| r.x * scale - lead).collect()
+ };
+ let tall = shaped.size * spec.y_scale;
+ let y = match spec.position {
+ // Its em box sits just clear of the parent's.
+ RubyPosition::AboveRight => -(st.size * 0.88 + tall * 0.2) - spec.y_offset,
+ RubyPosition::BelowLeft => st.size * 0.12 + tall * 0.96 + spec.y_offset,
+ };
+ let y = y + kenten_clearance(styles, &base, &shaped, tall, spec.position, y);
+ let missing = if spec.font_family.is_empty() { st.missing_font } else { !db.has_family(&spec.font_family) };
+ let style = ruby_style(styles, &st, &spec, shaped.size, missing);
+ for (r, off) in shaped.glyphs.iter().zip(offsets) {
+ extra.push(PlacedGlyph {
++ rendered_char: r.ch,
+ face: shaped.face,
+ gid: r.gid,
+ x: x0 + off + spec.x_offset,
+ y: y + r.y,
+ adv: r.adv * scale,
+ sx: r.sx * scale,
+ sy: r.sy,
+ style,
+ byte: first.byte,
+ len: 0,
+ visible: true,
+ upright: r.tcy.is_none() && upright_in_vertical(r.ch),
+ tcy: r.tcy,
+ rtl: false,
+ dx: 0.0,
+ });
}
i = j;
}
diff --cc crates/compose/src/shape.rs
index f298d2468,2c4037042..964da6038
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@@ -351,8 -305,9 +398,11 @@@ 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 = marks_join_their_base(&story.text, resolved);
+ let resolved = split_auto_tcy(resolved, &auto_tcy);
+ let mut pieces: Vec<Piece> = Vec::with_capacity(resolved.len());
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.
@@@ -403,98 -363,12 +453,100 @@@
k = e;
}
if k < b {
- shape_run(db, &story.text, k..b, &props, auto_leading, style, sub, &mut glyphs);
+ pieces.push(Piece { range: k..b, props, style, env: auto_leading, hidden: false, composite_note: false });
}
}
+ let mut i = 0;
+ while i < pieces.len() {
+ let first = &pieces[i];
+ if first.hidden {
+ // Hidden conditional text: zero-width, unbreakable, undrawn place-holders keep every
+ // byte addressable (caret, selection) without taking space.
+ let face = db.face(&first.props.font_family, &first.props.font_style);
+ for (k, c) in story.text[first.range.clone()].char_indices() {
+ if c == '\n' {
+ continue;
+ }
+ let mut g = control_glyph(&face, &first.props, first.env, first.style, first.range.start + k, c);
+ g.ch = HIDDEN;
+ (g.ascent, g.typo_ascent, g.descent, g.leading, g.cap, g.xh) = (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
+ glyphs.push(g);
+ }
+ i += 1;
+ continue;
+ }
+ if first.composite_note {
+ if let Some(composite) = styles.composite_font(&first.props.font_family) {
+ let at = first.range.start;
+ let label = sub.notes.get(&at).map_or("#", String::as_str);
+ let begin = glyphs.len();
+ let mut segments: Vec<(usize, usize, Option<&designcraft_doc::cjk::CompositeFontEntry>)> = Vec::new();
+ for (at, c) in label.char_indices() {
+ let entry = composite.entry(c);
+ if let Some((_, end, _)) = segments.last_mut().filter(|(_, _, previous)| *previous == entry) {
+ *end = at + c.len_utf8();
+ } else {
+ segments.push((at, at + c.len_utf8(), entry));
+ }
+ }
+ for (a, b, entry) in segments {
+ let props = composite_props(db, &first.props, entry);
+ let style = table.intern(db, &props);
+ let env = table.env_for(first.env, style);
+ let face = db.face(&props.font_family, &props.font_style);
+ shape_segment(
+ db,
+ &story.text,
+ first.range.clone(),
+ label.get(a..b),
+ &props,
+ &face,
+ env,
+ &StyleRuns(&[(at, style)]),
+ &mut glyphs,
- sub.vertical,
++ sub.upright(),
+ );
+ }
+ for (index, glyph) in glyphs[begin..].iter_mut().enumerate() {
+ glyph.len = if index == 0 { first.range.len() } else { 0 };
+ glyph.no_break = true;
+ }
+ }
+ i += 1;
+ continue;
+ }
+ let key = shaping_key(&first.props);
+ let mut j = i + 1;
+ // Jidori fits its own run into whole ems: such pieces stay apart.
+ while j < pieces.len()
+ && first.props.jidori == 0
+ && !pieces[j].hidden
+ && !pieces[j].composite_note
+ && pieces[j].range.start == pieces[j - 1].range.end
+ && pieces[j].env.glyph_fallback == first.env.glyph_fallback
+ && shaping_key(&pieces[j].props) == key
+ {
+ j += 1;
+ }
+ let group = &pieces[i..j];
+ let range = group[0].range.start..group[j - i - 1].range.end;
+ let runs: Vec<(usize, u32)> = group.iter().map(|p| (p.range.start, p.style)).collect();
+ let start = glyphs.len();
+ shape_run(db, &story.text, range, &first.props, first.env, &StyleRuns(&runs), sub, &mut glyphs);
+ // A cluster (a ligature, a letter with its marks) that spans two styles would paint one
+ // of them in the other's colour: shape those pieces apart instead.
+ let spans_cut = |g: &Glyph| runs[1..].iter().any(|&(cut, _)| g.byte < cut && cut < g.byte + g.len);
+ if group.len() > 1 && glyphs[start..].iter().any(spans_cut) {
+ glyphs.truncate(start);
+ for p in group {
+ shape_run(db, &story.text, p.range.clone(), &p.props, p.env, &StyleRuns(&[(p.range.start, p.style)]), sub, &mut glyphs);
+ }
+ }
+ i = j;
+ }
+ fit_auto_tcy(&mut glyphs, &auto_tcy);
collapse_tcy(&mut glyphs, sub.vertical);
+ crate::ruby::reserve(db, table.styles, &mut glyphs, auto_leading.glyph_fallback, sub.vertical);
ShapedPara { glyphs, range }
}
@@@ -723,7 -566,7 +776,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, styles, out, sub.vertical);
- shape_segment(db, text, a..b, None, p, face, auto_leading, style, out, sub.upright());
++ shape_segment(db, text, a..b, None, p, face, auto_leading, styles, out, sub.upright());
}
};
for (i, c) in text[range.clone()].char_indices() {
@@@ -750,7 -591,7 +803,7 @@@
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, styles, 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());
++ shape_segment(db, text, i..i + c.len_utf8(), Some(d.encode_utf8(&mut [0; 4])), p, &face, auto_leading, styles, out, sub.upright());
continue;
}
}
@@@ -782,9 -623,9 +835,9 @@@
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, styles, out, sub.vertical),
- Some(v) => shape_segment(db, text, i..i + c.len_utf8(), Some(v), p, &primary, auto_leading, style, out, sub.upright()),
++ Some(v) => shape_segment(db, text, i..i + c.len_utf8(), Some(v), p, &primary, auto_leading, styles, out, sub.upright()),
None => {
- let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
+ let mut g = control_glyph(&primary, p, auto_leading, styles.at(i), i, c);
g.adv = 0.0;
out.push(g);
}
@@@ -798,12 -639,10 +851,12 @@@
} 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.upright());
+ // Page numbers take the digits of the text they stand in.
+ let s: String = s.chars().map(|ch| digits.map(ch, &p.language)).collect();
- shape_segment(db, text, i..i + c.len_utf8(), Some(&s), p, &primary, auto_leading, styles, out, sub.vertical);
++ shape_segment(db, text, i..i + c.len_utf8(), Some(&s), p, &primary, auto_leading, styles, out, sub.upright());
}
designcraft_doc::OBJECT_MARK => {
- let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
+ let mut g = control_glyph(&primary, p, auto_leading, styles.at(i), i, c);
if let Some(o) = sub.objects.get(&i).filter(|o| !o.custom) {
let auto = matches!(p.leading, Leading::Auto);
match o.y_offset {
@@@ -831,16 -662,16 +884,16 @@@
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, styles, out, sub.vertical),
- Some(t) => shape_segment(db, text, i..i + c.len_utf8(), Some(t), p, &primary, auto_leading, style, out, sub.upright()),
++ Some(t) => shape_segment(db, text, i..i + c.len_utf8(), Some(t), p, &primary, auto_leading, styles, out, sub.upright()),
None => {
- let mut g = control_glyph(&primary, p, auto_leading, style, i, c);
+ let mut g = control_glyph(&primary, p, auto_leading, styles.at(i), i, c);
g.adv = 0.0;
out.push(g);
}
},
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, styles, out, sub.vertical);
- shape_segment(db, text, i..i + c.len_utf8(), Some(s), p, &primary, auto_leading, style, out, sub.upright());
++ shape_segment(db, text, i..i + c.len_utf8(), Some(s), p, &primary, auto_leading, styles, out, sub.upright());
}
_ => {
// Zero-width control glyph carrying metrics (tabs get their width at line layout).
@@@ -1034,36 -861,12 +1087,37 @@@ fn shape_segment
p: &CharProps,
face: &Arc<FontFace>,
auto_leading: TypeEnv,
- style: u32,
+ styles: &StyleRuns<'_>,
out: &mut Vec<Glyph>,
- vertical: bool,
+ mode: Upright,
) {
- let _ = db;
+ // Generated labels need the same coverage fallback as ordinary text. Keep the
+ // original marker address and one carrier even when several faces draw the label.
+ if let Some(label) = replacement.filter(|_| auto_leading.glyph_fallback) {
+ let lang = designcraft_doc::language_tag(&p.language);
+ let mut segments: Vec<(usize, usize, Arc<FontFace>)> = Vec::new();
+ for (at, c) in label.char_indices() {
+ let selected = if face.covers(c) { face.clone() } else { db.fallback_for(c, face.id(), lang).unwrap_or_else(|| face.clone()) };
+ if let Some((_, end, previous)) = segments.last_mut().filter(|(_, _, previous)| previous.id() == selected.id()) {
+ *end = at + c.len_utf8();
+ let _ = previous;
+ } else {
+ segments.push((at, at + c.len_utf8(), selected));
+ }
+ }
+ if segments.iter().any(|(_, _, selected)| selected.id() != face.id()) {
+ let begin = out.len();
+ for (a, b, selected) in segments {
- shape_segment(db, text, range.clone(), label.get(a..b), p, &selected, auto_leading, styles, out, vertical);
++ shape_segment(db, text, range.clone(), label.get(a..b), p, &selected, auto_leading, styles, out, mode);
+ }
+ for (i, glyph) in out[begin..].iter_mut().enumerate() {
+ glyph.len = if i == 0 { range.len() } else { 0 };
+ glyph.no_break = true;
+ }
+ return;
+ }
+ }
+ 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;
diff --cc crates/compose/src/tests.rs
index e8d0f16b4,a94c01187..6624a4c8f
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@@ -1808,1106 -1718,15 +1997,1131 @@@ fn keep_chain_spanning_frames_does_not_
}
#[test]
-fn cjk_hanging_punctuation_uses_frame_edge_without_changing_glyph_size() {
- let k = designcraft_doc::cjk::Kinsoku { name: "Test".into(), no_start: ",".into(), hanging: ",".into(), ..Default::default() };
- let (mut d, sid, fid) = doc_with(
- "AB,",
- Rect::new(0.0, 0.0, 300.0, 100.0),
- ParaAttrs {
- composer: Some(designcraft_doc::Composer::SingleLine),
- kinsoku: Some(Some(k)),
- kinsoku_hang: Some(designcraft_doc::cjk::KinsokuHang::Regular),
+fn satisfiable_keep_chain_still_moves_together_to_the_next_frame() {
+ let text = "One\u{2028}Two\nHeading\nSubheading\nBody";
+ let (mut d, sid, first, second) = two_keep_frames(text);
+ let paras = &mut d.story_mut(sid).unwrap().paras;
+ paras[1].para.keep_with_next = Some(1);
+ paras[2].para.keep_with_next = Some(1);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(!cs.is_overset());
+ assert_eq!(cs.frame(first).unwrap().lines.len(), 2);
+ assert_eq!(cs.frame(second).unwrap().lines.iter().map(|l| l.para).collect::<Vec<_>>(), [1, 2, 3]);
+}
+
+/// OS/2 field offsets: sTypoAscender, sxHeight, sCapHeight.
+const TYPO_ASCENDER: usize = 68;
+const X_HEIGHT: usize = 86;
+const CAP_HEIGHT: usize = 88;
+
+/// Source Sans 3 Regular (1000 units per em; OS/2 typo ascender = hhea ascender = 1000, cap height
+/// 660, x height 486) renamed to `family` (13 characters, the length of "Source Sans 3"), with the
+/// OS/2 fields at the given offsets set, or without an OS/2 table for `None`.
+fn test_font(family: &str, os2_fields: Option<&[(usize, i16)]>) -> Vec<u8> {
+ let mut b = designcraft_fonts::bundled()[0].to_vec();
+ assert_eq!(family.len(), "Source Sans 3".len());
+ let utf16 = |s: &str| s.encode_utf16().flat_map(u16::to_be_bytes).collect::<Vec<u8>>();
+ for (from, to) in [(utf16("Source Sans 3"), utf16(family)), (b"Source Sans 3".to_vec(), family.as_bytes().to_vec())] {
+ let mut i = 0;
+ while let Some(p) = b[i..].windows(from.len()).position(|w| w == from.as_slice()) {
+ b[i + p..i + p + to.len()].copy_from_slice(&to);
+ i += p + to.len();
+ }
+ }
+ let tables = u16::from_be_bytes([b[4], b[5]]) as usize;
+ let rec = (0..tables).map(|t| 12 + 16 * t).find(|&r| &b[r..r + 4] == b"OS/2").unwrap();
+ match os2_fields {
+ Some(fields) => {
+ let os2 = u32::from_be_bytes(b[rec + 8..rec + 12].try_into().unwrap()) as usize;
+ for &(at, v) in fields {
+ b[os2 + at..os2 + at + 2].copy_from_slice(&v.to_be_bytes());
+ }
+ }
+ // Still sorted between its neighbours, so the table directory stays valid.
+ None => b[rec..rec + 4].copy_from_slice(b"OS/1"),
+ }
+ b
+}
+
+/// [`test_font`] with OS/2 `sTypoAscender` set to `typo_ascender`, or without OS/2 for `None`.
+fn typo_test_font(family: &str, typo_ascender: Option<i16>) -> Vec<u8> {
+ test_font(family, typo_ascender.map(|v| [(TYPO_ASCENDER, v)]).as_ref().map(|f| f.as_slice()))
+}
+
+/// First baseline (frame space) of a 20 pt line in `family` in a frame at y = 36 with a 4 pt top
+/// inset, set up by `opts`.
+fn first_baseline_in(family: &str, opts: impl Fn(&mut designcraft_doc::TextFrameOptions)) -> f64 {
+ first_baseline_in_dir(family, false, opts)
+}
+
+/// [`first_baseline_in`] in a vertical story when `vertical`.
+fn first_baseline_in_dir(family: &str, vertical: bool, opts: impl Fn(&mut designcraft_doc::TextFrameOptions)) -> f64 {
+ let (mut d, sid, fid) = doc_with("Hxg Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());
+ d.story_mut(sid).unwrap().format_chars(0..7, |f| {
+ f.over.font_family = Some(family.into());
+ f.over.font_style = Some("Regular".into());
+ f.over.size = Some(20.0);
+ });
+ d.story_mut(sid).unwrap().vertical = vertical;
+ let tf = d.item_mut(fid).unwrap().text_frame_mut().unwrap();
+ tf.options.inset = [4.0, 0.0, 0.0, 0.0];
+ opts(&mut tf.options);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ cs.frames[0].lines[0].baseline
+}
+
+#[test]
+fn ascent_first_baseline_uses_the_typographic_ascender() {
+ use designcraft_doc::FirstBaseline;
+ let db = designcraft_fonts::FontDb::global();
+ db.add_font(typo_test_font("TypoAscent 07", Some(700)));
+ let face = db.face("TypoAscent 07", "Regular");
+ assert_eq!(face.family, "TypoAscent 07");
+ assert_eq!((face.ascent, face.typo_ascent), (1000.0, 700.0), "hhea 1 em, typo 0.7 em");
+ let top = 36.0 + 4.0;
+ let at = |kind: FirstBaseline, min: f64| {
+ first_baseline_in("TypoAscent 07", |o| {
+ o.first_baseline = kind;
+ o.first_baseline_min = min;
+ })
+ };
+ let close = |a: f64, b: f64| (a - b).abs() < 0.01;
+ // Ascent: top + typo ascender (0.7 em of 20 pt), not the hhea ascender (1 em).
+ assert!(close(at(FirstBaseline::Ascent, 0.0), top + 14.0), "{}", at(FirstBaseline::Ascent, 0.0));
+ // The minimum offset still wins when it is larger.
+ assert!(close(at(FirstBaseline::Ascent, 18.0), top + 18.0));
+ assert!(close(at(FirstBaseline::Ascent, 10.0), top + 14.0));
+ // The other kinds don't use it.
+ assert!(close(at(FirstBaseline::CapHeight, 0.0), top + 0.660 * 20.0));
+ assert!(close(at(FirstBaseline::XHeight, 0.0), top + 0.486 * 20.0));
+ assert!(close(at(FirstBaseline::Leading, 0.0), top + 24.0));
+ assert!(close(at(FirstBaseline::Fixed, 0.0), top));
+ // A mixed first line takes its tallest typographic ascender: 0.7 × 20 pt beats 1 em × 10 pt …
+ let (mut d, sid, fid) = doc_with("Hxg Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());
+ let st = d.story_mut(sid).unwrap();
+ st.format_chars(0..3, |f| {
+ f.over.font_family = Some("TypoAscent 07".into());
+ f.over.size = Some(20.0);
+ });
+ st.format_chars(3..7, |f| {
+ f.over.font_family = Some("Source Sans 3".into());
+ f.over.size = Some(10.0);
+ });
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.inset = [4.0, 0.0, 0.0, 0.0];
+ let first = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline;
+ assert!(close(first(&d), top + 14.0), "{}", first(&d));
+ // … and 1 em × 16 pt beats it.
+ d.story_mut(sid).unwrap().format_chars(3..7, |f| f.over.size = Some(16.0));
+ assert!(close(first(&d), top + 16.0), "{}", first(&d));
+}
+
+#[test]
+fn ascent_first_baseline_falls_back_to_the_ascent_without_a_usable_typo_ascender() {
+ let db = designcraft_fonts::FontDb::global();
+ // No OS/2 table, a negative and an absurd typo ascender: the (hhea) ascent, 1 em.
+ for (family, typo) in [("TypoAscentNoO", None), ("TypoAscentNeg", Some(-300)), ("TypoAscentBig", Some(i16::MAX))] {
+ db.add_font(typo_test_font(family, typo));
+ let face = db.face(family, "Regular");
+ assert_eq!(face.family, family);
+ assert_eq!(face.typo_ascent, face.ascent, "{family}");
+ let b = first_baseline_in(family, |_| {});
+ assert!((b - (36.0 + 4.0 + 20.0)).abs() < 0.01, "{family}: {b}");
+ }
+}
+
+#[test]
+fn vertical_frames_keep_the_ascent_first_baseline() {
+ let db = designcraft_fonts::FontDb::global();
+ db.add_font(typo_test_font("TypoAscentVrt", Some(700)));
+ let b = first_baseline_in_dir("TypoAscentVrt", true, |o| {
+ o.inset = [0.0; 4];
+ });
+ // Composed in the turned box (no inset): the hhea ascent, 1 em of 20 pt.
+ assert!((b - 20.0).abs() < 0.01, "{b}");
+}
+
+#[test]
+fn a_visible_frame_stroke_insets_the_text() {
+ use designcraft_doc::{Stroke, StrokeAlign};
+ let line = |stroke: Option<(StrokeAlign, &str)>| {
+ let (mut d, sid, fid) = doc_with("Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());
+ let it = d.item_mut(fid).unwrap();
+ if let Some((align, swatch)) = stroke {
+ it.stroke = Stroke { weight: 4.0, align, swatch: swatch.into(), ..Stroke::default() };
+ }
+ it.text_frame_mut().unwrap().options.inset = [4.0; 4];
+ let l = &compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0];
+ (l.baseline, l.x0, l.x1)
+ };
+ let black = designcraft_color::swatch::BLACK;
+ let (b, x0, x1) = line(None);
+ // The part of the 4 pt stroke inside the frame: half of it centred, all of it inside, none
+ // outside or without a colour; on the left and right as on the top.
+ for (stroke, d) in [
+ ((StrokeAlign::Center, black), 2.0),
+ ((StrokeAlign::Inside, black), 4.0),
+ ((StrokeAlign::Outside, black), 0.0),
+ ((StrokeAlign::Inside, designcraft_color::swatch::NONE), 0.0),
+ ] {
+ let (sb, sx0, sx1) = line(Some(stroke));
+ assert!((sb - (b + d)).abs() < 1e-6, "{stroke:?}: baseline {sb} vs {b}");
+ assert!((sx0 - (x0 + d)).abs() < 1e-6 && (sx1 - (x1 - d)).abs() < 1e-6, "{stroke:?}: {sx0}..{sx1} vs {x0}..{x1}");
+ }
+}
+
+#[test]
+fn list_labels_do_not_raise_the_ascent_first_baseline() {
+ use designcraft_doc::{CharAttrs, ListType};
+ // The paragraph's own character size (the label's) is 40 pt; its text is 10 pt (Source Sans 3:
+ // typo ascender 1 em).
+ let line = |text: &str, list: ListType| {
+ let (mut d, sid, _) = doc_with(text, Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs { list_type: Some(list), ..Default::default() });
+ let st = d.story_mut(sid).unwrap();
+ for p in &mut st.paras {
+ p.chars = CharAttrs { font_family: Some("Source Sans 3".into()), size: Some(40.0), ..Default::default() };
+ }
+ st.format_chars(0..text.len(), |f| f.over.size = Some(10.0));
+ let l = compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].clone();
+ (l.baseline, l.ascent, l.leading)
+ };
+ let (b, asc, lead) = line("Hxg Hxg", ListType::None);
+ // 1 em of the 10 pt text below the frame top.
+ assert!((b - 46.0).abs() < 0.01, "{b}");
+ for list in [ListType::Bullets, ListType::Numbers] {
+ let (lb, lasc, llead) = line("Hxg Hxg", list);
+ assert!((lb - b).abs() < 1e-6, "{list:?}: {lb} vs {b}");
+ // The 40 pt label still sets the line's ascent and leading.
+ assert!(lasc > asc + 20.0 && (llead - 48.0).abs() < 1e-6 && (lead - 12.0).abs() < 1e-6, "{list:?}: {lasc} {asc} {llead} {lead}");
+ }
+ // An empty bulleted paragraph sits like an empty paragraph.
+ let (eb, _, _) = line("", ListType::None);
+ let (ebl, _, _) = line("", ListType::Bullets);
+ assert!((ebl - eb).abs() < 1e-6, "{ebl} vs {eb}");
+}
+
+#[test]
+fn spaces_count_toward_the_ascent_first_baseline() {
+ // 10 pt text with a 40 pt space between its words (Source Sans 3: typo ascender 1 em).
+ let (mut d, sid, _) = doc_with("Hxg Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());
+ let st = d.story_mut(sid).unwrap();
+ st.format_chars(0..7, |f| {
+ f.over.font_family = Some("Source Sans 3".into());
+ f.over.size = Some(10.0);
+ });
+ st.format_chars(3..4, |f| f.over.size = Some(40.0));
+ let l = &compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0];
+ assert!((l.baseline - (36.0 + 40.0)).abs() < 0.01, "{}", l.baseline);
+}
+
+#[test]
+fn vertical_scale_does_not_move_the_ascent_first_baseline() {
+ let db = designcraft_fonts::FontDb::global();
+ db.add_font(typo_test_font("TypoAscentVSc", Some(700)));
+ let line = |v_scale: f64| {
+ let (mut d, sid, fid) = doc_with("Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());
+ d.story_mut(sid).unwrap().format_chars(0..3, |f| {
+ f.over.font_family = Some("TypoAscentVSc".into());
+ f.over.size = Some(20.0);
+ f.over.v_scale = Some(v_scale);
+ });
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.inset = [4.0, 0.0, 0.0, 0.0];
+ let l = &compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0];
+ (l.baseline, l.ascent)
+ };
+ let ((b100, a100), (b200, a200)) = (line(1.0), line(2.0));
+ // The typo ascender of the nominal size (0.7 × 20 pt) at 100 % and at 200 %.
+ assert!((b100 - (36.0 + 4.0 + 14.0)).abs() < 0.01, "{b100}");
+ assert!((b200 - b100).abs() < 0.01, "{b200} vs {b100}");
+ // The line box keeps the scaled ascent.
+ assert!((a100 - 20.0).abs() < 0.01 && (a200 - 40.0).abs() < 0.01, "{a100} {a200}");
+}
+
+#[test]
+fn cap_height_and_x_height_first_baselines_use_the_fonts_cap_and_x_heights() {
+ use designcraft_doc::FirstBaseline;
+ let db = designcraft_fonts::FontDb::global();
+ db.add_font(test_font("CapXHeight 01", Some(&[(CAP_HEIGHT, 500), (X_HEIGHT, 300)])));
+ let face = db.face("CapXHeight 01", "Regular");
+ assert_eq!(face.family, "CapXHeight 01");
+ assert_eq!((face.ascent, face.cap_height, face.x_height), (1000.0, 500.0, 300.0));
+ let top = 36.0 + 4.0;
+ let at = |kind: FirstBaseline, min: f64| {
+ first_baseline_in("CapXHeight 01", |o| {
+ o.first_baseline = kind;
+ o.first_baseline_min = min;
+ })
+ };
+ let close = |a: f64, b: f64| (a - b).abs() < 0.01;
+ // Cap height 0.5 em and x height 0.3 em of 20 pt, not 0.72 / 0.5 of the 1 em ascent.
+ assert!(close(at(FirstBaseline::CapHeight, 0.0), top + 10.0), "{}", at(FirstBaseline::CapHeight, 0.0));
+ assert!(close(at(FirstBaseline::XHeight, 0.0), top + 6.0), "{}", at(FirstBaseline::XHeight, 0.0));
+ // The minimum offset still wins when it is larger.
+ assert!(close(at(FirstBaseline::CapHeight, 12.0), top + 12.0));
+ assert!(close(at(FirstBaseline::XHeight, 5.0), top + 6.0));
+ // Vertical scale and a raised baseline count, as for the ascent.
+ let (mut d, sid, fid) = doc_with("Hxg Hxg", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());
+ let st = d.story_mut(sid).unwrap();
+ st.format_chars(0..7, |f| {
+ f.over.font_family = Some("CapXHeight 01".into());
+ f.over.size = Some(20.0);
+ f.over.v_scale = Some(1.5);
+ });
+ st.format_chars(4..5, |f| f.over.baseline_shift = Some(1.0));
+ let tf = d.item_mut(fid).unwrap().text_frame_mut().unwrap();
+ tf.options.inset = [4.0, 0.0, 0.0, 0.0];
+ tf.options.first_baseline = FirstBaseline::CapHeight;
+ let first = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].baseline;
+ assert!(close(first(&d), top + 15.0 + 1.0), "{}", first(&d));
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.first_baseline = FirstBaseline::XHeight;
+ assert!(close(first(&d), top + 9.0 + 1.0), "{}", first(&d));
+}
+
+#[test]
+fn cap_height_and_x_height_fall_back_without_usable_os2_values() {
+ use designcraft_doc::FirstBaseline;
+ let db = designcraft_fonts::FontDb::global();
+ // No OS/2 table, zero / negative and absurd values: the top of the H (0.656 em) and of the x
+ // (0.486 em).
+ let zero: &[(usize, i16)] = &[(CAP_HEIGHT, 0), (X_HEIGHT, -40)];
+ let big: &[(usize, i16)] = &[(CAP_HEIGHT, i16::MAX), (X_HEIGHT, i16::MAX)];
+ for (family, fields) in [("CapXHeightNoO", None), ("CapXHeightNeg", Some(zero)), ("CapXHeightBig", Some(big))] {
+ db.add_font(test_font(family, fields));
+ let face = db.face(family, "Regular");
+ assert_eq!(face.family, family);
+ assert_eq!((face.cap_height, face.x_height), (656.0, 486.0), "{family}");
+ let cap = first_baseline_in(family, |o| o.first_baseline = FirstBaseline::CapHeight);
+ let x = first_baseline_in(family, |o| o.first_baseline = FirstBaseline::XHeight);
+ assert!((cap - (40.0 + 13.12)).abs() < 0.01 && (x - (40.0 + 9.72)).abs() < 0.01, "{family}: {cap} {x}");
+ }
+}
+
+#[test]
+fn vertical_frames_keep_the_cap_height_and_x_height_first_baselines() {
+ use designcraft_doc::FirstBaseline;
+ let db = designcraft_fonts::FontDb::global();
+ db.add_font(test_font("CapXHeightVrt", Some(&[(CAP_HEIGHT, 500), (X_HEIGHT, 300)])));
+ let at = |kind: FirstBaseline| {
+ first_baseline_in_dir("CapXHeightVrt", true, |o| {
+ o.first_baseline = kind;
+ o.inset = [0.0; 4];
+ })
+ };
+ // 0.72 and 0.5 of the 1 em ascent of 20 pt.
+ assert!((at(FirstBaseline::CapHeight) - 14.4).abs() < 0.01, "{}", at(FirstBaseline::CapHeight));
+ assert!((at(FirstBaseline::XHeight) - 10.0).abs() < 0.01, "{}", at(FirstBaseline::XHeight));
+}
+
+// ---------- drop caps ----------
+
+/// `text` set 10 pt on 12 pt leading in a 300 pt measure, with `para` on top.
+fn drop_doc(text: &str, para: ParaAttrs) -> (Document, StoryId, ItemId) {
+ drop_doc_in(text, Rect::new(0.0, 0.0, 300.0, 1000.0), para)
+}
+
+fn drop_doc_in(text: &str, rect: Rect, para: ParaAttrs) -> (Document, StoryId, ItemId) {
+ let (mut d, sid, fid) = doc_with(text, rect, para);
+ for p in &mut d.story_mut(sid).unwrap().paras {
+ p.chars = designcraft_doc::CharAttrs { size: Some(10.0), leading: Some(designcraft_doc::Leading::Points(12.0)), ..Default::default() };
+ }
+ (d, sid, fid)
+}
+
+fn drop_cap(lines: u32, chars: u32) -> ParaAttrs {
+ ParaAttrs { drop_cap_lines: Some(lines), drop_cap_chars: Some(chars), ..Default::default() }
+}
+
+/// Cap height of a placed glyph, in points.
+fn cap_of(g: &PlacedGlyph) -> f64 {
+ g.face.cap_height * g.sy
+}
+
+/// x of the first glyph of `l` set from story byte `from` on.
+fn text_x(l: &Line, from: usize) -> f64 {
+ l.glyphs.iter().find(|g| g.len > 0 && g.byte >= from).map(|g| g.x).unwrap()
+}
+
+#[test]
+fn drop_cap_spans_lines_and_indents_them() {
+ let text = [LOREM; 2].join(" ");
+ let (plain, psid, _) = drop_doc(&text, ParaAttrs::default());
+ let plain = compose_story(&plain, psid, &ComposeOptions::default());
+ let (d, sid, _) = drop_doc(&text, drop_cap(3, 1));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ let pl = all_lines(&plain);
+ assert!(lines.len() > 4);
+ // Baselines don't move.
+ for (k, l) in lines.iter().enumerate() {
+ assert!((l.baseline - (pl[0].baseline + 12.0 * k as f64)).abs() < 1e-6, "line {k} at {}", l.baseline);
+ }
+ // The drop cap: the first glyph, on line 1, its baseline on line 3's and its cap top on line 1's.
+ let dc = &lines[0].glyphs[0];
+ assert_eq!((dc.byte, dc.len), (0, 1));
+ assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6, "drop cap baseline {}", lines[0].baseline + dc.y);
+ let body = lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap();
+ let top = lines[2].baseline - cap_of(dc);
+ assert!((top - (lines[0].baseline - cap_of(body))).abs() < 0.01, "cap top {top}");
+ assert!(dc.sy > body.sy * 3.0);
+ // Lines 1–3 start after it, line 4 at the frame edge.
+ let right = dc.x + dc.adv;
+ assert!(right > 20.0);
+ for l in &lines[..3] {
+ assert!(text_x(l, 1) >= right - 1e-6, "{} < {right}", text_x(l, 1));
+ assert!(l.end_x <= l.x1 + 0.5);
+ }
+ assert!(text_x(lines[3], 1) < 0.5);
+ // The text stays in order: the drop cap starts line 1 (exports and caret read it there).
+ assert_eq!(lines[0].range.start, 0);
+}
+
+#[test]
+fn tab_beside_a_drop_cap_is_measured_from_the_drop_cap() {
+ // The line breaker measures a tab from where the line starts, which beside a drop cap is
+ // after the drop cap: measured from the frame edge, the tab looks wider and the line breaks
+ // a word early.
+ let stop = designcraft_doc::TabStop { position: 100.0, align: TabAlign::Left, leader: String::new(), align_on: String::new() };
+ let para = ParaAttrs { tabs: Some(vec![stop]), hyphenate: Some(false), ..drop_cap(3, 1) };
+ let text = format!("Wort\t{LOREM}");
+ let (d, sid, _) = drop_doc(&text, para);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ let space = |g: &PlacedGlyph| g.len > 0 && text.get(g.byte..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace);
+ let right = lines[0].glyphs.iter().filter(|g| g.visible && !space(g)).map(|g| g.x + g.adv).fold(0.0, f64::max);
+ assert!(right <= lines[0].x1 + 0.01, "line 1 ends at {right}, past {}", lines[0].x1);
+ let word: f64 = lines[1].glyphs.iter().filter(|g| g.len > 0).take_while(|g| !space(g)).map(|g| g.adv).sum();
+ assert!(right + word + 4.0 > lines[0].x1, "line 2's first word ({word} pt) fits after line 1's end at {right} (edge {})", lines[0].x1);
+}
+
+#[test]
+fn warichu_on_a_drop_cap_line_leaves_the_drop_cap_alone() {
+ let text = format!("WABCDEFGH {LOREM}");
+ let (mut d, sid, _) = drop_doc(&text, drop_cap(3, 1));
+ let plain = compose_story(&d, sid, &ComposeOptions::default());
+ let plain_dc = plain.frames[0].lines[0].glyphs[0].clone();
+ // A plain drop cap line has no stacked rows: one selection band, caret on the line.
+ let pl = &plain.frames[0].lines[0];
+ assert_eq!(highlight_quads(pl, 0, 12, false).len(), 1);
+ assert_eq!(caret(&plain, 1).map(|c| (c.2, c.3)), Some((pl.baseline, pl.ascent)));
+ d.story_mut(sid).unwrap().format_chars(1..9, |f| {
+ f.over.warichu = Some(true);
+ f.over.warichu_alignment = Some(designcraft_doc::cjk::WarichuAlignment::Left);
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let dc = &l.glyphs[0];
+ assert_eq!((dc.byte, dc.x, dc.y, dc.sy), (0, plain_dc.x, plain_dc.y, plain_dc.sy), "the drop cap is not part of the note");
+ let at = |byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).unwrap();
+ let (top, bot, after) = (at(1), at(5), at(10));
+ assert!(bot.y - top.y > 1.0, "the note is stacked in two rows");
+ assert!(top.x >= dc.x + dc.adv - 1e-6, "the note starts after the drop cap");
+ assert!((after.x - (at(8).x + at(8).adv + at(9).adv)).abs() < 1e-3, "the line closes up after the note");
+ // The caret: in the drop cap as tall as it, on a note row that row's baseline, after the
+ // note the parent line's.
+ let dc_box = l.drop_cap.unwrap();
+ assert_eq!(caret(&cs, 0).map(|c| c.2), Some(dc_box.baseline));
+ assert!((caret(&cs, 1).unwrap().2 - (l.baseline + top.y)).abs() < 1e-6);
+ assert_eq!(caret(&cs, 10).map(|c| (c.2, c.3)), Some((l.baseline, l.ascent)));
+ let click = |g: &PlacedGlyph| hit(&cs, 0, designcraft_geom::Point::new(g.x + g.adv * 0.25, l.baseline + g.y)).unwrap();
+ assert_eq!((click(top), click(bot), click(after)), (1, 5, 10));
+ // Selecting the drop cap and the note: the drop cap's band and one per row.
+ assert_eq!(highlight_quads(l, 0, 9, false).len(), 3);
+}
+
+#[test]
+fn drop_cap_of_two_characters_as_a_local_override() {
+ let (d, sid, _) = drop_doc(LOREM, drop_cap(2, 2));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ let (a, b) = (&lines[0].glyphs[0], &lines[0].glyphs[1]);
+ assert_eq!((a.byte, b.byte), (0, 1));
+ let body = lines[0].glyphs.iter().find(|g| g.byte == 2).unwrap();
+ for g in [a, b] {
+ assert!((lines[0].baseline + g.y - lines[1].baseline).abs() < 1e-6);
+ assert!(g.sy > body.sy * 1.5);
+ }
+ assert!((b.x - (a.x + a.adv)).abs() < 1e-6, "the drop cap characters sit side by side");
+ let right = b.x + b.adv;
+ assert!(text_x(lines[0], 2) >= right - 1e-6 && text_x(lines[1], 2) >= right - 1e-6);
+ assert!(text_x(lines[2], 2) < 0.5);
+}
+
+#[test]
+fn short_paragraph_keeps_its_drop_cap_and_the_next_paragraph_is_not_indented() {
+ let (mut d, sid, _) = drop_doc(&format!("Short.\n{LOREM}"), drop_cap(3, 1));
+ d.story_mut(sid).unwrap().paras[1].para = ParaAttrs::default();
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert_eq!(lines.iter().filter(|l| l.para == 0).count(), 1);
+ let dc = &lines[0].glyphs[0];
+ // Still three lines tall (it may overlap the next paragraph, which isn't indented).
+ assert!((dc.y - 24.0).abs() < 1e-6, "{}", dc.y);
+ assert!(text_x(lines[1], 7) < 0.5);
+}
+
+#[test]
+fn drop_cap_counts_code_points_without_splitting_clusters_and_clamps_to_the_paragraph() {
+ // Four characters: a letter, its combining mark, another letter and a no-break space.
+ let (d, sid, _) = drop_doc("A\u{301}B\u{a0}rest of the words", drop_cap(2, 4));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let big: Vec<usize> = l.glyphs.iter().filter(|g| g.len > 0 && g.y > 1.0).map(|g| g.byte).collect();
+ assert!(big.contains(&0) && big.contains(&3), "{big:?}");
+ assert!(big.iter().all(|b| *b < 6), "the r isn't part of it: {big:?}");
+ // One character that has a combining mark after it takes the mark too.
+ let (d, sid, _) = drop_doc("e\u{301}tude and more words", drop_cap(2, 1));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let big: Vec<usize> = l.glyphs.iter().filter(|g| g.y > 1.0).map(|g| g.byte).collect();
+ assert!(!big.is_empty() && big.iter().all(|b| *b < 3), "{big:?}");
+ assert!(l.glyphs.iter().any(|g| g.byte == 0 && g.y > 1.0));
+ // More characters than the paragraph has: all of them, and nothing of the next paragraph.
+ let (mut d, sid, _) = drop_doc("Hi\nNext", drop_cap(2, 50));
+ d.story_mut(sid).unwrap().paras[1].para = ParaAttrs::default();
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert!(lines[0].glyphs.iter().filter(|g| g.len > 0).all(|g| g.y > 1.0));
+ assert!(lines[1].glyphs.iter().all(|g| g.y.abs() < 1e-6));
+}
+
+#[test]
+fn hostile_drop_cap_values_do_not_panic() {
+ for (lines, chars) in [(u32::MAX, u32::MAX), (1_000_000, 1), (2, 0), (0, 3)] {
+ let (d, sid, _) = drop_doc(LOREM, drop_cap(lines, chars));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let g = &cs.frames[0].lines[0].glyphs[0];
+ assert!(g.y.is_finite() && g.sy.is_finite() && g.y <= 12.0 * 25.0, "{lines}/{chars}: {}", g.y);
+ }
+ // No lines or no characters: no drop cap.
+ let (d, sid, _) = drop_doc(LOREM, drop_cap(0, 3));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(cs.frames[0].lines[0].glyphs[0].y.abs() < 1e-6);
+}
+
+#[test]
+fn one_line_drop_cap_is_not_enlarged() {
+ let (d, sid, _) = drop_doc(LOREM, drop_cap(1, 1));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let (dc, body) = (&l.glyphs[0], l.glyphs.iter().find(|g| g.byte == 1).unwrap());
+ assert!((cap_of(dc) - cap_of(body)).abs() < 0.01 && dc.y.abs() < 1e-6);
+}
+
+#[test]
+fn drop_cap_stays_with_the_first_line_across_a_column_break() {
+ // Two lines fit a column: line 3 starts the second column, at its edge.
+ let (mut d, sid, fid) = drop_doc_in(&[LOREM; 2].join(" "), Rect::new(0.0, 0.0, 400.0, 30.0), drop_cap(3, 1));
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let ft = &cs.frames[0];
+ let col1: Vec<&Line> = ft.lines.iter().filter(|l| l.column == 1).collect();
+ assert_eq!(ft.lines.iter().filter(|l| l.column == 0).count(), 2, "{:?}", ft.lines.iter().map(|l| l.column).collect::<Vec<_>>());
+ let dc = &ft.lines[0].glyphs[0];
+ assert!((dc.y - 24.0).abs() < 1e-6, "{}", dc.y);
+ assert!(text_x(&ft.lines[1], 1) >= dc.x + dc.adv - 1e-6);
+ assert!((text_x(col1[0], 1) - ft.columns[1].x0).abs() < 0.5);
+}
+
+#[test]
+fn drop_cap_in_right_to_left_paragraphs_is_on_the_right() {
+ let para = ParaAttrs { direction: Some(designcraft_doc::TextDirection::RightToLeft), align: Some(Align::Right), ..drop_cap(2, 1) };
+ let (d, sid, _) = drop_doc(LOREM, para);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ let dc = lines[0].glyphs.iter().find(|g| g.byte == 0).unwrap();
+ assert!((dc.x + dc.adv - 300.0).abs() < 0.5, "{}", dc.x + dc.adv);
+ for l in &lines[..2] {
+ assert!(l.glyphs.iter().filter(|g| g.byte > 0 && g.visible).all(|g| g.x + g.adv <= dc.x + 0.5));
+ }
+ assert!(lines[2].end_x > 299.0 || lines[2].glyphs.iter().any(|g| g.x + g.adv > 299.0));
+}
+
+#[test]
+fn vertical_frames_set_no_drop_cap() {
+ let (mut d, sid, _) = drop_doc(LOREM, drop_cap(3, 1));
+ d.story_mut(sid).unwrap().vertical = true;
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert!(cs.frames[0].lines[0].glyphs[0].y.abs() < 1e-6);
+}
+
+#[test]
+fn drop_cap_takes_its_character_style_and_nested_styles_count_it() {
+ let (mut d, sid, _) = drop_doc(LOREM, ParaAttrs { drop_cap_style: Some("Initial".into()), ..drop_cap(2, 3) });
+ for (name, fill) in [("Initial", "Initial Red"), ("Lead", "Lead Blue")] {
+ std::sync::Arc::make_mut(&mut d.styles).character.push(designcraft_doc::CharacterStyle {
+ name: name.into(),
+ based_on: None,
+ chars: designcraft_doc::CharAttrs { fill: Some(fill.into()), ..Default::default() },
+ shortcut: String::new(),
+ });
+ }
+ let fill = |cs: &ComposedStory, g: &PlacedGlyph| cs.styles[g.style as usize].fill.clone();
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let at = |b: usize| l.glyphs.iter().find(|g| g.byte == b).unwrap();
+ assert_eq!(fill(&cs, at(0)), "Initial Red");
+ assert_eq!(fill(&cs, at(2)), "Initial Red");
+ assert_eq!(fill(&cs, at(3)), "[Black]");
+ // The drop cap's style is a leading "through 1 drop cap" nested style: the nested styles start
+ // after the drop cap.
+ let one = designcraft_doc::NestedStyle { style: "Lead".into(), through: true, count: 1, until: designcraft_doc::NestedUntil::Characters };
+ d.story_mut(sid).unwrap().paras[0].para.nested_styles = Some(vec![one]);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let at = |b: usize| l.glyphs.iter().find(|g| g.byte == b).unwrap();
+ assert_eq!(fill(&cs, at(0)), "Initial Red");
+ assert_eq!((fill(&cs, at(3)), fill(&cs, at(4))), ("Lead Blue".to_string(), "[Black]".to_string()));
+ // A nested style "through 1 drop cap" covers the drop cap; the next one starts after it.
+ let ns = |style: &str, until: designcraft_doc::NestedUntil| designcraft_doc::NestedStyle { style: style.into(), through: true, count: 1, until };
+ d.story_mut(sid).unwrap().paras[0].para = ParaAttrs {
+ nested_styles: Some(vec![ns("Lead", designcraft_doc::NestedUntil::Dropcap), ns("Initial", designcraft_doc::NestedUntil::Words)]),
+ ..drop_cap(2, 3)
+ };
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let at = |b: usize| l.glyphs.iter().find(|g| g.byte == b).unwrap();
+ assert_eq!(fill(&cs, at(0)), "Lead Blue");
+ assert_eq!(fill(&cs, at(2)), "Lead Blue");
+ assert_eq!(fill(&cs, at(3)), "Initial Red", "the second nested style starts after the drop cap");
+ let first_space = LOREM.find(' ').unwrap();
+ assert_eq!(fill(&cs, at(first_space + 1)), "[Black]");
+}
+
+#[test]
+fn drop_cap_caret_and_hit_testing() {
+ let (d, sid, _) = drop_doc(LOREM, drop_cap(3, 1));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ let dc = lines[0].glyphs[0].clone();
+ let drop_box = lines[0].drop_cap.unwrap().rect;
+ assert!(drop_box.y1 > lines[2].baseline - 0.01 && drop_box.y0 < lines[0].baseline - 5.0, "{drop_box:?}");
+ // A click on the lower half of the big letter (beside line 3) is at the drop cap.
+ let y = lines[2].baseline - 2.0;
+ assert_eq!(hit(&cs, 0, Point::new(dc.x + dc.adv * 0.25, y)), Some(0));
+ assert_eq!(hit(&cs, 0, Point::new(dc.x + dc.adv * 0.75, y)), Some(1));
+ // A double click there is on the drop cap's character, not on line 3's text.
+ assert_eq!(hit_char(&cs, 0, Point::new(dc.x + dc.adv * 0.5, y)), Some(0));
+ // The caret before the drop cap is as tall as it; after it, beside line 1's text.
+ let (_, x, bl, asc, _) = caret(&cs, 0).unwrap();
+ assert!((x - dc.x).abs() < 1e-6 && (bl - lines[2].baseline).abs() < 1e-6 && asc > 24.0, "{x} {bl} {asc}");
+ let (_, x, bl, _, _) = caret(&cs, 1).unwrap();
+ assert!(x >= dc.x + dc.adv - 1e-6 && (bl - lines[0].baseline).abs() < 1e-6);
+}
+
+#[test]
+fn drop_cap_on_a_baseline_grid_reaches_down_by_grid_steps() {
+ // Lines on a 15 pt baseline grid (not the 12 pt leading): the drop cap reaches down two grid
+ // steps, to line 3.
+ let (mut d, sid, _) = drop_doc(LOREM, ParaAttrs { grid_align: Some(designcraft_doc::GridAlign::AllLines), ..drop_cap(3, 1) });
+ d.settings.baseline_grid.increment = 15.0;
+ d.settings.baseline_grid.start = 0.0;
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert!((lines[1].baseline - lines[0].baseline - 15.0).abs() < 1e-6);
+ let dc = &lines[0].glyphs[0];
+ assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6);
+ let b = lines[0].drop_cap.unwrap();
+ assert!((b.baseline - lines[2].baseline).abs() < 1e-6 && b.rect.y1 > lines[2].baseline);
+ // Scaled to the grid's line pitch: its cap top is still line 1's.
+ let body = lines[0].glyphs.iter().find(|g| g.byte == 1).unwrap();
+ assert!((lines[2].baseline - cap_of(dc) - (lines[0].baseline - cap_of(body))).abs() < 0.01);
+}
+
+/// A line with a larger auto leading doesn't move the drop cap: it reaches down `lines − 1`
+/// leadings of the text after it, not to where line N is set.
+#[test]
+fn drop_cap_reaches_down_by_the_text_leading_past_a_line_with_larger_leading() {
+ use designcraft_doc::{CharAttrs, Composer, Leading};
+ let text = [LOREM; 2].join(" ");
+ let para = ParaAttrs { composer: Some(Composer::SingleLine), ..drop_cap(3, 1) };
+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 1000.0), para);
+ d.story_mut(sid).unwrap().paras[0].chars = CharAttrs { size: Some(12.0), leading: Some(Leading::Auto), ..Default::default() };
+ // A larger word starts line 2, so lines 2 and 3 are set further down than 2 × 14.4 pt.
+ let start2 = all_lines(&compose_story(&d, sid, &ComposeOptions::default()))[1].range.start;
+ d.story_mut(sid).unwrap().format_chars(start2..start2 + 3, |f| f.over.size = Some(20.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert_eq!(lines[1].range.start, start2);
+ assert!(lines[2].baseline - lines[0].baseline > 2.0 * 14.4 + 5.0, "{} {}", lines[0].baseline, lines[2].baseline);
+ let dc = &lines[0].glyphs[0];
+ assert!((dc.y - 2.0 * 14.4).abs() < 1e-6, "drop cap baseline {} below line 1", dc.y);
+ let b = lines[0].drop_cap.unwrap();
+ assert!((b.baseline - (lines[0].baseline + 2.0 * 14.4)).abs() < 1e-6, "{}", b.baseline);
+}
+
+/// A space after the drop cap is set at its size on its baseline and doesn't widen the indent: the
+/// lines beside it start where its characters end.
+#[test]
+fn space_after_a_drop_cap_does_not_widen_the_indent() {
+ let (d, sid, _) = drop_doc(&format!("In 2003 {LOREM}"), drop_cap(2, 2));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ let (i, n) = (&lines[0].glyphs[0], &lines[0].glyphs[1]);
+ assert_eq!((i.byte, n.byte), (0, 1));
+ let end = n.x + n.adv;
+ for l in &lines[..2] {
+ assert!((text_x(l, 3) - end).abs() < 1e-6, "{} vs {end}", text_x(l, 3));
+ }
+ let space = lines[0].glyphs.iter().find(|g| g.byte == 2).unwrap();
+ assert!((space.sy - n.sy).abs() < 1e-9 && (space.y - n.y).abs() < 1e-9, "the space is set like the drop cap");
+ assert_eq!(lines[0].drop_cap.unwrap().end, 3);
+}
+
+/// A one-line drop cap keeps its characters' own size (a smaller verse number stays smaller), and
+/// the tabs in it advance to the paragraph's tab stops.
+#[test]
+fn one_line_drop_cap_keeps_its_size_and_sets_its_tabs() {
+ let stop = |position, align| designcraft_doc::TabStop { position, align, leader: String::new(), align_on: String::new() };
+ let para = ParaAttrs { tabs: Some(vec![stop(30.0, TabAlign::Right), stop(40.0, TabAlign::Left)]), ..drop_cap(1, 3) };
+ let (mut d, sid, _) = drop_doc(&format!("\t7\t{LOREM}"), para);
+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.size = Some(8.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let at = |b: usize| l.glyphs.iter().find(|g| g.byte == b).unwrap();
+ let (seven, body) = (at(1), at(3));
+ assert!((seven.sy / body.sy - 0.8).abs() < 1e-9, "{} vs {}", seven.sy, body.sy);
+ assert!(seven.y.abs() < 1e-9);
+ assert!((seven.x + seven.adv - 30.0).abs() < 1e-6, "the number ends at the right tab: {}", seven.x + seven.adv);
+ assert!((text_x(l, 3) - 40.0).abs() < 1e-6, "the text starts at the left tab: {}", text_x(l, 3));
+}
+
+/// Right to left, the tabs in a drop cap advance to tab stops measured from the column's right
+/// edge.
+#[test]
+fn right_to_left_drop_cap_sets_its_tabs_from_the_right_edge() {
+ let stop = |position, align| designcraft_doc::TabStop { position, align, leader: String::new(), align_on: String::new() };
+ let para = ParaAttrs {
+ direction: Some(designcraft_doc::TextDirection::RightToLeft),
+ align: Some(Align::Right),
+ tabs: Some(vec![stop(30.0, TabAlign::Right), stop(40.0, TabAlign::Left)]),
+ ..drop_cap(1, 3)
+ };
+ let (d, sid, _) = drop_doc(&format!("\t7\t{LOREM}"), para);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let seven = l.glyphs.iter().find(|g| g.byte == 1).unwrap();
+ // The 300 pt column's right edge is at 300: the number's far (left) end is 30 pt from it.
+ assert!((seven.x - 270.0).abs() < 1e-6, "the number ends at the right tab: {}", seven.x);
+ // The text beside it starts at the left tab, 40 pt from the edge.
+ let right = l.glyphs.iter().filter(|g| g.byte >= 3 && g.visible).map(|g| g.x + g.adv).fold(f64::NEG_INFINITY, f64::max);
+ assert!(right <= 260.0 + 1e-6 && right > 255.0, "text ends at {right}");
+}
+
+/// A rule in Text Color takes the colour of the paragraph's text: the first character's for the
+/// rule above, the last character's for the rule below. A swatch colour is used as is.
+#[test]
+fn text_color_rules_follow_the_text() {
+ use designcraft_doc::{CharAttrs, CharFormat, Rule, TEXT_COLOR};
+ let rule = Rule { on: true, weight: 2.0, ..Default::default() };
+ let para = ParaAttrs { rule_above: Some(rule.clone()), rule_below: Some(rule.clone()), ..Default::default() };
+ let (mut d, sid, fid) = doc_with("Red then blue", Rect::new(0.0, 0.0, 300.0, 200.0), para);
+ {
+ let s = d.story_mut(sid).unwrap();
+ s.format_chars(0..3, |f: &mut CharFormat| f.over.merge(&CharAttrs { fill: Some("Red".into()), fill_tint: Some(0.5), ..Default::default() }));
+ s.format_chars(9..13, |f: &mut CharFormat| f.over.fill = Some("Blue".into()));
+ }
+ let decos = |d: &Document| {
+ let cs = compose_story(d, sid, &ComposeOptions::default());
+ let mut v: Vec<(f64, String, f32)> = cs.frame(fid).unwrap().decos.iter().map(|dc| (dc.rect.y0, dc.color.clone(), dc.tint)).collect();
+ v.sort_by(|a, b| a.0.total_cmp(&b.0));
+ v.into_iter().map(|(_, c, t)| (c, t)).collect::<Vec<_>>()
+ };
+ assert_eq!(rule.color, TEXT_COLOR);
+ assert_eq!(decos(&d), vec![("Red".to_string(), 0.5), ("Blue".to_string(), 1.0)]);
+ let swatch = Rule { color: "[Black]".into(), tint: 0.3, ..rule };
+ d.story_mut(sid).unwrap().paras[0].para.rule_above = Some(swatch);
+ assert_eq!(decos(&d)[0], ("[Black]".to_string(), 0.3));
+}
+
+/// Align Left Edge (InDesign's default): the drop cap's origin moves left by its first letter's
+/// left side bearing so its ink starts at the indent, and the lines beside it start where its
+/// advance ends. Measured case: 14/18 text, two lines, one character.
+#[test]
+fn drop_cap_aligns_its_left_edge() {
+ let text = format!("Once {LOREM}");
+ let compose = |align: Option<bool>| {
+ let para = ParaAttrs { left_indent: Some(10.0), drop_cap_align_left: align, ..drop_cap(2, 1) };
+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 1000.0), para);
+ d.story_mut(sid).unwrap().paras[0].chars =
+ designcraft_doc::CharAttrs { size: Some(14.0), leading: Some(designcraft_doc::Leading::Points(18.0)), ..Default::default() };
+ compose_story(&d, sid, &ComposeOptions::default())
+ };
+ use designcraft_geom::Shape as _;
+ let ink_left = |g: &PlacedGlyph| g.x + designcraft_fonts::FontDb::global().outline(g.face.get(), g.gid).bounding_box().x0 * g.sx;
+ for align in [None, Some(true), Some(false)] {
+ let cs = compose(align);
+ let lines = all_lines(&cs);
+ let dc = &lines[0].glyphs[0];
+ assert_eq!(dc.byte, 0);
+ let lsb = ink_left(dc) - dc.x;
+ assert!(lsb > 0.5, "the O has a visible side bearing at this size: {lsb}");
+ if align != Some(false) {
+ assert!((ink_left(dc) - 10.0).abs() < 1e-6, "{align:?}: ink at {}", ink_left(dc));
+ } else {
+ assert!((dc.x - 10.0).abs() < 1e-6, "origin at {}", dc.x);
+ }
+ for l in &lines[..2] {
+ assert!((text_x(l, 1) - (dc.x + dc.adv)).abs() < 1e-6, "{align:?}: {} vs {}", text_x(l, 1), dc.x + dc.adv);
+ }
+ assert!((text_x(lines[2], 1) - 10.0).abs() < 1e-6);
+ }
+}
+
+#[test]
+fn caret_follows_spaces_typed_at_the_end() {
+ let x_at_end = |text: &str| {
+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let end_x = cs.frames[0].lines[0].end_x;
+ (caret(&cs, text.len()).unwrap().1, end_x)
+ };
+ let (word, word_end) = x_at_end("Word");
+ let (one, one_end) = x_at_end("Word ");
+ let (two, _) = x_at_end("Word ");
+ assert!(one > word + 1.0 && two > one + 1.0, "{word} {one} {two}");
+ // The spaces don't count for the line's own length (alignment, justification).
+ assert!((one_end - word_end).abs() < 1e-9);
+ // Wrapped lines keep their spaces too: a caret between two spaces at a line end sits after
+ // the first one.
+ let text = "Lorem ipsum dolor sit amet consectetur";
+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 140.0, 100.0), ParaAttrs::default());
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l0 = &cs.frames[0].lines[0];
+ if l0.range.end == text.find("consectetur").unwrap() {
+ let mid = text.find(" ").unwrap() + 1;
+ assert!(caret(&cs, mid).unwrap().1 > l0.end_x, "between the trailing spaces");
+ }
+}
+
+#[test]
+fn colour_change_keeps_kerning_and_ligatures_keep_colour() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 200.0), lid, "ayay", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.font_style = Some("Bold".into()));
+ let line = |d: &Document| compose_story(d, sid, &ComposeOptions::default()).frames[0].lines[0].clone();
+ let xs = |l: &Line| l.glyphs.iter().map(|g| (g.x, g.adv)).collect::<Vec<_>>();
+ let kerned = line(&d);
+ // The font kerns "ay" (otherwise this test proves nothing).
+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::None));
+ assert_ne!(xs(&line(&d)), xs(&kerned), "Source Serif 4 Bold kerns a–y");
+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::Metrics));
+ // Colour the first "a": positions are unchanged, only its style differs.
+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.fill = Some("Cyan".into()));
+ let coloured = line(&d);
+ assert_eq!(xs(&coloured), xs(&kerned), "a colour change must not change spacing");
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let fill = |l: &Line, i: usize| cs.styles[l.glyphs[i].style as usize].fill.clone();
+ assert_eq!(fill(&coloured, 0), "Cyan");
+ assert_ne!(fill(&coloured, 1), "Cyan");
+
+ // A ligature never swallows a differently coloured letter: the "i" of "fi" keeps its colour.
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 300.0, 400.0, 400.0), lid, "fifi", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().format_chars(1..2, |f| f.over.fill = Some("Cyan".into()));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let l = &cs.frames[0].lines[0];
+ let at = |b: usize| l.glyphs.iter().find(|g| g.len > 0 && g.byte <= b && b < g.byte + g.len).map(|g| cs.styles[g.style as usize].fill.clone());
+ assert_eq!(at(1).as_deref(), Some("Cyan"));
+ assert_ne!(at(2).as_deref(), Some("Cyan"));
+}
+
+/// The emphasis mark drawn over the text only paints: a change of kenten character keeps the
+/// kerning across it.
+#[test]
+fn kenten_character_change_keeps_kerning() {
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(100.0, 100.0, 400.0, 200.0), lid, "ayay", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().format_chars(0..4, |f| {
+ f.over.font_style = Some("Bold".into());
+ f.over.kenten = Some(true);
+ });
+ let xs = |d: &Document| {
+ let cs = compose_story(d, sid, &ComposeOptions::default());
+ cs.frames[0].lines[0].glyphs.iter().filter(|g| g.len > 0).map(|g| (g.byte, g.x, g.adv)).collect::<Vec<_>>()
+ };
+ let kerned = xs(&d);
+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::None));
+ assert_ne!(xs(&d), kerned, "Source Serif 4 Bold kerns a–y");
+ d.story_mut(sid).unwrap().format_chars(0..4, |f| f.over.kerning = Some(designcraft_doc::Kerning::Metrics));
+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.kenten_character = Some("●".into()));
+ assert_eq!(xs(&d), kerned, "a kenten character change must not change spacing");
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let mark = |b: usize| {
+ cs.frames[0].lines[0].glyphs.iter().find(|g| g.len > 0 && g.byte == b).map(|g| cs.styles[g.style as usize].kenten_character.clone())
+ };
+ assert_eq!((mark(0).as_deref(), mark(1).as_deref()), (Some("●"), Some("")));
+}
+
+#[test]
+fn empty_paragraph_takes_its_marks_format() {
+ // Paragraph style text is 12 pt (auto leading 14.4); every character, including the empty
+ // paragraph's mark, is 6 pt with 8 pt leading: the empty line must advance 8, not 14.4.
+ let text = "One\n\nTwo";
+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 200.0, 200.0), ParaAttrs::default());
+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| {
+ f.over.size = Some(6.0);
+ f.over.leading = Some(designcraft_doc::Leading::Points(8.0));
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert_eq!(lines.len(), 3);
+ assert!((lines[1].baseline - lines[0].baseline - 8.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[1].baseline);
+ assert!((lines[2].baseline - lines[1].baseline - 8.0).abs() < 1e-6, "{} {}", lines[1].baseline, lines[2].baseline);
+}
+
+#[test]
+fn empty_paragraph_uses_its_own_mark_not_the_previous_one() {
+ // "One\n" is 20 pt; the empty paragraph's mark (byte 4) and "Two" are 6 pt with 8 pt leading.
+ // The format run boundary sits exactly at the empty paragraph's start: its line must take the
+ // 8 pt leading of its own mark, not the previous paragraph's 20 pt (auto 24) mark.
+ let text = "One\n\nTwo";
+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 200.0, 200.0), ParaAttrs::default());
+ let st = d.story_mut(sid).unwrap();
+ st.format_chars(0..4, |f| f.over.size = Some(20.0));
+ st.format_chars(4..text.len(), |f| {
+ f.over.size = Some(6.0);
+ f.over.leading = Some(designcraft_doc::Leading::Points(8.0));
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert_eq!(lines.len(), 3);
+ assert!((lines[1].baseline - lines[0].baseline - 8.0).abs() < 1e-6, "{} {}", lines[0].baseline, lines[1].baseline);
+}
+
+#[test]
+fn spanish_text_gets_spanish_hyphenation() {
+ let text = "La transición democrática fue una construcción colectiva extraordinariamente compleja y desesperadamente necesaria.";
+ let narrow = Rect::new(36.0, 36.0, 120.0, 700.0);
+ let (mut d, sid, _) = doc_with(text, narrow, ParaAttrs::default());
+ let st = d.story_mut(sid).unwrap();
+ let n = st.len();
+ st.format_chars(0..n, |f| f.over.language = Some("Spanish".into()));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ let hy: Vec<&str> = lines.iter().filter(|l| l.hyphenated).map(|l| text[l.range.clone()].trim_end()).collect();
+ assert!(!hy.is_empty(), "Spanish hyphenates");
+ for l in &hy {
+ let last: String = l.chars().rev().take_while(|c| c.is_alphabetic()).collect::<Vec<_>>().into_iter().rev().collect();
+ let whole = text[text.find(l).unwrap() + l.len() - last.len()..].split(|c: char| !c.is_alphabetic()).next().unwrap();
+ let es = hyphen::Lang::for_language("Spanish").unwrap();
+ let pts = hyphen::hyphen_points_in(whole, &hyphen::Limits::default(), es);
+ assert!(pts.contains(&last.chars().count()), "break {last}- in {whole} is a Bezos point");
+ }
+}
+
+#[test]
+fn cjk_aki_adds_space_without_scaling_outlines() {
+ let (mut d, sid, _) = doc_with("AB", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());
+ let old = compose_story(&d, sid, &ComposeOptions::default());
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {
+ f.over.leading_aki = Some(Some(0.25));
+ f.over.trailing_aki = Some(Some(0.5));
+ });
+ let new = compose_story(&d, sid, &ComposeOptions::default());
+ let a = &old.frames[0].lines[0];
+ let b = &new.frames[0].lines[0];
+ assert!((b.end_x - a.end_x - 18.0).abs() < 1e-6);
+ assert_eq!(a.glyphs[0].sx, b.glyphs[0].sx);
+ assert!((b.glyphs[0].x - a.glyphs[0].x - 3.0).abs() < 1e-6);
+}
+
+#[test]
+fn cjk_jidori_sets_group_width_and_survives_narrow_frames() {
+ for composer in [designcraft_doc::Composer::SingleLine, designcraft_doc::Composer::Paragraph] {
+ let (mut d, sid, _) = doc_with(
+ "AB",
+ Rect::new(0.0, 0.0, 30.0, 150.0),
+ ParaAttrs { composer: Some(composer), glyph_scale_desired: Some(1.2), letter_space_desired: Some(0.2), ..Default::default() },
+ );
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.jidori = Some(4));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert_eq!(lines.len(), 1, "an indivisible jidori group must not be emergency-split");
+ assert!((lines[0].end_x - lines[0].x0 - 48.0).abs() < 1e-6);
+ assert_eq!(lines[0].range, 0..2);
+ }
+}
+
+#[test]
+fn cjk_tsume_removes_sidebearings_without_collapsing_ink() {
+ let (mut d, sid, _) = doc_with("HH", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());
+ let old = compose_story(&d, sid, &ComposeOptions::default());
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.tsume = Some(1.0));
+ let new = compose_story(&d, sid, &ComposeOptions::default());
+ let a = &old.frames[0].lines[0];
+ let b = &new.frames[0].lines[0];
+ let g = &b.glyphs[0];
+ let outline = designcraft_fonts::FontDb::global().outline(&g.face, g.gid);
+ let ink_width = designcraft_geom::Shape::bounding_box(&*outline).width() * g.sx;
+ assert!(ink_width > 0.0);
+ assert!((b.end_x - b.x0 - 2.0 * ink_width).abs() < 1e-6);
+ assert!(b.end_x < a.end_x);
+ assert_eq!(a.glyphs[0].sx, g.sx);
+}
+
+#[test]
+fn cjk_composite_font_selects_entries_before_shaping() {
+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};
+ let (mut d, sid, _) = doc_with("A1B", Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs::default());
+ std::sync::Arc::make_mut(&mut d.styles).composite_fonts.push(CompositeFont {
+ name: "Mixed".into(),
+ entries: vec![
+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },
+ CompositeFontEntry { characters: "0123456789".into(), family: "Source Sans 3".into(), relative_size: 0.5, ..Default::default() },
+ ],
+ });
+ d.story_mut(sid).unwrap().format_chars(0..3, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let line = &cs.frames[0].lines[0];
+ let a = line.glyphs.iter().find(|g| g.byte == 0).unwrap();
+ let n = line.glyphs.iter().find(|g| g.byte == 1).unwrap();
+ assert_ne!(a.face.id(), n.face.id());
+ assert_eq!(cs.styles[a.style as usize].size, 12.0);
+ assert_eq!(cs.styles[n.style as usize].size, 6.0);
+ assert!(!cs.styles.iter().any(|s| s.missing_font));
+}
+
+#[test]
+fn cjk_bunri_does_not_split_double_dash() {
+ for composer in [designcraft_doc::Composer::SingleLine, designcraft_doc::Composer::Paragraph] {
+ let (d, sid, _) =
+ doc_with("--", Rect::new(0.0, 0.0, 5.0, 100.0), ParaAttrs { composer: Some(composer), bunri_kinshi: Some(true), ..Default::default() });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(all_lines(&cs).len(), 1);
+ }
+}
+
+#[test]
+fn cjk_custom_kinsoku_disables_selected_breaks() {
+ let (mut d, sid, _) = doc_with(
+ "甲乙丙丁",
+ Rect::new(0.0, 0.0, 25.0, 200.0),
+ ParaAttrs {
+ composer: Some(designcraft_doc::Composer::SingleLine),
+ kinsoku: Some(Some(designcraft_doc::cjk::Kinsoku { name: "Test".into(), no_start: "乙丙丁".into(), ..Default::default() })),
+ ..Default::default()
+ },
+ );
+ d.story_mut(sid).unwrap().format_chars(0.."甲乙丙丁".len(), |f| f.over.size = Some(12.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(all_lines(&cs).len(), 1);
+}
+
+fn japanese() -> ParaAttrs {
+ ParaAttrs { composer: Some(Composer::Japanese), ..Default::default() }
+}
+
+#[test]
+fn cjk_center_leading_measures_em_centers_across_different_sizes() {
+ let lines_with = |para: ParaAttrs| {
+ let (mut d, sid, _) = doc_with("A\nB", Rect::new(0.0, 0.0, 300.0, 200.0), para);
+ d.story_mut(sid).unwrap().format_chars(0..3, |f| {
+ f.over.leading = Some(designcraft_doc::Leading::Points(30.0));
+ f.over.leading_model = Some(designcraft_doc::cjk::LeadingModel::Center);
+ });
+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.size = Some(24.0));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ all_lines(&cs).into_iter().cloned().collect::<Vec<_>>()
+ };
+ let lines = lines_with(japanese());
+ assert_eq!(lines.len(), 2);
+ let center = |l: &Line| {
+ let g = &l.glyphs[0];
+ let (a, b) = g.face.vertical_metrics();
+ l.baseline + (b - a) / (2.0 * (a + b)) * g.face.units_per_em() * g.sy
+ };
+ assert!((center(&lines[1]) - center(&lines[0]) - 30.0).abs() < 1e-6);
+ assert!((lines[1].baseline - lines[0].baseline - 30.0).abs() > 0.1);
+ // The other composers set lines baseline to baseline.
+ let lines = lines_with(ParaAttrs::default());
+ assert!((lines[1].baseline - lines[0].baseline - 30.0).abs() < 1e-6);
+}
+
+#[test]
+fn cjk_aki_below_sets_the_upper_lines_leading_below_it() {
+ let lines_with = |para: ParaAttrs| {
+ let (mut d, sid, _) = doc_with("A\nB", Rect::new(0.0, 0.0, 300.0, 200.0), para);
+ let st = d.story_mut(sid).unwrap();
+ st.format_chars(0..3, |f| f.over.leading_model = Some(designcraft_doc::cjk::LeadingModel::AkiBelow));
+ st.format_chars(0..2, |f| {
+ f.over.size = Some(24.0);
+ f.over.leading = Some(designcraft_doc::Leading::Points(40.0));
+ });
+ st.format_chars(2..3, |f| {
+ f.over.size = Some(12.0);
+ f.over.leading = Some(designcraft_doc::Leading::Points(20.0));
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ all_lines(&cs).into_iter().cloned().collect::<Vec<_>>()
+ };
+ let lines = lines_with(japanese());
+ assert_eq!(lines.len(), 2);
+ let em_bottom = |l: &Line| {
+ let g = &l.glyphs[0];
+ let (a, b) = g.face.vertical_metrics();
+ l.baseline + b / (a + b) * g.face.units_per_em() * g.sy
+ };
+ let gap = em_bottom(&lines[1]) - em_bottom(&lines[0]);
+ assert!((gap - 40.0).abs() < 1e-6, "{gap}");
+ // The other composers advance by the lower line's leading, baseline to baseline.
+ let lines = lines_with(ParaAttrs::default());
+ assert!((lines[1].baseline - lines[0].baseline - 20.0).abs() < 1e-6);
+}
+
++#[test]
++fn cjk_aki_below_measures_em_tops_and_aki_above_em_bottoms() {
++ use designcraft_doc::cjk::LeadingModel;
++ for (model, top) in [(LeadingModel::AkiBelow, true), (LeadingModel::AkiAbove, false)] {
++ let (mut d, sid, _) = doc_with("A\nB", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());
++ d.story_mut(sid).unwrap().format_chars(0..3, |f| {
++ f.over.leading = Some(designcraft_doc::Leading::Points(30.0));
++ f.over.leading_model = Some(model);
++ });
++ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.size = Some(24.0));
++ let cs = compose_story(&d, sid, &ComposeOptions::default());
++ let lines = all_lines(&cs);
++ assert_eq!(lines.len(), 2);
++ // The em box edge below the baseline (y down): its top, or its bottom one em lower.
++ let edge = |l: &Line| {
++ let g = &l.glyphs[0];
++ let (a, b) = g.face.vertical_metrics();
++ let em = g.face.units_per_em() * g.sy;
++ let em_top = l.baseline - em * a / (a + b);
++ if top { em_top } else { em_top + em }
++ };
++ assert!((edge(lines[1]) - edge(lines[0]) - 30.0).abs() < 1e-6, "{model:?}");
++ }
++}
++
+#[test]
+fn cjk_em_center_alignment_moves_small_characters() {
+ let line_with = |para: ParaAttrs| {
+ let (mut d, sid, _) = doc_with("AB", Rect::new(0.0, 0.0, 300.0, 100.0), para);
+ d.story_mut(sid).unwrap().format_chars(0..1, |f| f.over.size = Some(24.0));
+ d.story_mut(sid).unwrap().format_chars(0..2, |f| f.over.character_alignment = Some(designcraft_doc::cjk::CharacterAlignment::EmCenter));
+ compose_story(&d, sid, &ComposeOptions::default()).frames[0].lines[0].clone()
+ };
+ let line = line_with(japanese());
+ let center = |g: &PlacedGlyph| {
+ let (a, b) = g.face.vertical_metrics();
+ g.y + (b - a) / (2.0 * (a + b)) * g.face.units_per_em() * g.sy
+ };
+ assert!((center(&line.glyphs[0]) - center(&line.glyphs[1])).abs() < 1e-6);
+ // The other composers keep every character on the baseline.
+ let line = line_with(ParaAttrs::default());
+ assert!(line.glyphs.iter().all(|g| g.y.abs() < 1e-9), "{:?}", line.glyphs.iter().map(|g| g.y).collect::<Vec<_>>());
+}
+
+#[test]
+fn cjk_hanging_punctuation_uses_frame_edge_without_changing_glyph_size() {
+ let k = designcraft_doc::cjk::Kinsoku { name: "Test".into(), no_start: ",".into(), hanging: ",".into(), ..Default::default() };
+ let (mut d, sid, fid) = doc_with(
+ "AB,",
+ Rect::new(0.0, 0.0, 300.0, 100.0),
+ ParaAttrs {
+ composer: Some(designcraft_doc::Composer::SingleLine),
+ kinsoku: Some(Some(k)),
+ kinsoku_hang: Some(designcraft_doc::cjk::KinsokuHang::Regular),
..Default::default()
},
);
@@@ -4788,307 -2986,283 +5002,588 @@@ fn empty_paragraphs_get_no_bullet_or_nu
}
}
+#[test]
+fn tight_word_spacing_does_not_isolate_a_word() {
+ // A narrow word-spacing range (100–105%) with some letter spacing and glyph scaling, no
+ // hyphenation: lines that need more stretch must open their word spaces, not letter-space a
+ // single word across the measure.
+ let para = ParaAttrs {
+ align: Some(Align::LeftJustified),
+ hyphenate: Some(false),
+ first_line_indent: Some(9.0),
+ word_space_min: Some(1.0),
+ word_space_desired: Some(1.03),
+ word_space_max: Some(1.05),
+ letter_space_min: Some(-0.05),
+ letter_space_max: Some(0.05),
+ glyph_scale_min: Some(0.99),
+ glyph_scale_max: Some(1.01),
+ ..Default::default()
+ };
+ // Short words: any two fit on a line together.
+ let text = CORPUS[..2].join(" ");
+ for w in (200..=320).step_by(5) {
+ let (d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, w as f64, 20000.0), para.clone());
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ for l in &lines[..lines.len() - 1] {
+ let words = text[l.range.clone()].split_whitespace().count();
+ assert!(words > 1, "width {w}: a single-word line {:?}", &text[l.range.clone()]);
+ }
+ }
+}
+
+#[test]
+fn fixed_width_spaces_do_not_stretch_on_justified_lines() {
+ // Long words in a narrow column: lines stretch past the maximum word spacing. Only the word
+ // spaces take that stretch; em, en and thin spaces keep their width.
+ let words = ["characteristically", "misunderstanding", "unquestionably", "responsibility", "administration", "photographer"];
+ let seps = [" ", "\u{2003}", " ", "\u{2002}", " ", "\u{2009}"];
+ let text: String = (0..60).map(|i| format!("{}{}", words[i % words.len()], seps[i % seps.len()])).collect();
+ let text = text.trim_end().to_string();
+ let fixed = |c: char| matches!(c, '\u{2003}' | '\u{2002}' | '\u{2009}');
+ // (character, advance) of each fixed space, per line, and whether the line ends the paragraph.
+ let spaces = |align: Align, w: f64| -> Vec<(Vec<(char, f64)>, bool)> {
+ let para = ParaAttrs { align: Some(align), hyphenate: Some(false), ..Default::default() };
+ let (d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, w, 20000.0), para);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ all_lines(&cs)
+ .iter()
+ .map(|l| {
+ let found = l.glyphs.iter().filter_map(|g| text[g.byte..].chars().next().filter(|&c| fixed(c)).map(|c| (c, g.adv))).collect();
+ (found, l.last_in_para)
+ })
+ .collect()
+ };
+ let mut checked = 0;
+ for w in [190.0, 230.0, 270.0] {
+ let natural: Vec<(char, f64)> = spaces(Align::Left, w).into_iter().flat_map(|l| l.0).collect();
+ for (found, last) in spaces(Align::LeftJustified, w) {
+ if last {
+ continue;
+ }
+ for (c, a) in found {
+ let Some(&(_, n)) = natural.iter().find(|x| x.0 == c) else { continue };
+ assert!((a - n).abs() < 1e-6, "width {w}: U+{:04X} is {a:.2} wide, not {n:.2}", c as u32);
+ checked += 1;
+ }
+ }
+ }
+ assert!(checked > 5, "{checked} fixed spaces on justified lines");
+}
+
+#[test]
+fn grep_style_in_the_documents_dialect_keeps_short_words_with_the_next() {
+ // `\l` (lowercase letter) and `\h` (horizontal space) aren't Rust regex syntax; the style used
+ // to be skipped silently.
+ let text = "Мы и он в доме и в саду, а она у окна и с книгой в руках у стола.";
+ let para = ParaAttrs {
+ align: Some(Align::Left),
+ grep_styles: Some(vec![designcraft_doc::GrepStyle { style: "nobreak".into(), pattern: r"\b\l{1,2}\h".into() }]),
+ ..Default::default()
+ };
+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 70.0, 1000.0), para);
+ let chars = designcraft_doc::CharAttrs { no_break: Some(true), ..Default::default() };
+ std::sync::Arc::make_mut(&mut d.styles).character.push(designcraft_doc::CharacterStyle {
+ name: "nobreak".into(),
+ based_on: None,
+ chars,
+ shortcut: String::new(),
+ });
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let lines = all_lines(&cs);
+ assert!(lines.len() > 3);
+ let short = |w: &str| w.chars().count() <= 2 && w.chars().all(char::is_lowercase);
+ for l in &lines[..lines.len() - 1] {
+ let last = text[l.range.clone()].split_whitespace().last().unwrap_or("");
+ assert!(!short(last), "line ends with a short word: {:?}", &text[l.range.clone()]);
+ }
+}
+
+// ---------- paragraph border and shading ----------
+
+fn bordered(text: &str, rect: Rect, para: ParaAttrs) -> ComposedStory {
+ let para = ParaAttrs { border_on: Some(true), border_weights: Some([1.0; 4]), ..para };
+ let (d, sid, _) = doc_with(text, rect, para);
+ compose_story(&d, sid, &ComposeOptions::default())
+}
+
+fn has_curves(bp: &designcraft_geom::BezPath) -> bool {
+ bp.elements().iter().any(|e| matches!(e, designcraft_geom::PathEl::CurveTo(..) | designcraft_geom::PathEl::QuadTo(..)))
+}
+
+#[test]
+fn rounded_border_corners_are_curves_and_dotted_borders_paint_their_gap_first() {
+ use designcraft_geom::corners::{Corner, CornerShape};
+ let rounded = [Corner { shape: CornerShape::Rounded, size: 6.0 }; 4];
+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs { border_corners: Some(rounded), ..Default::default() });
+ let paths: Vec<_> = cs.frames[0].decos.iter().filter_map(|dc| dc.path.as_ref()).collect();
+ assert_eq!(paths.len(), 1, "one stroked outline");
+ assert!(has_curves(paths[0]));
+ // Square corners: plain edges, no curves.
+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());
+ assert!(cs.frames[0].decos.iter().all(|dc| dc.path.is_none()));
+ // A dotted border with a gap colour: the gap under the dots.
+ let dotted = ParaAttrs { border_type: Some(designcraft_doc::StrokeType::Dotted), border_gap_color: Some("[Paper]".into()), ..Default::default() };
+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), dotted);
+ let colors: Vec<&str> = cs.frames[0].decos.iter().filter(|dc| dc.path.is_some()).map(|dc| dc.color.as_str()).collect();
+ assert_eq!(colors, ["[Paper]", "[Black]"]);
+}
+
+/// The width of the widest border edge (the top and bottom edges span the box).
+fn border_width(cs: &ComposedStory) -> f64 {
+ cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect.width()).fold(0.0, f64::max)
+}
+
+#[test]
+fn a_text_width_border_is_narrower_than_a_column_width_one() {
+ let rect = Rect::new(0.0, 0.0, 300.0, 200.0);
+ let column = border_width(&bordered("Short", rect, ParaAttrs::default()));
+ let text = border_width(&bordered("Short", rect, ParaAttrs { border_width: Some(designcraft_doc::BoxWidth::Text), ..Default::default() }));
+ assert!((column - 302.0).abs() < 1e-6, "column and both side strokes: {column}");
+ assert!(text > 2.0 && text < 60.0, "text: {text}");
+}
+
+/// Edges of a plain border by frame column: (column, count).
+fn edges_per_column(cs: &ComposedStory) -> Vec<usize> {
+ let cols = &cs.frames[0].columns;
+ cols.iter()
+ .map(|c| {
+ cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]" && dc.rect.center().x > c.x0 - 2.0 && dc.rect.center().x < c.x1 + 2.0).count()
+ })
+ .collect()
+}
+
+#[test]
+fn a_split_paragraph_closes_its_border_in_each_column_only_when_set_to() {
+ let text = format!("{LOREM} {LOREM}");
+ let compose = |display: bool| {
+ let para = ParaAttrs { border_on: Some(true), border_weights: Some([1.0; 4]), border_display_if_splits: Some(display), ..Default::default() };
+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, 90.0), para);
+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;
+ compose_story(&d, sid, &ComposeOptions::default())
+ };
+ let open = compose(false);
+ assert!(open.frames[0].lines.iter().any(|l| l.column == 1), "the paragraph reaches the second column");
+ // Open at the split: top and sides in the first column, sides and bottom in the second.
+ assert_eq!(edges_per_column(&open), [3, 3]);
+ assert_eq!(edges_per_column(&compose(true)), [4, 4]);
+}
+
+#[test]
+fn consecutive_paragraphs_with_the_same_border_share_one_box() {
+ let compose = |merge: bool| {
+ let para = ParaAttrs { space_after: Some(10.0), border_merge: Some(merge), ..Default::default() };
+ bordered("One\nTwo\nThree", Rect::new(0.0, 0.0, 300.0, 300.0), para)
+ };
+ let merged = compose(true);
+ let edges: Vec<Rect> = merged.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect).collect();
+ assert_eq!(edges.len(), 4, "one box: {edges:?}");
+ let lines = &merged.frames[0].lines;
+ let (first, last) = (&lines[0], &lines[lines.len() - 1]);
+ let left = edges.iter().find(|r| r.height() > r.width()).unwrap();
+ assert!((left.y0 - (first.baseline - first.ascent)).abs() < 1e-6 && (left.y1 - (last.baseline + last.descent)).abs() < 1e-6, "{left:?}");
+ assert_eq!(compose(false).frames[0].decos.iter().filter(|dc| dc.color == "[Black]").count(), 12, "a box each");
+}
+
+#[test]
+fn shading_clips_to_the_frame_and_can_stay_off_print() {
+ let para = ParaAttrs {
+ shading_on: Some(true),
+ shading_offsets: Some([50.0; 4]),
+ shading_clip: Some(true),
+ shading_nonprinting: Some(true),
+ ..Default::default()
+ };
+ let (d, sid, _) = doc_with("Shaded", Rect::new(0.0, 0.0, 300.0, 200.0), para);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let area = cs.frames[0].columns[0];
+ let shade = &cs.frames[0].decos[0];
+ assert!(shade.nonprinting);
+ assert!(shade.rect.x0 >= area.x0 - 1e-6 && shade.rect.y0 >= area.y0 - 1e-6 && shade.rect.x1 <= area.x1 + 1e-6, "{:?} in {area:?}", shade.rect);
+}
+
+// ---------- span space, bullets and numbering ----------
+
+#[test]
+fn space_before_and_after_a_span_moves_the_span_and_the_text_below() {
+ let at = |before: f64, after: f64| {
+ let (mut d, sid, _, h) = span_doc(1, 1, Rect::new(0.0, 0.0, 600.0, 800.0));
+ let p = &mut d.story_mut(sid).unwrap().paras[h].para;
+ p.span_space_before = Some(before);
+ p.span_space_after = Some(after);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let first = |pi: usize| cs.frames[0].lines.iter().find(|l| l.para == pi).map(|l| l.baseline).unwrap();
+ (first(h), first(h + 1))
+ };
+ let (span0, below0) = at(0.0, 0.0);
+ let (span1, below1) = at(24.0, 0.0);
+ assert!((span1 - span0 - 24.0).abs() < 0.01, "{span0} → {span1}");
+ assert!((below1 - below0 - 24.0).abs() < 0.01, "the text below moves with it");
+ let (span2, below2) = at(0.0, 18.0);
+ assert!((span2 - span0).abs() < 0.01 && (below2 - below0 - 18.0).abs() < 0.01, "{below0} → {below2}");
+}
+
+/// The first line of each paragraph.
+fn first_lines(cs: &ComposedStory) -> Vec<&Line> {
+ all_lines(cs).into_iter().filter(|l| l.first_in_para).collect()
+}
+
+#[test]
+fn a_right_aligned_number_ends_at_the_line_start() {
+ use designcraft_doc::{ListAlign, ListType};
+ let compose = |align: ListAlign| {
+ let para = ParaAttrs {
+ list_type: Some(ListType::Numbers),
+ number_align: Some(align),
+ left_indent: Some(36.0),
+ first_line_indent: Some(-18.0),
+ ..Default::default()
+ };
+ let (d, sid, _) = doc_with("Item", Rect::new(0.0, 0.0, 300.0, 200.0), para);
+ compose_story(&d, sid, &ComposeOptions::default())
+ };
+ // The label "1.\t": its first two glyphs are the number and the full stop.
+ let cs = compose(ListAlign::Left);
+ let col = cs.frames[0].columns[0];
+ let l = first_lines(&cs)[0];
+ assert!((l.glyphs[0].x - (col.x0 + 18.0)).abs() < 0.01, "left: starts at the line start");
+ let text_x = l.glyphs.iter().find(|g| g.len > 0).unwrap().x;
+ let cs = compose(ListAlign::Right);
+ let l = first_lines(&cs)[0];
+ let end = l.glyphs[1].x + l.glyphs[1].adv;
+ assert!((end - (col.x0 + 18.0)).abs() < 0.01, "right: ends at the line start ({end})");
+ assert!((l.glyphs.iter().find(|g| g.len > 0).unwrap().x - text_x).abs() < 0.01, "the text stays at the tab stop");
+}
+
+#[test]
+fn level_two_numbering_restarts_after_level_one() {
+ let para = numbered(designcraft_doc::NumberStyle::Arabic, "^1.^#");
+ let (mut d, sid, _) = doc_with("A\nB\nC\nD\nE", Rect::new(0.0, 0.0, 300.0, 300.0), para);
+ for (p, level) in d.story_mut(sid).unwrap().paras.iter_mut().zip([1, 2, 2, 1, 2]) {
+ p.para.list_level = Some(level);
+ }
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ // `^1` is level 1's number, `^#` the paragraph's own level.
+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.1", "1.1", "1.2", "2.2", "2.1"]);
+ // Without the restart, level 2 carries on.
+ for p in &mut d.story_mut(sid).unwrap().paras {
+ p.para.restart_numbers = Some(false);
+ }
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.1", "1.1", "1.2", "2.2", "2.3"]);
+}
+
+#[test]
+fn the_tab_position_places_the_text_after_the_label() {
+ use designcraft_doc::ListType;
+ let compose = |tab: Option<f64>| {
+ let para = ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(tab), ..Default::default() };
+ let (d, sid, _) = doc_with("Item", Rect::new(0.0, 0.0, 300.0, 200.0), para);
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let col = cs.frames[0].columns[0];
+ first_lines(&cs)[0].glyphs.iter().find(|g| g.len > 0).unwrap().x - col.x0
+ };
+ assert!((compose(Some(50.0)) - 50.0).abs() < 0.01);
+ assert!((compose(None) - 36.0).abs() < 0.01, "the default tab stop");
+}
+
+#[test]
+fn paragraph_mark_size_counts_in_its_line_auto_leading() {
+ let gaps = |mark_size: f64| {
+ let (mut d, sid, _) = doc_with("One\nTwo\nThree", Rect::new(36.0, 36.0, 300.0, 300.0), ParaAttrs::default());
+ d.story_mut(sid).unwrap().format_chars(7..8, |f| f.over.size = Some(mark_size));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let b: Vec<f64> = all_lines(&cs).iter().map(|l| l.baseline).collect();
+ assert_eq!(b.len(), 3);
+ (b[1] - b[0], b[2] - b[1])
+ };
+ // A 12 pt line ending in a 14 pt return: 14 × 120% above it, the next line unchanged.
+ let (above, below) = gaps(14.0);
+ assert!((above - 16.8).abs() < 1e-6, "{above}");
+ assert!((below - 14.4).abs() < 1e-6, "{below}");
+ let (above, below) = gaps(12.0);
+ assert!((above - 14.4).abs() < 1e-6, "{above}");
+ assert!((below - 14.4).abs() < 1e-6, "{below}");
+}
++
+ // 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 --cc crates/engine/src/cmd/preflight.rs
index 5a69ff1bf,1516c75d9..fcf7980d3
--- a/crates/engine/src/cmd/preflight.rs
+++ b/crates/engine/src/cmd/preflight.rs
@@@ -168,8 -113,18 +168,17 @@@ pub fn check(s: &Session, min_ppi: f64
unsupported_typography
.insert(format!("Kinsoku priority `{}` is preserved, but push-in/push-out priority is not applied", para.kinsoku_type));
}
- 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;
+ let kenten = props.kenten && (props.kenten_overprint_fill == O::On || props.kenten_overprint_stroke == O::On);
+ let ruby = !props.ruby.is_empty() && (props.ruby_overprint_fill == O::On || props.ruby_overprint_stroke == O::On);
+ if kenten || ruby {
+ unsupported_typography
+ .insert("Ruby and kenten overprint show in Overprint Preview, but PDF export doesn't write overprint".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 --cc crates/engine/src/cmd/text.rs
index 7feb9f613,7eca1625a..a0d3e9057
--- a/crates/engine/src/cmd/text.rs
+++ b/crates/engine/src/cmd/text.rs
@@@ -2213,42 -2269,64 +2600,102 @@@ 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());
+ }
}
+
+#[cfg(test)]
+mod reserve_tests {
+ use super::*;
+
+ #[test]
+ fn failed_reservation_rolls_back_the_edit_even_after_local_text_was_removed() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let result = s.execute("frame.create", &json!({"rect":[36,36,300,300],"content":"text","text":"Keep this text."})).unwrap();
+ let sid = StoryId(result["story"].as_u64().unwrap());
+ s.execute("text.select", &json!({"story":sid.0,"anchor":1,"focus":4})).unwrap();
+ let before = s.doc().unwrap().clone();
+ assert!(before.selection.text.is_some_and(|t| !t.range().is_empty()));
+ let journal = s.journal.clone();
+ let error = s
+ .edit(|d, sel| {
+ let st = d.story_mut(sid).unwrap();
+ st.format_chars(5..9, |f| f.over.change = Some(designcraft_doc::ChangeMark::Inserted));
+ let at = super::super::changes::mark_deleted(st, 0..9);
+ assert_eq!(at, 5);
+ assert_eq!(st.text, "Keep text.");
+ assert_eq!(st.format_after(0).over.change, Some(designcraft_doc::ChangeMark::Deleted));
+ sel.text = None;
+ reserve_command_text(st, usize::MAX)?;
+ ok()
+ })
+ .unwrap_err();
+ assert!(error.to_string().contains("could not reserve text insertion"));
+ let after = s.doc().unwrap();
+ assert!(std::sync::Arc::ptr_eq(&after.doc, &before.doc));
+ assert_eq!(after.selection, before.selection);
+ assert_eq!(after.revision, before.revision);
+ assert_eq!(after.history.undo.len(), before.history.undo.len());
+ assert_eq!(after.history.redo.len(), before.history.redo.len());
+ assert_eq!(s.journal, journal);
+ }
+}
diff --cc crates/fonts/src/fontdb.rs
index 34e419b03,1c8fd41a2..d835b9765
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@@ -123,10 -119,10 +123,12 @@@ pub struct FontFace
bmp: std::sync::OnceLock<Box<[u64]>>,
/// The ideographic em box, read on first use.
em: std::sync::OnceLock<(f64, f64)>,
+ /// The ideographic character face box, read on first use.
+ icf: std::sync::OnceLock<(f64, f64)>,
/// The font menu group and native family name, read on first use.
group: std::sync::OnceLock<(FontGroup, Option<String>)>,
+ family_aliases: Vec<String>,
+ style_aliases: Vec<String>,
}
/// A cheap `Copy` handle to a face. Faces are never unloaded, so the handle lives for the rest of
@@@ -754,8 -715,7 +761,9 @@@ fn make_face(bytes: FontBytes, source:
index,
bmp: std::sync::OnceLock::new(),
em: std::sync::OnceLock::new(),
+ family_aliases,
+ style_aliases,
+ icf: std::sync::OnceLock::new(),
group: std::sync::OnceLock::new(),
})
}
diff --cc crates/idml/src/export.rs
index b1f9d5c21,af680afb1..7f97a0ec6
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@@ -1419,13 -1375,10 +1424,16 @@@ impl<'a> Ex<'a>
n!(space_after, "SpaceAfter");
n!(drop_cap_lines, "DropCapLines");
n!(drop_cap_chars, "DropCapCharacters");
+ if a.drop_cap_align_left.is_some() || a.drop_cap_scale_descenders.is_some() {
+ let d = designcraft_doc::ParaProps::default();
+ let bits = u32::from(a.drop_cap_align_left.unwrap_or(d.drop_cap_align_left))
+ | u32::from(a.drop_cap_scale_descenders.unwrap_or(d.drop_cap_scale_descenders)) << 1;
+ el.set("DropcapDetail", bits);
+ }
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 => {
@@@ -2860,70 -2674,102 +2868,170 @@@ fn topic_self(path: &[String]) -> Strin
s
}
+/// Package metadata: the creation and modification times that date variables show.
+fn metadata_xmp(d: &Document) -> String {
+ use designcraft_doc::vars::format_date;
+ let iso = |t: i64| format!("{}:{:02}Z", format_date(t, "yyyy-MM-ddTHH:mm"), t.rem_euclid(60));
+ let modified = if d.modified > 0 { d.modified } else { d.created };
+ format!(
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n <rdf:Description rdf:about=\"\" xmlns:xmp=\"http://ns.adobe.com/xap/1.0/\">\n <xmp:CreateDate>{}</xmp:CreateDate>\n <xmp:ModifyDate>{}</xmp:ModifyDate>\n </rdf:Description>\n </rdf:RDF>\n</x:xmpmeta>\n",
+ iso(d.created),
+ iso(modified)
+ )
+}
+
+/// A text variable definition with its type's settings element.
+fn text_variable_el(v: &designcraft_doc::vars::TextVariable) -> El {
+ use designcraft_doc::vars::{Use, VarKind};
+ let pref = |name: &str| El::new(name).attr("TextBefore", &v.before);
+ let (ty, settings) = match &v.kind {
+ VarKind::Custom { text } => ("CustomTextType", Some(pref("CustomTextVariablePreference").attr("Contents", text))),
+ VarKind::LastPageNumber { section } => (
+ "LastPageNumberType",
+ Some(
+ pref("PageNumberVariablePreference").attr("Format", "Current").attr("Scope", if *section { "SectionScope" } else { "DocumentScope" }),
+ ),
+ ),
+ VarKind::ChapterNumber => ("ChapterNumberType", Some(pref("ChapterNumberVariablePreference").attr("Format", "Current"))),
+ VarKind::FileName { extension } => {
+ ("FileNameType", Some(pref("FileNameVariablePreference").attr("IncludePath", "false").attr("IncludeExtension", bool_s(*extension))))
+ }
+ VarKind::CreationDate { format } => ("CreationDateType", Some(pref("DateVariablePreference").attr("Format", format))),
+ VarKind::ModificationDate { format } => ("ModificationDateType", Some(pref("DateVariablePreference").attr("Format", format))),
+ VarKind::OutputDate { format } => ("OutputDateType", Some(pref("DateVariablePreference").attr("Format", format))),
+ VarKind::RunningHeader { style, use_, character } => {
+ let (ty, el, key, style_ref) = if *character {
+ (
+ "MatchCharacterStyleType",
+ "MatchCharacterStylePreference",
+ "AppliedCharacterStyle",
+ names::style_self("CharacterStyle", CHAR_BUILTINS, style),
+ )
+ } else {
+ (
+ "MatchParagraphStyleType",
+ "MatchParagraphStylePreference",
+ "AppliedParagraphStyle",
+ names::style_self("ParagraphStyle", PARA_BUILTINS, style),
+ )
+ };
+ let strategy = if *use_ == Use::LastOnPage { "LastOnPage" } else { "FirstOnPage" };
+ (
+ ty,
+ Some(pref(el).attr(key, style_ref).attr("SearchStrategy", strategy).attr("ChangeCase", "None").attr("DeleteEndPunctuation", "false")),
+ )
+ }
+ VarKind::Imported { variable_type, settings_element, settings, .. } => {
+ let el = (!settings_element.is_empty()).then(|| El { name: settings_element.clone(), attrs: settings.clone(), children: vec![] });
+ (variable_type.as_str(), el)
+ }
+ };
+ let mut e = El::new("TextVariable").attr("Self", format!("dTextVariablen{}", v.name)).attr("Name", &v.name).attr("VariableType", ty);
+ if let Some(mut s) = settings {
+ if !matches!(v.kind, VarKind::Imported { .. }) {
+ s.set("TextAfter", &v.after);
+ }
+ e.push(s);
+ }
+ e
+}
++
+ /// 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 --cc crates/idml/src/import.rs
index efed6534f,9823b5650..88f668558
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@@ -1520,22 -1284,21 +1524,25 @@@ impl<'r> Importer<'r>
a.space_after = e.num("SpaceAfter");
a.drop_cap_lines = u("DropCapLines");
a.drop_cap_chars = u("DropCapCharacters");
+ // DropcapDetail bits: 1 = Align Left Edge, 2 = Scale for Descenders.
+ if let Some(v) = e.num("DropcapDetail").filter(|v| v.is_finite() && *v >= 0.0) {
+ let bits = v as u32;
+ a.drop_cap_align_left = Some(bits & 1 != 0);
+ a.drop_cap_scale_descenders = Some(bits & 2 != 0);
+ }
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")
- .map(|c| if c.contains("Single") { designcraft_doc::Composer::SingleLine } else { designcraft_doc::Composer::Paragraph });
+ a.composer = e.prop("Composer").map(|c| composer_in(&c));
a.hyphenate = e.boolean("Hyphenation");
a.hyph_min_word = u("HyphenateWordsLongerThan");
a.hyph_after_first = u("HyphenateAfterFirst");
@@@ -2964,9 -2550,80 +2971,68 @@@ fn pdf_page_in(g: &El) -> u32
pub(crate) fn uri_to_path(uri: &str) -> String {
let rest = uri.strip_prefix("file://").or_else(|| uri.strip_prefix("file:")).unwrap_or(uri);
// `file:///C:/…` → `/C:/…` → `C:/…`
- let rest = if rest.len() > 3 && rest.starts_with('/') && rest.as_bytes()[2] == b':' { &rest[1..] } else { rest };
- let mut out = Vec::with_capacity(rest.len());
- let b = rest.as_bytes();
- let mut i = 0;
- while i < b.len() {
- if b[i] == b'%'
- && i + 2 < b.len()
- && let Ok(v) = u8::from_str_radix(&rest[i + 1..i + 3], 16)
- {
- out.push(v);
- i += 3;
- continue;
- }
- out.push(b[i]);
- i += 1;
- }
- String::from_utf8_lossy(&out).to_string()
+ let rest = match rest.as_bytes() {
+ [b'/', _, b':', _, ..] => rest.get(1..).unwrap_or(rest),
+ _ => rest,
+ };
+ percent_decode(rest)
}
+
+ /// 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 --cc crates/idml/src/tests.rs
index a93516584,80e7bd80b..36e3c5203
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@@ -2339,106 -1400,166 +2339,270 @@@ fn list_numbering_format_expression_and
check(&import_idml(&export_idml(&d)).unwrap());
}
+/// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is
+/// set in that family instead of counting as a missing font drawn in the fallback.
+#[test]
+fn applied_font_with_an_id_prefix_names_the_family() {
+ let styles = STYLES.replace(">Source Serif 4</AppliedFont>", ">$ID/Source Serif 4</AppliedFont>");
+ let story = STORY.replace(
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14">"#,
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14"><Properties><AppliedFont type="string">$ID/Source Serif 4</AppliedFont></Properties>"#,
+ );
+ let bytes = zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", &styles),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", &story),
+ ]);
+ let d = import_idml_with(&bytes, &|_| None).unwrap();
+ let fonts: Vec<&str> = d.styles.paragraph.iter().filter_map(|s| s.chars.font_family.as_deref()).collect();
+ assert!(!fonts.is_empty() && fonts.iter().all(|f| *f == "Source Serif 4"), "{fonts:?}");
+ let (sid, story) = d.stories.iter().next().unwrap();
+ let bold = story.runs().find(|(r, _)| story.text[r.clone()].starts_with("bold")).unwrap().1;
+ assert_eq!(bold.over.font_family.as_deref(), Some("Source Serif 4"));
+ // The bundled family draws the text (an unknown family would fall back to Source Sans 3).
+ let cs = designcraft_compose::compose_story(&d, *sid, &Default::default());
+ let first_para = story.text.find('\n').unwrap();
+ let families: Vec<&str> = cs
+ .frames
+ .iter()
+ .flat_map(|f| &f.lines)
+ .flat_map(|l| &l.glyphs)
+ .filter(|g| g.visible && g.len > 0 && g.byte < first_para)
+ .map(|g| g.face.get().family.as_str())
+ .collect();
+ assert!(!families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"), "{families:?}");
+}
+
+#[test]
+fn list_tab_position_round_trips_as_a_tab_stop() {
+ use designcraft_doc::{ListType, ParaAttrs, ParagraphStyle, TabAlign, TabStop};
+ let stop = |position, align| TabStop { position, align, leader: String::new(), align_on: String::new() };
+ let mut d = Document::new(&NewDocument::default());
+ std::sync::Arc::make_mut(&mut d.styles).paragraph.push(ParagraphStyle {
+ name: "List".into(),
+ based_on: None,
+ next_style: None,
+ para: ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(Some(24.0)), ..Default::default() },
+ chars: CharAttrs::default(),
+ shortcut: String::new(),
+ });
+ let local = ParaAttrs {
+ list_type: Some(ListType::Bullets),
+ list_tab: Some(Some(36.0)),
+ tabs: Some(vec![stop(100.0, TabAlign::Right)]),
+ ..Default::default()
+ };
+ let ended = ParaAttrs { list_type: Some(ListType::None), ..Default::default() };
+ let lid = d.default_layer();
+ for (i, (text, style, para)) in
+ [("Local\tx", "", local), ("Styled\ty", "List", ParaAttrs::default()), ("Ended\tz", "List", ended)].into_iter().enumerate()
+ {
+ let pf = ParaFormat { style: if style.is_empty() { ParaFormat::default().style } else { style.into() }, para, ..Default::default() };
+ let y = 40.0 + 100.0 * i as f64;
+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, y, 300.0, y + 80.0), lid, text, pf).unwrap();
+ }
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let tabs = |prefix: &str| {
+ let s = back.stories.values().find(|s| s.text.starts_with(prefix)).unwrap();
+ back.styles.resolve_para(&s.paras[0]).0.tabs
+ };
+ assert_eq!(tabs("Local"), vec![stop(36.0, TabAlign::Left), stop(100.0, TabAlign::Right)]);
+ assert_eq!(tabs("Styled"), vec![stop(24.0, TabAlign::Left)]);
+ assert_eq!(tabs("Ended"), vec![], "a paragraph that ends the list has no list tab stop");
+}
+
+#[test]
+fn round_trips_the_zero_point_and_ruler_origin() {
+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });
+ d.settings.zero_point = [36.0, 18.5];
+ let back = import_idml(&export_idml(&d)).unwrap();
+ assert_eq!(back.settings.zero_point, [36.0, 18.5]);
+ for origin in [designcraft_doc::RulerOrigin::Page, designcraft_doc::RulerOrigin::Spine, designcraft_doc::RulerOrigin::Spread] {
+ d.settings.ruler_origin = origin;
+ assert_eq!(import_idml(&export_idml(&d)).unwrap().settings.ruler_origin, origin);
+ }
+ // A hostile ZeroPoint lands on the pasteboard; a malformed one is ignored.
+ let fixture = |zp: &str| {
+ let designmap = format!(
+ r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d" ZeroPoint="{zp}">
+ <idPkg:Spread src="Spreads/Spread_s.xml"/>
+ </Document>"#
+ );
+ let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">
+ <Spread Self="s"><Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/></Spread>
+ </idPkg:Spread>"#;
+ import_idml(&zip_files(&[("designmap.xml", &designmap), ("Spreads/Spread_s.xml", spread)])).unwrap()
+ };
+ let [x, y] = fixture("1e300 -1e300").settings.zero_point;
+ assert!(x.is_finite() && y.is_finite() && x < 1e4 && y > -1e4, "{x} {y}");
+ assert_eq!(fixture("12").settings.zero_point, [0.0, 0.0]);
+ assert_eq!(fixture("NaN 4").settings.zero_point, [0.0, 0.0]);
+}
++
+ #[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)
+ );
+ }
+
+ #[test]
+ fn ruby_settings_import_from_idml_and_round_trip() {
+ use designcraft_doc::cjk_settings::AdornmentOverprint;
+ use designcraft_doc::ruby::{RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubyType};
+ // InDesign's names: RubyFlag is a number, colours and fonts are properties.
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">
+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">
+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" RubyFlag="1" RubyString="かん じ" RubyType="PerCharacterRuby" RubyAlignment="RubyCenter" RubyPosition="BelowLeft" RubyYOffset="-1.4173228" RubyFontSize="-1" RubyXScale="90" RubyParentOverhangAmount="RubyOverhangNoLimit" RubyParentSpacing="RubyParentBothSides" RubyAutoAlign="false" RubyAutoScaling="true" RubyParentScalingPercent="40" RubyAutoTcyDigits="2" RubyTint="-1" RubyOverprintFill="Auto"><Properties><RubyFont type="string">$ID/</RubyFont><RubyFontStyle type="enumeration">Nothing</RubyFontStyle><RubyFill type="string">Text Color</RubyFill></Properties><Content>漢字</Content></CharacterStyleRange>
+ </ParagraphStyleRange></Story></idPkg:Story>"#;
+ let doc = import_idml(&fixture_with_story(story)).unwrap();
+ let a = doc.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();
+ assert_eq!(a.ruby.as_deref(), Some("かん じ"));
+ assert_eq!(a.ruby_type, Some(RubyType::PerCharacter));
+ assert_eq!(a.ruby_alignment, Some(RubyAlignment::Center));
+ assert_eq!(a.ruby_position, Some(RubyPosition::BelowLeft));
+ assert_eq!(a.ruby_y_offset, Some(-1.4173228));
+ assert_eq!(a.ruby_font_size, Some(None));
+ assert_eq!(a.ruby_x_scale, Some(0.9));
+ assert_eq!(a.ruby_overhang_amount, Some(RubyOverhang::NoLimit));
+ assert_eq!(a.ruby_parent_spacing, Some(RubyParentSpacing::BothSides));
+ assert_eq!((a.ruby_auto_align, a.ruby_auto_scaling, a.ruby_scaling_min), (Some(false), Some(true), Some(0.4)));
+ assert_eq!(a.ruby_auto_tcy_digits, Some(2));
+ assert_eq!((a.ruby_font.as_deref(), a.ruby_font_style.as_deref(), a.ruby_fill.as_deref()), (Some(""), Some(""), Some("")));
+ assert_eq!((a.ruby_fill_tint, a.ruby_overprint_fill), (Some(None), Some(AdornmentOverprint::Auto)));
+
+ // Every setting survives export and import.
+ let mut d = Document::new(&NewDocument::default());
+ let lid = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 200.0), lid, "漢字", ParaFormat::default()).unwrap();
+ d.story_mut(sid).unwrap().format_chars(0.."漢字".len(), |f| {
+ let o = &mut f.over;
+ o.ruby = Some("かん じ".into());
+ o.ruby_type = Some(RubyType::PerCharacter);
+ o.ruby_alignment = Some(RubyAlignment::OneAki);
+ o.ruby_position = Some(RubyPosition::BelowLeft);
+ o.ruby_x_offset = Some(1.5);
+ o.ruby_y_offset = Some(-1.25);
+ o.ruby_font = Some("Source Sans 3".into());
+ o.ruby_font_style = Some("Bold".into());
+ o.ruby_font_size = Some(Some(7.0));
+ o.ruby_x_scale = Some(0.9);
+ o.ruby_y_scale = Some(1.1);
+ o.ruby_open_type_pro = Some(false);
+ o.ruby_auto_tcy_digits = Some(3);
+ o.ruby_auto_tcy_include_roman = Some(true);
+ o.ruby_auto_tcy_auto_scale = Some(false);
+ o.ruby_overhang = Some(true);
+ o.ruby_overhang_amount = Some(RubyOverhang::HalfChar);
+ o.ruby_parent_spacing = Some(RubyParentSpacing::EqualAki);
+ o.ruby_auto_align = Some(false);
+ o.ruby_auto_scaling = Some(true);
+ o.ruby_scaling_min = Some(0.5);
+ o.ruby_fill = Some("[Black]".into());
+ o.ruby_fill_tint = Some(Some(0.5));
+ o.ruby_stroke = Some(String::new());
+ o.ruby_stroke_tint = Some(None);
+ o.ruby_stroke_weight = Some(Some(0.25));
+ o.ruby_overprint_fill = Some(AdornmentOverprint::On);
+ o.ruby_overprint_stroke = Some(AdornmentOverprint::Off);
+ });
+ let a = d.stories[&sid].runs().next().unwrap().1.over.clone();
+ let back = import_idml(&export_idml(&d)).unwrap();
+ let b = back.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();
+ macro_rules! same {
+ ($($f:ident),*) => { $( assert_eq!(a.$f, b.$f, stringify!($f)); )* };
+ }
+ same!(
+ ruby,
+ ruby_type,
+ ruby_alignment,
+ ruby_position,
+ ruby_x_offset,
+ ruby_y_offset,
+ ruby_font,
+ ruby_font_style,
+ ruby_font_size,
+ ruby_x_scale,
+ ruby_y_scale,
+ ruby_open_type_pro,
+ ruby_auto_tcy_digits,
+ ruby_auto_tcy_include_roman,
+ ruby_auto_tcy_auto_scale,
+ ruby_overhang,
+ ruby_overhang_amount,
+ ruby_parent_spacing,
+ ruby_auto_align,
+ ruby_auto_scaling,
+ ruby_scaling_min,
+ ruby_fill,
+ ruby_fill_tint,
+ ruby_stroke,
+ ruby_stroke_tint,
+ ruby_stroke_weight,
+ ruby_overprint_fill,
+ ruby_overprint_stroke
+ );
+ }
diff --cc crates/ui-egui/src/dialogs.rs
index d33123448,48ddf65f4..3457b7773
--- a/crates/ui-egui/src/dialogs.rs
+++ b/crates/ui-egui/src/dialogs.rs
@@@ -2715,23 -2606,7 +2709,21 @@@ fn paragraph_style_options(app: &mut De
});
}
"color" => character_color(&app.ui.language, ui, d, &CharFields { base: &cv, sparse: false }, &doc),
+ "advanced" => advanced_character_formats(&app.ui.language, ui, d, &CharFields { base: &cv, sparse: false }),
+ "openType" => open_type_features(&app.ui.language, ui, d, &CharFields { base: &cv, sparse: false }),
+ "underline" => line_options(&app.ui.language, ui, d, &CharFields { base: &cv, sparse: false }, &doc, "underline"),
+ "strikethrough" => line_options(&app.ui.language, ui, d, &CharFields { base: &cv, sparse: false }, &doc, "strikethrough"),
+ "border" => border_shading(&app.ui.language, ui, d, &pv, &doc, true),
+ "shading" => border_shading(&app.ui.language, ui, d, &pv, &doc, false),
+ "keep" => keep_options(&app.ui.language, ui, d, &pv),
+ "span" => span_columns(&app.ui.language, ui, d, &pv, &doc),
+ "bullets" => {
+ let (char_styles, families, fonts, scope) = ListUi::new_parts(app);
+ let lu =
+ ListUi { char_styles: &char_styles, families: &families, fonts: &fonts, scope, family: &cp.font_family, style: &cp.font_style };
+ bullets_and_numbering(&app.ui.language, ui, d, &pv, &doc, &lu);
+ }
- s if style_cjk::is_section(s) => {
- style_cjk::section(&app.ui.language, ui, d, s, &CharFields { base: &cv, sparse: false }, Some(&pv), &doc)
- }
+ s if style_cjk::is_section(s) => style_cjk::section_ui(app, ui, d, s, &CharFields { base: &cv, sparse: false }, Some(&pv), &doc),
_ => {
egui::Grid::new("psg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Style Name:"));
@@@ -2904,843 -2734,152 +2896,843 @@@ fn style_tabs(lang: &str, ui: &mut egui
d.fields.insert("tabsAlign".into(), serde_json::to_value(align).unwrap_or_default());
}
-/// The section list on the left of the style options dialogs.
-fn section_list(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cjk: bool, sections: &[(&str, &str)]) {
- let sections = style_cjk::sections(cjk, d.id == "paragraphStyleOptions", sections);
- ui.vertical(|ui| {
- ui.set_width(170.0);
- // The dialog has a fixed height; a long list scrolls.
- egui::ScrollArea::vertical().id_salt("style_sections").auto_shrink([false, true]).show(ui, |ui| {
- for (id, label) in &sections {
- if ui.selectable_label(d.s("section") == *id, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
- d.fields.insert("section".into(), json!(id));
- }
- }
- });
- });
+/// A paragraph attribute as Paragraph Style Options shows it: the dialog's edit (`p.<key>`), else
+/// the style's resolved value in `pv`.
+fn para_value(d: &Dialog, pv: &Value, key: &str) -> Value {
+ d.fields.get(&format!("p.{key}")).cloned().unwrap_or_else(|| pv.get(key).cloned().unwrap_or(Value::Null))
}
-/// "Paragraph Style n" / "Character Style n": the first name no style has.
-fn next_style_name(styles: &designcraft_doc::Styles, para: bool) -> String {
- let (base, count) = if para { ("Paragraph Style", styles.paragraph.len()) } else { ("Character Style", styles.character.len()) };
- let taken = |n: &str| if para { styles.para(n).is_some() } else { styles.char_style(n).is_some() };
- // Among count + 1 numbers at least one is free.
- (1..=count + 1).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| format!("{base} {}", count + 1))
+/// Edit paragraph attribute `key`. The value is the whole attribute: `confirm` reads a dotted key
+/// as one field of a rule.
+fn para_set(d: &mut Dialog, key: &str, v: Value) {
+ d.fields.insert(format!("p.{key}"), v);
}
-/// Paragraph or Character Style Options for an existing style (a double-click on it in the styles
-/// panel, or Edit in its menu). [None] and [No Paragraph Style] have no options.
-pub fn open_style_options(app: &mut DesignApp, para: bool, name: &str) {
- if name == if para { designcraft_doc::NO_PARA_STYLE } else { designcraft_doc::NO_CHAR_STYLE } {
- return;
+/// A count attribute (lines, columns), rounded and kept in `range`.
+fn para_count(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, range: (u32, u32)) {
+ let v = para_value(d, pv, key).as_f64();
+ if let Some(n) = crate::widgets::number(ui, &format!("ps{key}"), v, "", 50.0, 0) {
+ let n = if n.is_finite() { n.round().clamp(f64::from(range.0), f64::from(range.1)) as u32 } else { range.0 };
+ para_set(d, key, json!(n));
}
- let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };
- app.ui.dialog = Some(Dialog::new(id, json!({"name": name})));
}
-/// New Paragraph Style… / New Character Style…: the style options for a style made on OK, named
-/// with the next free "Paragraph Style n" / "Character Style n".
-pub fn open_new_style(app: &mut DesignApp, para: bool) {
- let Some(st) = app.session.active() else { return };
- let name = next_style_name(&st.doc.styles, para);
- let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };
- app.ui.dialog = Some(Dialog::new(id, json!({"new": true, "rename": name})));
+fn para_check(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, label: &str) {
+ let mut on = para_value(d, pv, key).as_bool().unwrap_or(false);
+ if ui.checkbox(&mut on, crate::rtl::widget(ui, label)).changed() {
+ para_set(d, key, json!(on));
+ }
}
-/// Character Style Options: General, then the character sections it shares with Paragraph Style
-/// Options. A character style sets only some attributes: the fields show those it and its Based
-/// On set and leave the rest blank. Edits are `c.<attr>` fields (`null` = no longer set), applied
-/// on OK; `new` makes the style instead of editing `name`.
-fn character_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
- let name = d.s("name");
- let new = d.b("new");
- let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return };
- let styles = &doc.styles;
- let style = match styles.char_style(&name) {
- _ if new => designcraft_doc::CharacterStyle { name: String::new(), based_on: None, chars: Default::default(), shortcut: String::new() },
- Some(s) if name != designcraft_doc::NO_CHAR_STYLE => s.clone(),
- _ => {
- crate::rtl::label(ui, format!("No style named {name}"));
- return;
- }
- };
- if !d.fields.contains_key("rename") {
- d.fields.insert("rename".into(), json!(if new { next_style_name(styles, false) } else { name.clone() }));
+fn para_measure(ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, unit: Unit) {
+ let v = para_value(d, pv, key).as_f64();
+ if let Some(n) = crate::widgets::measure(ui, &format!("ps{key}"), v, unit, 80.0) {
+ para_set(d, key, json!(n));
}
- let based = d
- .fields
- .get("basedOn")
- .and_then(Value::as_str)
- .map(str::to_string)
- .or(style.based_on.clone())
- .unwrap_or_else(|| designcraft_doc::NO_CHAR_STYLE.into());
- // The fields show the style's own attributes over those its Based On gives it.
- let mut shown = styles.char_style_attrs(&based);
- shown.merge(&style.chars);
- let base = serde_json::to_value(&shown).unwrap_or_default();
- let cf = CharFields { base: &base, sparse: true };
- let lang = app.ui.language.clone();
- ui.set_min_width(560.0);
- ui.horizontal_top(|ui| {
- // A fixed height: the separator would otherwise stretch the dialog to the window.
- ui.set_min_height(380.0);
- ui.set_max_height(380.0);
- section_list(
- &lang,
- ui,
- d,
- crate::cjk_features(app),
- &[
- ("general", "General"),
- ("chars", "Basic Character Formats"),
- ("advanced", "Advanced Character Formats"),
- ("color", "Character Color"),
- ("openType", "OpenType Features"),
- ("underline", "Underline Options"),
- ("strikethrough", "Strikethrough Options"),
- ],
- );
- ui.separator();
- ui.vertical(|ui| match d.s("section").as_str() {
- "chars" => basic_character_formats(app, ui, d, &cf),
- "advanced" => advanced_character_formats(&lang, ui, d, &cf),
- "color" => character_color(&lang, ui, d, &cf, &doc),
- "openType" => open_type_features(&lang, ui, d, &cf),
- "underline" => line_options(&lang, ui, d, &cf, &doc, "underline"),
- "strikethrough" => line_options(&lang, ui, d, &cf, &doc, "strikethrough"),
- s if style_cjk::is_section(s) => style_cjk::section_ui(app, ui, d, s, &cf, None, &doc),
- _ => {
- egui::Grid::new("csg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
- crate::rtl::label(ui, crate::i18n::tr(&lang, "Style Name:"));
- text_field(ui, d, "rename", 220.0);
- ui.end_row();
- crate::rtl::label(ui, crate::i18n::tr(&lang, "Based On:"));
- egui::ComboBox::from_id_salt("csbased")
- .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&lang, &based)))
- .width(220.0)
- .show_ui(ui, |ui| {
- // Not itself, nor a style based on it.
- for s in styles.character.iter().filter(|s| new || !styles.char_based_on_cycles(&name, &s.name)) {
- if ui.selectable_label(s.name == based, crate::rtl::widget(ui, crate::i18n::style_name(&lang, &s.name))).clicked() {
- d.fields.insert("basedOn".into(), json!(s.name));
- }
- }
- });
- ui.end_row();
- });
- let status = d.s("status");
- if !status.is_empty() {
- crate::rtl::label(ui, egui::RichText::new(status).color(crate::theme::Tokens::get(ui.ctx()).text_strong));
- }
- ui.add_space(8.0);
- crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Style Settings:")).font(semibold(12.0)));
- // What OK would leave the style setting, after its Based On.
- let mut own = serde_json::to_value(&style.chars).unwrap_or_default();
- if let Some(o) = own.as_object_mut() {
- for (k, v) in d.fields.iter().filter_map(|(k, v)| Some((k.strip_prefix("c.")?, v))) {
- if v.is_null() {
- o.remove(k);
- } else {
- o.insert(k.to_string(), v.clone());
- }
- }
- }
- let mut parts = vec![crate::i18n::style_name(&lang, &based).to_string()];
- parts.extend(own.as_object().into_iter().flatten().map(|(k, v)| format!("{}: {}", setting_label(&lang, k), setting_text(v))));
- ui.add(egui::Label::new(egui::RichText::new(parts.join(" + ")).color(crate::theme::Tokens::get(ui.ctx()).text_dim)).wrap());
+}
+
+/// A paragraph attribute chosen from `opts` (serialized value, label).
+fn para_choice(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, opts: &[(&str, &str)]) {
+ let cur = para_value(d, pv, key);
+ let shown = opts.iter().find(|o| cur == o.0).map_or("", |o| crate::i18n::tr(lang, o.1));
+ egui::ComboBox::from_id_salt(("pschoice", key)).selected_text(crate::rtl::widget(ui, shown)).width(200.0).show_ui(ui, |ui| {
+ for (v, label) in opts {
+ if ui.selectable_label(cur == *v, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
+ para_set(d, key, json!(v));
}
- });
+ }
+ });
+}
+
+/// Four per-side values in the order the attribute holds them: top, left, bottom, right. An
+/// edited side stores the whole array.
+fn para_sides(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, field: &dyn Fn(&mut egui::Ui, &str, Option<f64>) -> Option<f64>) {
+ let mut sides: [f64; 4] = serde_json::from_value(para_value(d, pv, key)).unwrap_or_default();
+ let mut changed = false;
+ egui::Grid::new(("pssides", key)).num_columns(4).spacing([8.0, 6.0]).show(ui, |ui| {
+ for (i, label) in ["Top:", "Left:", "Bottom:", "Right:"].into_iter().enumerate() {
+ crate::rtl::label(ui, crate::i18n::tr(lang, label));
+ if let Some(side) = sides.get_mut(i)
+ && let Some(v) = field(ui, &format!("ps{key}{i}"), Some(*side))
+ {
+ *side = v;
+ changed = true;
+ }
+ if i % 2 == 1 {
+ ui.end_row();
+ }
+ }
+ });
+ if changed {
+ para_set(d, key, json!(sides));
+ }
+}
+
+/// A swatch menu with a colour chip per swatch (hidden swatches left out); returns the swatch
+/// picked.
+fn swatch_menu(ui: &mut egui::Ui, doc: &designcraft_doc::Document, id: impl egui::AsIdSalt, current: &str, width: f32) -> Option<String> {
+ let mut picked = None;
+ egui::ComboBox::from_id_salt(id).selected_text(current).width(width).show_ui(ui, |ui| {
+ for w in doc.swatches.iter().filter(|w| !w.hidden) {
+ let (c, g) = crate::widgets::swatch_colors(doc, &w.name, 1.0);
+ ui.horizontal(|ui| {
+ let (r, _) = ui.allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::hover());
+ crate::widgets::paint_chip(ui.painter(), r, c, g);
+ if ui.selectable_label(w.name == current, &w.name).clicked() {
+ picked = Some(w.name.clone());
+ }
+ });
+ }
+ });
+ picked
+}
+
+/// Built-in stroke types of the paragraph border's Type menu (serialized `StrokeType`s).
+const BORDER_TYPES: [&str; 11] =
+ ["solid", "dashed", "dotted", "thickThin", "thinThick", "thinThin", "thickThick", "thinThickThin", "thickThinThick", "wavy", "hashed"];
+
+/// The border's stroke type: a built-in type or one of the document's stroke styles.
+fn border_type_menu(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &designcraft_doc::Document) {
+ use designcraft_doc::StrokeType;
+ let cur: StrokeType = serde_json::from_value(para_value(d, pv, "borderType")).unwrap_or_default();
+ let shown = match &cur {
+ StrokeType::Style { name } => name.clone(),
+ k => crate::i18n::tr(lang, k.label()).to_string(),
+ };
+ egui::ComboBox::from_id_salt("psbordertype").selected_text(crate::rtl::widget(ui, shown)).width(160.0).show_ui(ui, |ui| {
+ for k in BORDER_TYPES {
+ let ty = if k == "dashed" { json!({"kind": k, "pattern": []}) } else { json!({"kind": k}) };
+ let Ok(t) = serde_json::from_value::<StrokeType>(ty.clone()) else { continue };
+ let on = std::mem::discriminant(&t) == std::mem::discriminant(&cur);
+ if ui.selectable_label(on, crate::rtl::widget(ui, crate::i18n::tr(lang, t.label()))).clicked() && !on {
+ para_set(d, "borderType", ty);
+ }
+ }
+ for st in &doc.stroke_styles {
+ let on = matches!(&cur, StrokeType::Style { name } if *name == st.name);
+ if ui.selectable_label(on, &st.name).clicked() {
+ para_set(d, "borderType", json!({"kind": "style", "name": st.name}));
+ }
+ }
+ });
+}
+
+/// Corner size and shape of a border or shading (`key` holds top left, top right, bottom right,
+/// bottom left); an edited corner stores all four.
+fn para_corners(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, units: Unit) {
+ use designcraft_geom::corners::{Corner, CornerShape};
+ let mut corners: [Corner; 4] = serde_json::from_value(para_value(d, pv, key)).unwrap_or_default();
+ let mut changed = false;
+ egui::Grid::new(("pscorners", key)).num_columns(3).spacing([8.0, 6.0]).show(ui, |ui| {
+ for (i, label) in ["Top Left:", "Top Right:", "Bottom Right:", "Bottom Left:"].into_iter().enumerate() {
+ let Some(c) = corners.get_mut(i) else { continue };
+ crate::rtl::label(ui, crate::i18n::tr(lang, label));
+ if let Some(v) = crate::widgets::measure(ui, &format!("ps{key}{i}"), Some(c.size), units, 70.0) {
+ c.size = if v.is_finite() { v.clamp(0.0, 10_000.0) } else { 0.0 };
+ changed = true;
+ }
+ egui::ComboBox::from_id_salt(("pscornershape", key, i))
+ .selected_text(crate::rtl::widget(ui, crate::i18n::tr(lang, c.shape.label())))
+ .width(130.0)
+ .show_ui(ui, |ui| {
+ for shape in CornerShape::ALL {
+ if ui.selectable_label(c.shape == shape, crate::rtl::widget(ui, crate::i18n::tr(lang, shape.label()))).clicked() {
+ c.shape = shape;
+ changed = true;
+ }
+ }
+ });
+ ui.end_row();
+ }
+ });
+ if changed {
+ para_set(d, key, serde_json::to_value(corners).unwrap_or_default());
+ }
+}
+
+/// The colour and tint rows of a border, its gap or shading (`keys`: colour, tint), in a grid.
+fn para_color_tint(
+ ui: &mut egui::Ui,
+ d: &mut Dialog,
+ pv: &Value,
+ doc: &designcraft_doc::Document,
+ keys: (&str, &str),
+ labels: (&str, &str),
+ enabled: bool,
+) {
+ let (color_key, tint_key) = keys;
+ crate::rtl::label(ui, labels.0);
+ let color = para_value(d, pv, color_key).as_str().unwrap_or("").to_string();
+ if let Some(w) = ui.add_enabled_ui(enabled, |ui| swatch_menu(ui, doc, ("pscolor", color_key), &color, 160.0)).inner {
+ para_set(d, color_key, json!(w));
+ }
+ ui.end_row();
+ crate::rtl::label(ui, labels.1);
+ let tint = para_value(d, pv, tint_key).as_f64().map(|t| t * 100.0);
+ if let Some(v) = ui.add_enabled_ui(enabled, |ui| crate::widgets::number(ui, &format!("ps{tint_key}"), tint, "%", 60.0, 0)).inner {
+ para_set(d, tint_key, json!(if v.is_finite() { (v / 100.0).clamp(0.0, 1.0) } else { 1.0 }));
+ }
+ ui.end_row();
+}
+
+/// Paragraph Style Options › Paragraph Border / Paragraph Shading (and the Paragraph Borders and
+/// Shading dialog): on or off, the stroke (border) or colour (shading), corners, offsets, the
+/// edges and width the box follows, and the options for split and consecutive paragraphs.
+fn border_shading(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &designcraft_doc::Document, border: bool) {
+ let key = |field: &str| format!("{}{field}", if border { "border" } else { "shading" });
+ let on_key = key("On");
+ para_check(ui, d, pv, &on_key, crate::i18n::tr(lang, if border { "Border" } else { "Shading" }));
+ let on = para_value(d, pv, &on_key).as_bool().unwrap_or(false);
+ let units = doc.settings.horizontal_units;
+ let head = |ui: &mut egui::Ui, t: &str| {
+ ui.add_space(4.0);
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(lang, t)).font(semibold(12.0)));
+ };
+ ui.add_space(4.0);
+ egui::ScrollArea::vertical().id_salt(("psbsscroll", border)).max_height(330.0).show(ui, |ui| {
+ ui.add_enabled_ui(on, |ui| {
+ if border {
+ head(ui, "Stroke");
+ para_sides(lang, ui, d, pv, &key("Weights"), &|ui: &mut egui::Ui, id: &str, v: Option<f64>| {
+ crate::widgets::number(ui, id, v, " pt", 60.0, 2).map(|w| if w.is_finite() { w.clamp(0.0, 1000.0) } else { 0.0 })
+ });
+ ui.add_space(4.0);
+ } else {
+ head(ui, "Color");
+ }
+ egui::Grid::new(("psbs", border)).num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ if border {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Type:"));
+ border_type_menu(lang, ui, d, pv, doc);
+ ui.end_row();
+ }
+ let (color, tint) = (crate::i18n::tr(lang, "Color:"), crate::i18n::tr(lang, "Tint:"));
+ para_color_tint(ui, d, pv, doc, (&key("Color"), &key("Tint")), (color, tint), true);
+ if border {
+ // The gap colour shows between the dashes, dots or stripes.
+ let solid = para_value(d, pv, "borderType").get("kind").and_then(Value::as_str).is_none_or(|k| k == "solid");
+ let (gap, gap_tint) = (crate::i18n::tr(lang, "Gap Color:"), crate::i18n::tr(lang, "Gap Tint:"));
+ para_color_tint(ui, d, pv, doc, ("borderGapColor", "borderGapTint"), (gap, gap_tint), !solid);
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Cap:"));
+ para_choice(lang, ui, d, pv, "borderCap", &[("butt", "Butt"), ("round", "Round"), ("projecting", "Projecting")]);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Join:"));
+ para_choice(lang, ui, d, pv, "borderJoin", &[("miter", "Miter"), ("round", "Round"), ("bevel", "Bevel")]);
+ ui.end_row();
+ }
+ });
+ head(ui, "Corner Size and Shape");
+ para_corners(lang, ui, d, pv, &key("Corners"), units);
+ head(ui, "Offsets");
+ para_sides(lang, ui, d, pv, &key("Offsets"), &|ui: &mut egui::Ui, id: &str, v: Option<f64>| {
+ crate::widgets::measure(ui, id, v, units, 60.0)
+ });
+ ui.add_space(4.0);
+ egui::Grid::new(("psbsedges", border)).num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Top Edge:"));
+ para_choice(
+ lang,
+ ui,
+ d,
+ pv,
+ &key("Top"),
+ &[("ascent", "Ascent"), ("baseline", "Baseline"), ("emBox", "Em Box Top"), ("leading", "Leading")],
+ );
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Bottom Edge:"));
+ para_choice(lang, ui, d, pv, &key("Bottom"), &[("descent", "Descent"), ("baseline", "Baseline"), ("emBox", "Em Box Bottom")]);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Width:"));
+ para_choice(lang, ui, d, pv, &key("Width"), &[("column", "Column"), ("text", "Text")]);
+ ui.end_row();
+ });
+ ui.add_space(4.0);
+ if border {
+ para_check(ui, d, pv, "borderDisplayIfSplits", crate::i18n::tr(lang, "Display Border if Paragraph Splits Across Frames/Columns"));
+ para_check(ui, d, pv, "borderMerge", crate::i18n::tr(lang, "Merge Consecutive Borders and Shading"));
+ } else {
+ para_check(ui, d, pv, "shadingClip", crate::i18n::tr(lang, "Clip to Frame"));
+ para_check(ui, d, pv, "shadingNonprinting", crate::i18n::tr(lang, "Do not Print or Export"));
+ }
+ });
+ });
+}
+
+/// Paragraph Style Options › Keep Options: lines kept with the next paragraph, the paragraph's
+/// lines kept together (all of them, or its first and last lines), and where it starts.
+fn keep_options(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value) {
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Keep with Next:"));
+ para_count(ui, d, pv, "keepWithNext", (0, 5));
+ crate::rtl::label(ui, crate::i18n::tr(lang, "lines"));
+ });
+ ui.add_space(4.0);
+ para_check(ui, d, pv, "keepLinesTogether", crate::i18n::tr(lang, "Keep Lines Together"));
+ let together = para_value(d, pv, "keepLinesTogether").as_bool().unwrap_or(false);
+ ui.add_enabled_ui(together, |ui| {
+ ui.indent("pskeepall", |ui| {
+ let all = para_value(d, pv, "keepAllLines").as_bool().unwrap_or(true);
+ if ui.radio(all, crate::rtl::widget(ui, crate::i18n::tr(lang, "All Lines in Paragraph"))).clicked() {
+ para_set(d, "keepAllLines", json!(true));
+ }
+ if ui.radio(!all, crate::rtl::widget(ui, crate::i18n::tr(lang, "At Start/End of Paragraph"))).clicked() {
+ para_set(d, "keepAllLines", json!(false));
+ }
+ ui.add_enabled_ui(!all, |ui| {
+ egui::Grid::new("pskeepends").num_columns(3).spacing([8.0, 6.0]).show(ui, |ui| {
+ for (label, key) in [("Start:", "keepFirst"), ("End:", "keepLast")] {
+ crate::rtl::label(ui, crate::i18n::tr(lang, label));
+ para_count(ui, d, pv, key, (1, 50));
+ crate::rtl::label(ui, crate::i18n::tr(lang, "lines"));
+ ui.end_row();
+ }
+ });
+ });
+ });
+ });
+ ui.add_space(6.0);
+ ui.horizontal(|ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Start Paragraph:"));
+ para_choice(
+ lang,
+ ui,
+ d,
+ pv,
+ "startParagraph",
+ &[
+ ("anywhere", "Anywhere"),
+ ("nextColumn", "In Next Column"),
+ ("nextFrame", "In Next Frame"),
+ ("nextPage", "On Next Page"),
+ ("nextOddPage", "On Next Odd Page"),
+ ("nextEvenPage", "On Next Even Page"),
+ ],
+ );
+ });
+}
+
+/// Paragraph Style Options › Span Columns (and the Span Columns dialog): one column, spanning
+/// columns (0 = all), or split into sub-columns with inside and outside gutters; the least space
+/// before and after a spanning or split paragraph.
+fn span_columns(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &designcraft_doc::Document) {
+ use designcraft_doc::SpanColumns;
+ let cur: SpanColumns = serde_json::from_value(para_value(d, pv, "spanColumns")).unwrap_or_default();
+ let same = |a: &SpanColumns, b: &SpanColumns| std::mem::discriminant(a) == std::mem::discriminant(b);
+ let units = doc.settings.horizontal_units;
+ let mut next = None;
+ egui::Grid::new("psspan").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Paragraph Layout:"));
+ let kinds = [("Single Column", SpanColumns::Single), ("Span Columns", SpanColumns::Span(0)), ("Split Column", SpanColumns::Split(2))];
+ // "Span Columns" names both the section and this option, which some languages word differently.
+ let kind_label = |k: &'static str| -> &'static str { crate::i18n::tr_context(lang, k, "paragraphLayout") };
+ let shown = kinds.iter().find(|k| same(&k.1, &cur)).map_or("", |k| kind_label(k.0));
+ egui::ComboBox::from_id_salt("psspankind").selected_text(crate::rtl::widget(ui, shown)).width(200.0).show_ui(ui, |ui| {
+ for (label, v) in kinds {
+ if ui.selectable_label(same(&v, &cur), crate::rtl::widget(ui, kind_label(label))).clicked() && !same(&v, &cur) {
+ next = Some(v);
+ }
+ }
+ });
+ ui.end_row();
+ match cur {
+ SpanColumns::Single => {}
+ SpanColumns::Span(n) => {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Columns:"));
+ let shown = if n == 0 { crate::i18n::tr(lang, "All").to_string() } else { n.to_string() };
+ egui::ComboBox::from_id_salt("psspann").selected_text(crate::rtl::widget(ui, shown)).width(80.0).show_ui(ui, |ui| {
+ if ui.selectable_label(n == 0, crate::rtl::widget(ui, crate::i18n::tr(lang, "All"))).clicked() {
+ next = Some(SpanColumns::Span(0));
+ }
+ for c in 2..=20u32 {
+ if ui.selectable_label(n == c, c.to_string()).clicked() {
+ next = Some(SpanColumns::Span(c));
+ }
+ }
+ });
+ ui.end_row();
+ }
+ SpanColumns::Split(n) => {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Columns:"));
+ if let Some(c) = crate::widgets::number(ui, "pssplitn", Some(f64::from(n)), "", 50.0, 0) {
+ next = Some(SpanColumns::Split(if c.is_finite() { c.round().clamp(2.0, 20.0) as u32 } else { 2 }));
+ }
+ ui.end_row();
+ }
+ }
+ let v_units = doc.settings.vertical_units;
+ let spaces = match cur {
+ SpanColumns::Single => None,
+ SpanColumns::Span(_) => Some(("Space Before Span:", "Space After Span:")),
+ SpanColumns::Split(_) => Some(("Space Before Split:", "Space After Split:")),
+ };
+ if let Some((before, after)) = spaces {
+ for (label, key) in [(before, "spanSpaceBefore"), (after, "spanSpaceAfter")] {
+ crate::rtl::label(ui, crate::i18n::tr(lang, label));
+ para_measure(ui, d, pv, key, v_units);
+ ui.end_row();
+ }
+ }
+ if matches!(cur, SpanColumns::Split(_)) {
+ for (label, key) in [("Inside Gutter:", "splitInsideGutter"), ("Outside Gutter:", "splitOutsideGutter")] {
+ crate::rtl::label(ui, crate::i18n::tr(lang, label));
+ para_measure(ui, d, pv, key, units);
+ ui.end_row();
+ }
+ }
+ });
+ if let Some(v) = next {
+ para_set(d, "spanColumns", serde_json::to_value(v).unwrap_or_default());
+ }
+}
+
+/// Number styles as the list's Format menu shows them (`NumberStyle` values).
+const NUMBER_STYLES: [(&str, &str); 9] = [
+ ("arabic", "1, 2, 3, 4..."),
+ ("upperRoman", "I, II, III, IV..."),
+ ("lowerRoman", "i, ii, iii, iv..."),
+ ("upperLetters", "A, B, C, D..."),
+ ("lowerLetters", "a, b, c, d..."),
+ ("arabicLeadingZero", "01, 02, 03..."),
+ ("arabicThreeDigits", "001, 002, 003..."),
+ ("arabicFourDigits", "0001, 0002, 0003..."),
+ ("symbols", "*, †, ‡, §..."),
+];
+
+/// A list label text (Text After, Number), shown with its tab as `^t`; labels expand
+/// metacharacters, so the typed text is stored as it is.
+fn list_text(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, label: &str, key: &str) {
+ crate::rtl::label(ui, crate::i18n::tr(lang, label));
+ let mut s = para_value(d, pv, key).as_str().unwrap_or("").replace('\t', "^t");
+ if ui.add(egui::TextEdit::singleline(&mut s).desired_width(160.0)).changed() {
+ para_set(d, key, json!(s));
+ }
+ ui.end_row();
+}
+
+/// What the Bullets and Numbering section offers besides the paragraph's attributes: the
+/// document's character styles, the font families for the bullet, the fonts, and the paragraph's
+/// font (the bullet's when it has none of its own).
+struct ListUi<'a> {
+ char_styles: &'a [String],
+ families: &'a [String],
+ fonts: &'a designcraft_fonts::ScopedFonts<'static>,
+ scope: u32,
+ family: &'a str,
+ style: &'a str,
+}
+
+impl ListUi<'_> {
+ fn new_parts(app: &DesignApp) -> (Vec<String>, Vec<String>, designcraft_fonts::ScopedFonts<'static>, u32) {
+ let styles = app.session.active().map(|s| s.doc.styles.character.iter().map(|c| c.name.clone()).collect()).unwrap_or_default();
+ let families = crate::panels::font_menu(app).into_iter().map(|f| f.family).collect();
+ (styles, families, crate::panels::fonts(app), crate::panels::font_scope(app))
+ }
+}
+
+/// A character style for a bullet or number (`key`), [None] first.
+fn list_char_style(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, key: &str, styles: &[String]) {
+ let cur = para_value(d, pv, key).as_str().unwrap_or(designcraft_doc::NO_CHAR_STYLE).to_string();
+ egui::ComboBox::from_id_salt(("pslistcs", key)).selected_text(crate::rtl::widget(ui, crate::i18n::style_name(lang, &cur))).width(200.0).show_ui(
+ ui,
+ |ui| {
+ for n in std::iter::once(designcraft_doc::NO_CHAR_STYLE)
+ .chain(styles.iter().map(String::as_str).filter(|n| *n != designcraft_doc::NO_CHAR_STYLE))
+ {
+ if ui.selectable_label(n == cur, crate::rtl::widget(ui, crate::i18n::style_name(lang, n))).clicked() {
+ para_set(d, key, json!(n));
+ }
+ }
+ },
+ );
+}
+
+/// The bullet character: common bullets, a field, and the font's glyphs in a grid to pick from.
+fn bullet_char(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, lu: &ListUi<'_>) {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Bullet Character:"));
+ ui.horizontal(|ui| {
+ let cur = para_value(d, pv, "bulletChar").as_str().unwrap_or("").to_string();
+ for b in ["\u{2022}", "\u{2013}", "\u{2014}", "\u{00BB}", "*"] {
+ if ui.add_sized([24.0, 20.0], egui::Button::selectable(cur == b, b)).clicked() {
+ para_set(d, "bulletChar", json!(b));
+ }
+ }
+ let mut s = cur;
+ if ui.add(egui::TextEdit::singleline(&mut s).desired_width(36.0)).changed() {
+ para_set(d, "bulletChar", json!(s));
+ }
+ let open = d.b("bulletGlyphs");
+ if ui.selectable_label(open, crate::rtl::widget(ui, crate::i18n::tr(lang, "Glyphs…"))).clicked() {
+ d.fields.insert("bulletGlyphs".into(), json!(!open));
+ }
+ });
+ ui.end_row();
+ if d.b("bulletGlyphs") {
+ ui.label("");
+ ui.vertical(|ui| {
+ ui.set_width(300.0);
+ let font = para_value(d, pv, "bulletFont").as_str().unwrap_or("").to_string();
+ let (family, style) = if font.is_empty() {
+ (lu.family.to_string(), lu.style.to_string())
+ } else {
+ let st = para_value(d, pv, "bulletFontStyle").as_str().unwrap_or("").to_string();
+ let st = if st.is_empty() { lu.fonts.styles(&font).into_iter().next().unwrap_or_else(|| "Regular".into()) } else { st };
+ (font, st)
+ };
+ let mut q = d.s("bulletGlyphQuery");
+ if ui
+ .add(
+ egui::TextEdit::singleline(&mut q)
+ .hint_text(crate::rtl::widget(ui, crate::i18n::tr(lang, "Search: character or U+code")))
+ .desired_width(300.0),
+ )
+ .changed()
+ {
+ d.fields.insert("bulletGlyphQuery".into(), json!(q));
+ }
+ if let (Some(c), _) = crate::panels::glyphs::grid(ui, lu.fonts, lu.scope, &family, &style, &q, 160.0) {
+ para_set(d, "bulletChar", json!(c.to_string()));
+ }
+ });
+ ui.end_row();
+ }
+}
+
+/// The bullet's font family and style ("" = the paragraph's).
+fn bullet_font(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, lu: &ListUi<'_>) {
+ let font = para_value(d, pv, "bulletFont").as_str().unwrap_or("").to_string();
+ let inherit = crate::i18n::tr(lang, "(Paragraph Font)");
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Font Family:"));
+ egui::ComboBox::from_id_salt("psbulletfont").selected_text(if font.is_empty() { inherit } else { font.as_str() }).width(200.0).show_ui(
+ ui,
+ |ui| {
+ if ui.selectable_label(font.is_empty(), inherit).clicked() {
+ para_set(d, "bulletFont", json!(""));
+ para_set(d, "bulletFontStyle", json!(""));
+ }
+ for f in lu.families {
+ if ui.selectable_label(*f == font, f).clicked() {
+ para_set(d, "bulletFont", json!(f));
+ para_set(d, "bulletFontStyle", json!(lu.fonts.styles(f).into_iter().next().unwrap_or_default()));
+ }
+ }
+ },
+ );
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Font Style:"));
+ let style = para_value(d, pv, "bulletFontStyle").as_str().unwrap_or("").to_string();
+ ui.add_enabled_ui(!font.is_empty(), |ui| {
+ egui::ComboBox::from_id_salt("psbulletstyle").selected_text(style.as_str()).width(200.0).show_ui(ui, |ui| {
+ for st in lu.fonts.styles(&font) {
+ if ui.selectable_label(st == style, &st).clicked() {
+ para_set(d, "bulletFontStyle", json!(st));
+ }
+ }
+ });
+ });
+ ui.end_row();
+}
+
+/// Paragraph Style Options › Bullets and Numbering (and the Bullets and Numbering dialog): the
+/// list type and level; the bullet, its font and the text after it, or the list, number style,
+/// number text and where numbering starts and restarts; the label's character style; then where
+/// the label goes (alignment, indents and the tab position of the text after it).
+fn bullets_and_numbering(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, pv: &Value, doc: &designcraft_doc::Document, lu: &ListUi<'_>) {
+ let units = doc.settings.horizontal_units;
+ let kind = para_value(d, pv, "listType").as_str().unwrap_or("none").to_string();
+ let level = para_value(d, pv, "listLevel").as_u64().unwrap_or(1).clamp(1, designcraft_doc::LIST_LEVELS as u64) as u32;
+ egui::ScrollArea::vertical().id_salt("psbnscroll").max_height(340.0).show(ui, |ui| {
+ egui::Grid::new("psbn").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "List Type:"));
+ para_choice(lang, ui, d, pv, "listType", &[("none", "None"), ("bullets", "Bullets"), ("numbers", "Numbers")]);
+ ui.end_row();
+ if kind != "none" {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Level:"));
+ para_count(ui, d, pv, "listLevel", (1, designcraft_doc::LIST_LEVELS as u32));
+ ui.end_row();
+ }
+ match kind.as_str() {
+ "bullets" => {
+ bullet_char(lang, ui, d, pv, lu);
+ bullet_font(lang, ui, d, pv, lu);
+ list_text(lang, ui, d, pv, "Text After:", "listSeparator");
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Character Style:"));
+ list_char_style(lang, ui, d, pv, "bulletCharStyle", lu.char_styles);
+ ui.end_row();
+ }
+ "numbers" => {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "List:"));
+ let list = para_value(d, pv, "listName").as_str().unwrap_or("").to_string();
+ // "" is the story's own list.
+ let name = |n: &str| if n.is_empty() { crate::i18n::tr(lang, "[Default]").to_string() } else { n.to_string() };
+ egui::ComboBox::from_id_salt("pslist").selected_text(name(&list)).width(200.0).show_ui(ui, |ui| {
+ for n in std::iter::once("").chain(doc.settings.lists.iter().map(|l| l.name.as_str())) {
+ if ui.selectable_label(n == list, name(n)).clicked() {
+ para_set(d, "listName", json!(n));
+ }
+ }
+ });
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Format:"));
+ para_choice(lang, ui, d, pv, "numberStyle", &NUMBER_STYLES);
+ ui.end_row();
+ list_text(lang, ui, d, pv, "Number:", "numberExpression");
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Character Style:"));
+ list_char_style(lang, ui, d, pv, "numberCharStyle", lu.char_styles);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Mode:"));
+ let start = para_value(d, pv, "startAt").as_u64();
+ ui.horizontal(|ui| {
+ let shown = crate::i18n::tr(lang, if start.is_some() { "Start At" } else { "Continue from Previous Number" });
+ egui::ComboBox::from_id_salt("psmode").selected_text(crate::rtl::widget(ui, shown)).width(200.0).show_ui(ui, |ui| {
+ if ui
+ .selectable_label(start.is_none(), crate::rtl::widget(ui, crate::i18n::tr(lang, "Continue from Previous Number")))
+ .clicked()
+ {
+ para_set(d, "startAt", Value::Null);
+ }
+ if ui.selectable_label(start.is_some(), crate::rtl::widget(ui, crate::i18n::tr(lang, "Start At"))).clicked()
+ && start.is_none()
+ {
+ para_set(d, "startAt", json!(1));
+ }
+ });
+ if let Some(n) = start
+ && let Some(v) = crate::widgets::number(ui, "psstartat", Some(n as f64), "", 60.0, 0)
+ {
+ para_set(d, "startAt", json!(if v.is_finite() { v.round().clamp(0.0, 1_000_000.0) as u32 } else { 1 }));
+ }
+ });
+ ui.end_row();
+ // Restart Numbers at This Level After: a higher level (any, or one of them).
+ ui.label("");
+ ui.add_enabled_ui(level > 1, |ui| {
+ ui.horizontal(|ui| {
+ para_check(ui, d, pv, "restartNumbers", crate::i18n::tr(lang, "Restart Numbers at This Level After:"));
+ let after = para_value(d, pv, "restartAfterLevel").as_u64().unwrap_or(0) as u32;
+ let label = |n: u32| if n == 0 { crate::i18n::tr(lang, "Any Previous Level").to_string() } else { n.to_string() };
+ egui::ComboBox::from_id_salt("psrestartafter").selected_text(crate::rtl::widget(ui, label(after))).width(140.0).show_ui(
+ ui,
+ |ui| {
+ for n in 0..level {
+ if ui.selectable_label(n == after, crate::rtl::widget(ui, label(n))).clicked() {
+ para_set(d, "restartAfterLevel", json!(n));
+ }
+ }
+ },
+ );
+ });
+ });
+ ui.end_row();
+ }
+ _ => {}
+ }
+ if kind != "none" {
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Alignment:"));
+ let key = if kind == "bullets" { "bulletAlign" } else { "numberAlign" };
+ para_choice(lang, ui, d, pv, key, &[("left", "Left"), ("center", "Center"), ("right", "Right")]);
+ ui.end_row();
+ for (label, key) in [("Left Indent:", "leftIndent"), ("First Line Indent:", "firstLineIndent")] {
+ crate::rtl::label(ui, crate::i18n::tr(lang, label));
+ para_measure(ui, d, pv, key, units);
+ ui.end_row();
+ }
+ // Tab Position: none, or a stop for the text after the label.
+ crate::rtl::label(ui, crate::i18n::tr(lang, "Tab Position:"));
+ ui.horizontal(|ui| {
+ let tab = para_value(d, pv, "listTab").as_f64();
+ let mut on = tab.is_some();
+ if ui.checkbox(&mut on, "").changed() {
+ let left = para_value(d, pv, "leftIndent").as_f64().filter(|v| v.is_finite() && *v > 0.0).unwrap_or(18.0);
+ para_set(d, "listTab", if on { json!(left) } else { Value::Null });
+ }
+ if let Some(t) = tab
+ && let Some(v) = crate::widgets::measure(ui, "pslisttab", Some(t), units, 80.0)
+ {
+ para_set(d, "listTab", json!(if v.is_finite() { v.max(0.0) } else { 0.0 }));
+ }
+ });
+ ui.end_row();
+ }
+ });
+ });
+}
+
+/// Paragraph Borders and Shading, Span Columns, and Bullets and Numbering for the selected
+/// paragraphs: the Paragraph Style Options sections over the paragraphs' attributes (`current`);
+/// OK applies the edits (`p.<key>`) as local formatting.
+fn paragraph_local(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ let Some(doc) = app.session.active().map(|s| s.doc.clone()) else { return };
+ let pv = d.fields.get("current").cloned().unwrap_or_default();
+ let lang = app.ui.language.clone();
+ ui.set_min_width(480.0);
+ match d.s("section").as_str() {
+ "span" => span_columns(&lang, ui, d, &pv, &doc),
+ "bullets" => {
+ let (char_styles, families, fonts, scope) = ListUi::new_parts(app);
+ let (family, style) = (d.s("family"), d.s("style"));
+ let lu = ListUi { char_styles: &char_styles, families: &families, fonts: &fonts, scope, family: &family, style: &style };
+ bullets_and_numbering(&lang, ui, d, &pv, &doc, &lu);
+ }
+ section => {
+ let border = section != "shading";
+ ui.horizontal(|ui| {
+ for (tab, label) in [("border", "Border"), ("shading", "Shading")] {
+ if ui.selectable_label(section == tab, crate::rtl::widget(ui, crate::i18n::tr(&lang, label))).clicked() {
+ d.fields.insert("section".into(), json!(tab));
+ }
+ }
+ });
+ ui.separator();
+ border_shading(&lang, ui, d, &pv, &doc, border);
+ }
+ }
+}
+
+fn section_list(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, cjk: bool, sections: &[(&str, &str)]) {
+ let sections = style_cjk::sections(cjk, d.id == "paragraphStyleOptions", sections);
+ ui.vertical(|ui| {
+ ui.set_width(170.0);
+ // The dialog has a fixed height; a long list scrolls.
+ egui::ScrollArea::vertical().id_salt("style_sections").auto_shrink([false, true]).show(ui, |ui| {
+ for (id, label) in &sections {
+ if ui.selectable_label(d.s("section") == *id, crate::rtl::widget(ui, crate::i18n::tr(lang, label))).clicked() {
+ d.fields.insert("section".into(), json!(id));
+ }
+ }
+ });
+ });
+}
+
+/// "Paragraph Style n" / "Character Style n": the first name no style has.
+fn next_style_name(styles: &designcraft_doc::Styles, para: bool) -> String {
+ let (base, count) = if para { ("Paragraph Style", styles.paragraph.len()) } else { ("Character Style", styles.character.len()) };
+ let taken = |n: &str| if para { styles.para(n).is_some() } else { styles.char_style(n).is_some() };
+ // Among count + 1 numbers at least one is free.
+ (1..=count + 1).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_else(|| format!("{base} {}", count + 1))
+}
+
+/// Paragraph or Character Style Options for an existing style (a double-click on it in the styles
+/// panel, or Edit in its menu). [None] and [No Paragraph Style] have no options.
+pub fn open_style_options(app: &mut DesignApp, para: bool, name: &str) {
+ if name == if para { designcraft_doc::NO_PARA_STYLE } else { designcraft_doc::NO_CHAR_STYLE } {
+ return;
+ }
+ let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };
+ app.ui.dialog = Some(Dialog::new(id, json!({"name": name})));
+}
+
+/// New Paragraph Style… / New Character Style…: the style options for a style made on OK, named
+/// with the next free "Paragraph Style n" / "Character Style n".
+pub fn open_new_style(app: &mut DesignApp, para: bool) {
+ let Some(st) = app.session.active() else { return };
+ let name = next_style_name(&st.doc.styles, para);
+ let id = if para { "paragraphStyleOptions" } else { "characterStyleOptions" };
+ app.ui.dialog = Some(Dialog::new(id, json!({"new": true, "rename": name})));
+}
+
+/// Character Style Options: General, then the character sections it shares with Paragraph Style
+/// Options. A character style sets only some attributes: the fields show those it and its Based
+/// On set and leave the rest blank. Edits are `c.<attr>` fields (`null` = no longer set), applied
+/// on OK; `new` makes the style instead of editing `name`.
+fn character_style_options(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {
+ let name = d.s("name");
+ let new = d.b("new");
+ let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return };
+ let styles = &doc.styles;
+ let style = match styles.char_style(&name) {
+ _ if new => designcraft_doc::CharacterStyle { name: String::new(), based_on: None, chars: Default::default(), shortcut: String::new() },
+ Some(s) if name != designcraft_doc::NO_CHAR_STYLE => s.clone(),
+ _ => {
+ crate::rtl::label(ui, format!("No style named {name}"));
+ return;
+ }
+ };
+ if !d.fields.contains_key("rename") {
+ d.fields.insert("rename".into(), json!(if new { next_style_name(styles, false) } else { name.clone() }));
+ }
+ let based = d
+ .fields
+ .get("basedOn")
+ .and_then(Value::as_str)
+ .map(str::to_string)
+ .or(style.based_on.clone())
+ .unwrap_or_else(|| designcraft_doc::NO_CHAR_STYLE.into());
+ // The fields show the style's own attributes over those its Based On gives it.
+ let mut shown = styles.char_style_attrs(&based);
+ shown.merge(&style.chars);
+ let base = serde_json::to_value(&shown).unwrap_or_default();
+ let cf = CharFields { base: &base, sparse: true };
+ let lang = app.ui.language.clone();
+ ui.set_min_width(560.0);
+ ui.horizontal_top(|ui| {
+ // A fixed height: the separator would otherwise stretch the dialog to the window.
+ ui.set_min_height(380.0);
+ ui.set_max_height(380.0);
+ section_list(
+ &lang,
+ ui,
+ d,
+ crate::cjk_features(app),
+ &[
+ ("general", "General"),
+ ("chars", "Basic Character Formats"),
+ ("advanced", "Advanced Character Formats"),
+ ("color", "Character Color"),
+ ("openType", "OpenType Features"),
+ ("underline", "Underline Options"),
+ ("strikethrough", "Strikethrough Options"),
+ ],
+ );
+ ui.separator();
+ ui.vertical(|ui| match d.s("section").as_str() {
+ "chars" => basic_character_formats(app, ui, d, &cf),
+ "advanced" => advanced_character_formats(&lang, ui, d, &cf),
+ "color" => character_color(&lang, ui, d, &cf, &doc),
+ "openType" => open_type_features(&lang, ui, d, &cf),
+ "underline" => line_options(&lang, ui, d, &cf, &doc, "underline"),
+ "strikethrough" => line_options(&lang, ui, d, &cf, &doc, "strikethrough"),
- s if style_cjk::is_section(s) => style_cjk::section(&lang, ui, d, s, &cf, None, &doc),
++ s if style_cjk::is_section(s) => style_cjk::section_ui(app, ui, d, s, &cf, None, &doc),
+ _ => {
+ egui::Grid::new("csg").num_columns(2).spacing([8.0, 6.0]).show(ui, |ui| {
+ crate::rtl::label(ui, crate::i18n::tr(&lang, "Style Name:"));
+ text_field(ui, d, "rename", 220.0);
+ ui.end_row();
+ crate::rtl::label(ui, crate::i18n::tr(&lang, "Based On:"));
+ egui::ComboBox::from_id_salt("csbased")
+ .selected_text(crate::rtl::widget(ui, crate::i18n::style_name(&lang, &based)))
+ .width(220.0)
+ .show_ui(ui, |ui| {
+ // Not itself, nor a style based on it.
+ for s in styles.character.iter().filter(|s| new || !styles.char_based_on_cycles(&name, &s.name)) {
+ if ui.selectable_label(s.name == based, crate::rtl::widget(ui, crate::i18n::style_name(&lang, &s.name))).clicked() {
+ d.fields.insert("basedOn".into(), json!(s.name));
+ }
+ }
+ });
+ ui.end_row();
+ });
+ let status = d.s("status");
+ if !status.is_empty() {
+ crate::rtl::label(ui, egui::RichText::new(status).color(crate::theme::Tokens::get(ui.ctx()).text_strong));
+ }
+ ui.add_space(8.0);
+ crate::rtl::label(ui, egui::RichText::new(crate::i18n::tr(&lang, "Style Settings:")).font(semibold(12.0)));
+ // What OK would leave the style setting, after its Based On.
+ let mut own = serde_json::to_value(&style.chars).unwrap_or_default();
+ if let Some(o) = own.as_object_mut() {
+ for (k, v) in d.fields.iter().filter_map(|(k, v)| Some((k.strip_prefix("c.")?, v))) {
+ if v.is_null() {
+ o.remove(k);
+ } else {
+ o.insert(k.to_string(), v.clone());
+ }
+ }
+ }
+ let mut parts = vec![crate::i18n::style_name(&lang, &based).to_string()];
+ parts.extend(own.as_object().into_iter().flatten().map(|(k, v)| format!("{}: {}", setting_label(&lang, k), setting_text(v))));
+ ui.add(egui::Label::new(egui::RichText::new(parts.join(" + ")).color(crate::theme::Tokens::get(ui.ctx()).text_dim)).wrap());
+ }
+ });
});
}
diff --cc docs/cjk.md
index 035b732f5,77ad82798..c5d651cee
--- a/docs/cjk.md
+++ b/docs/cjk.md
@@@ -37,10 -37,13 +37,13 @@@ presets or tables are copied. Our defau
| Korean line breaking | at spaces (Hangul everywhere, hanja in Korean text); per-paragraph character-based breaking (`koreanCharBreaks`); DesignCraft-only, not in IDML |
| Mojikumi | tables and paragraph references kept through IDML; not applied (Preflight says so) |
| Aki, tsume, jidori | done ([cjk-typography.md](cjk-typography.md)) |
- | Character alignment, leading model | em box top / centre / bottom, ICF from ascender and descender, roman baseline; aki above / below, centre (centre down as centre); under aki below a line's leading is the space to the line below it; with the Japanese composers (`Composer::Japanese`, `JapaneseSingleLine`, IDML `HL Composer J` / `HL Single J`), the others set lines baseline to baseline on the Roman baseline |
- | Tate-chu-yoko | manual, with offsets; no auto, 3+ digits overflow the em |
- | Ruby | group ruby only, fixed 50 % size, no options, doesn't affect leading |
- | Kenten | the IDML kinds and a custom character, drawn as characters; no position, size, alignment, colour or font |
-| Character alignment, leading model | em box top / centre / bottom, ICF top / bottom (`BASE` `icft`/`icfb`, else the em box inset by 5%), roman baseline; aki above / below, centre (centre down as centre) |
++| Character alignment, leading model | em box top / centre / bottom, ICF top / bottom (`BASE` `icft`/`icfb`, else the em box inset by 5%), roman baseline; aki above / below, centre (centre down as centre); under aki below a line's leading is the space to the line below it; with the Japanese composers (`Composer::Japanese`, `JapaneseSingleLine`, IDML `HL Composer J` / `HL Single J`), the others set lines baseline to baseline on the Roman baseline |
+ | Tate-chu-yoko | manual, with offsets; auto tate-chu-yoko of short digit runs (with roman letters when asked) in vertical text, narrowed to fit the em (`type.autoTateChuYoko`, IDML `AutoTcy`, `AutoTcyIncludeRoman`); manual groups of 3+ digits overflow the em |
+ | Ruby | group and per-character (jukugo) ruby; alignment (shoulder, centre, end, justify, JIS 1-2-1, equal aki, 1 ruby-character aki); above/right or below/left with offsets; font, size (½ by default), scales, OpenType `ruby` glyphs, auto tate-chu-yoko of digits; overhang onto kana and punctuation; parent spacing and automatic narrowing when the ruby is longer; flush with the line edge (a group stays on the line of each neighbour its ruby overhangs, so the reserved spacing holds at line edges); set beyond kenten on the same side; fill, stroke, tint, weight, and overprint in Overprint Preview; every setting through `type.ruby` and IDML. Doesn't affect leading; PDF export writes no overprint (Preflight and the export say so) |
+ | Kenten | the kinds and a custom mark (up to 8 characters) in its own font; size, x/y scale, distance, above/right or below/left, centred or at the character's start; fill, stroke, tints, weight, and overprint in Overprint Preview (`type.kenten`, IDML `Kenten*`). The character set (input mode) is kept, not converted; PDF export writes no overprint |
+ | Shatai | magnification, angle, adjust rotation and adjust tsume on screen, in PDF, outlines and type on a path (`type.shatai`, IDML `Shatai*`) |
+ | Rotate roman, roman word break | half-width characters upright in vertical text (`type.rotateRoman`, IDML `RotateSingleByteCharacters`); breaks between Latin, Greek or Cyrillic letters without a hyphen (`type.romanWordBreak`, IDML `AllowArbitraryHyphenation`) |
+ | Grid alignment | against the baseline grid: roman baseline, em box top / centre / bottom, ICF top / bottom; first line only; gyoudori (auto or N grid lines) and paragraph gyoudori (`type.gridSettings`, IDML `GridAlignment`, `GridGyoudori`, `ParagraphGyoudori`). No frame grid; vertical frames have no baseline grid |
| Composite fonts | done: model, `style.compositeFont.*`, shaping, IDML, font list, replace and Preflight; no dialog |
| Languages | Japanese, Korean, Simplified and Traditional Chinese reach the shaper (`locl`), font fallback, line breaking and typographer's quotes; IDML language names are kept as written; locale codes (`ja_JP`, `ko-KR`, `de_DE_2006`) are their language and region, and Chinese is also recognised in its common spellings ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`) |
| Missing glyphs | as in InDesign: characters the applied font lacks are drawn as its missing-glyph box (screen and PDF) and listed by Preflight; the document setting Draw Missing Glyphs from Fallback Fonts (Preferences › Composition, off in new documents and IDML imports, on in documents saved before it existed) draws them from fallback fonts instead |