DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge upstream main into fix/29-kerning-across-runs
aiongga82174d53ed2
diff --cc Cargo.lockindex 9a27f0d7a,9473c974a..f551976b0--- a/Cargo.lock+++ b/Cargo.lock@@@ -855,9 -870,8 +870,9 @@@ dependencies =[[package]]name = "designcraft"- version = "0.2.1"+ version = "0.5.0"dependencies = [+ "arboard","designcraft-engine","designcraft-ui-egui","eframe",diff --cc ROADMAP.mdindex 55460efec,86a435456..fb5b68c88--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -11,13 -13,14 +13,14 @@@ DesignCraft aims at full Adobe InDesig**Working today**- Document model: facing/non-facing spreads, parent pages with page-number markers, sections, layers, frames (text / graphic / unassigned), threaded stories, paragraph/character/object styles with based-on, swatches (process/spot/tints/gradients), corner options, text wrap, drop shadow, opacity/blend.-- Text engine: Knuth–Plass paragraph composer and single-line composer, dictionary hyphenation (public-domain Moby list + our own trained Liang patterns), justification with word/letter/glyph-scaling ranges, keep options (keep with next, keep lines together, widows/orphans), balance ragged lines, optical margin alignment, hyphenation zone/limit, columns, threading across frames and spreads, tabs, bullets/numbering, rules, shading, baseline grid, first-baseline options, vertical justification, wrap exclusions, overset detection, caret/hit testing.+- Text engine: Knuth–Plass paragraph composer and single-line composer, dictionary hyphenation (public-domain Moby list + our own trained Liang patterns), justification with word/letter/glyph-scaling ranges, keep options (keep with next, keep lines together — at start/end of paragraph by default, as in InDesign — widows/orphans), balance ragged lines, optical margin alignment, hyphenation zone/limit, columns, threading across frames and spreads, tabs, bullets/numbering, rules, shading, baseline grid, first-baseline options, vertical justification, wrap exclusions, overset detection, caret/hit testing.+ - FID2: IDML underline/strikethrough Text Color resets survive style inheritance and roundtrip. Raster and PDF paint underlines behind glyphs, retain strikethrough above, and center rules on their offsets; synthetic overlap tests cover both backends.- Rendering: vello_cpu (SIMD, multithreaded) — pages, items, images with mip levels, gradients, composed text.- UI (egui): application bar + menus, Control panel (object and text modes), Tools panel with flyouts, document tabs, rulers, pasteboard, guides (margins, columns, bleed, baseline grid), frame edges, selection handles, text ports and threads, Properties / Pages / Layers dock, Swatches, Styles, Character, Paragraph, Stroke, Text Wrap panels, New Document and Preferences dialogs, Quick Apply (⌘Return), 4 brightness themes.- Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows.- Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom.- - PDF export (krilla): real selectable text with embedded font subsets, DeviceCMYK/RGB + spot Separations, bleed boxes, crop/bleed marks + page info, pages or spreads, PDF/A-2b (PDF/X-4 output intent pending) — `file.exportPdf`, File › Export PDF…, `designcraft-cli run --export out.pdf`.+ - PDF export (krilla): real selectable text with embedded font subsets, DeviceCMYK/RGB + spot Separations, bleed boxes, crop/bleed marks + page info, pages or spreads, PDF/A-2b (PDF/X-4 output intent pending) — `file.exportPdf`, File › Export PDF…, `designcraft-cli run --export out.pdf`. File › Export PDF… now opens an "Export PDF" options dialog (General / Compression / Marks and Bleeds / Advanced) and remembers the last-used settings across exports and sessions.-- IDML interchange (`designcraft-idml`): export and import of swatches, styles, fonts, preferences, parent spreads, spreads/pages, frames, groups, images (embedded or linked), formatted threaded stories — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`).+- IDML interchange (`designcraft-idml`): export and import of swatches, styles, fonts, preferences, parent spreads, spreads/pages, frames, groups, images (embedded or linked), formatted threaded stories; attributes a file leaves unset take InDesign's defaults (Keep Lines Together at start/end of paragraph, 12 pt corners, paragraph rules in Text Color, auto-sizing from the centre, numbered lists restarting in each story, alternating table fills Black 20 % / None; a tint of −1 is the colour's own; frames take the fill, stroke, corners and Text Frame Options they don't write from their object style chain, then [None]) — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`).- Tables (M8): tables anchored in stories (header/footer/body rows, merged cells, per-edge strokes, fills + alternating fills, insets, vertical justification, at-least/exact row heights); composed into the text column (columns scale to fit, rows break across columns/frames with repeating headers/footers, overset); rendered, exported to PDF (real text) and IDML (export + import); Table menu, Table panel, Create Table dialog, caret/typing/Tab navigation and cell selection in cells; `table.*` commands.- Hyperlinks (text or frames → URL / e-mail / page) and bookmarks, exported as PDF link annotations and outline.- EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`).@@@ -33,9 -37,9 +37,10 @@@- Missing glyphs, as in InDesign: a character the applied font lacks is drawn as that font's missing-glyph box (its .notdef; a drawn box when the font's is empty), on screen and in PDF (as a path, so PDF/A and PDF/UA exports take it), and Preflight lists the characters by font. Preferences › Composition › Draw Missing Glyphs from Fallback Fonts (`document.preferences {glyphFallback}`, stored with the document) draws them from other fonts instead; it is off in new documents and IDML imports, on in documents saved before it existed. A missing font's substitute always uses fallback fonts.- Damage-region repaint: after an edit the canvas re-renders only the frames whose composed text (or the items that) changed and patches its texture — pixel-identical to a full render; typing in a frame repaints in under a millisecond instead of a full-viewport render (22 ms measured on the sample).- Crash recovery: unsaved documents are written to the recovery folder every 30 s and reopened (unsaved, remembering their files) after a crash; File › Revert and Save a Copy…; `file.recovery.*`, `file.revert`, `file.saveACopy`.+ - Graphics backend chosen before the window exists (DirectX 12 on Windows, Vulkan on Linux, Metal on macOS, OpenGL as the fallback; `WGPU_BACKEND` overrides) with a start-up fallback: a backend whose start never showed a frame is skipped at the next start and the status bar says so (`gpu.json`). Found on an AMD hybrid-graphics laptop whose Vulkan driver faulted at the first present.- Edit › Paste Into (copied objects become a frame's content, clipped by it; rendered, PDF and IDML both ways — verified in InDesign 2026); Polygon Settings (sides, star inset; double-click the Polygon tool).- Color panel (fill/stroke proxy, CMYK/RGB/Lab sliders with channel ramps, tint slider for swatches, spectrum ramp, Add to Swatches) and Color Picker (double-click the proxy); mixed colours are unnamed (not listed in Swatches until added); `object.color`, `swatch.addToSwatches`, `swatch.addUnnamed`.+- Threading: click a selected text frame's in or out port (overset or not) to load the text cursor, then click a frame to thread it (stories merge), click empty space for a column-wide frame down to the bottom margin, or drag a frame; Shift-click autoflows, Alt-click stays loaded; click the linked frame or double-click a port to break the thread; Esc unloads. Link and unthread cursors show where a click threads or unthreads. `text.thread`, `text.unthread`, `text.removeFromThread`.- Place text files: Word (.docx: styles by name with their attributes, bold/italic/underline/size/font, footnotes, tables, tabs, breaks), RTF and plain text, into the insertion point, the selected frame or a new frame; autoflow adds pages and threaded frames until the text fits; Remove Styles option (`designcraft-textimport`).- Gradient Feather (⇧G tool, `object.gradientFeather`): objects fade along a linear or radial opacity gradient, on screen and as a soft mask in PDF.- Script Label (`object.label`, `object.findByLabel`), alt text (`object.altText`), Isolate Blending / Knockout Group (`object.transparencyGroup`; on screen, PDF isolates), Table ▸ Sort (`table.sortRows`, numeric-aware, header/footer fixed).@@@ -104,10 -109,10 +111,10 @@@- Split Window / New Window (`window.split`, `window.newWindow`, Window ▸ Arrange): two side-by-side views of the document with their own zoom, scroll and render cache. New Window puts the second view in its own OS window (an egui viewport; a floating window on the web).- Transparency flattener (`file.exportPdf {flatten: high|medium|low|ppi}`, Edit ▸ Transparency Flattener Presets): each object involving transparency becomes an opaque image of its area over what's beneath it, so everything else stays vector (spreads with transparent parent items are rasterised whole).- Video and sound (place .mp4/.mov/.webm/.mp3/.wav…, `media.options/get`, Media panel): media frames show a poster or placeholder on screen, in print and in PDF, and export as HTML5 `<video>`/`<audio>` in EPUB. Interactive PDF export (`file.exportPdf {media: true}`, File ▸ Export PDF (Interactive)) embeds each file and plays it in a Screen annotation through a rendition action (controls, loop, play on page load). No in-app playback.-- Right-to-left text (World-Ready basics): right-to-left runs are shaped right to left, lines are reordered by the Unicode Bidirectional Algorithm (matched against the reference implementation), Paragraph Direction (`type.para {direction}`, Paragraph panel, IDML ParagraphDirection, EPUB `dir`). Digits (`digits`: Default, Arabic, Hindi, Farsi, Native by language; Character panel for right-to-left text; IDML DigitsType) draw 0–9 in another script. Kashidas (`kashidas` paragraph attribute, on by default): justified Arabic lines stretch at one join per word (after seen/sad when possible, never inside lam–alef) with a drawn tatweel before word spaces widen. Carets follow the drawing: the caret before a right-to-left glyph sits at its right edge, arrow keys move as drawn (by words in the line's direction), clicks find the nearest drawn caret position and selections highlight the selected glyphs. Binding: Right to Left (Document Setup, `layout.documentSetup {binding}`, IDML PageBinding) makes page 1 a left page and lays spreads out right to left.+- Right-to-left text (World-Ready basics): right-to-left runs are shaped right to left, lines are reordered by the Unicode Bidirectional Algorithm (matched against the reference implementation), Paragraph Direction (`type.para {direction}`, Paragraph panel, IDML ParagraphDirection, EPUB `dir`). Digits (`digits`: Default, Arabic, Hindi, Farsi, Native by language; Character panel for right-to-left text; IDML DigitsType) draw 0–9 in another script. Kashidas (`kashidas` paragraph attribute, on by default; IDML Kashidas): justified Arabic lines stretch at one join per word (after seen/sad when possible, never inside lam–alef) with a drawn tatweel before word spaces widen. Carets follow the drawing: the caret before a right-to-left glyph sits at its right edge, arrow keys move as drawn (by words in the line's direction), clicks find the nearest drawn caret position and selections highlight the selected glyphs. Binding: Right to Left (Document Setup, `layout.documentSetup {binding}`, IDML PageBinding) makes page 1 a left page and lays spreads out right to left.- - Interface language (Edit ▸ Interface Language, `app.language`): German, French, Spanish, Japanese, Simplified Chinese and Arabic menu titles, common menu items and panel names (our own translations). Common dialog, panel and tooltip labels are also localized, with English fallback for untranslated strings. Arabic translations cover every key in the shared interface translation table, including menu commands and utility labels. The Type menu's Story Direction, Horizontal/Vertical, Tate-Chu-Yoko, Ruby… and Kenten are translated too. Arabic labels use Unicode bidi run ordering and contextual shaping; welcome and new-document form layouts follow RTL direction independently of document binding. CJK and Arabic glyphs come from [craft-fonts](https://github.com/storytold/craft-fonts) when built with `CRAFT_FONTS_DIR` (all releases): BIZ UDPGothic and Noto Sans CJK SC for the UI (Chinese forms first in the Chinese interface), Noto Sans Arabic, and Mincho for Japanese documents (the web build embeds BIZ UDPGothic only); otherwise from system fonts.+ - Interface language (Edit ▸ Interface Language, `app.language`): German, French, Spanish, Italian, Japanese, Simplified Chinese and Arabic menu titles, common menu items and panel names (our own translations). Common dialog, panel and tooltip labels are also localized, with English fallback for untranslated strings. Arabic translations cover every key in the shared interface translation table, including menu commands and utility labels. The Type menu's Story Direction, Horizontal/Vertical, Tate-Chu-Yoko, Ruby… and Kenten are translated too. Arabic labels use Unicode bidi run ordering and contextual shaping; welcome and new-document form layouts follow RTL direction independently of document binding. CJK and Arabic glyphs come from [craft-fonts](https://github.com/storytold/craft-fonts) when built with `CRAFT_FONTS_DIR` (all releases): BIZ UDPGothic and Noto Sans CJK SC for the UI (Chinese forms first in the Chinese interface), Noto Sans Arabic, and Mincho for Japanese documents (the web build embeds BIZ UDPGothic only); otherwise from system fonts. Ukrainian covers all 1,430 existing catalog keys, including publishing dialogs and built-in names, with persisted selection, grammatical count captions, English fallback and bundled Cyrillic UI glyph coverage.- Page transitions (`page.transition/transitions`, Page Transitions panel): twelve transition types with speed and direction per spread, written into exported PDFs as `/Trans` entries through an incremental update.- - PDF/X-4 export (`file.exportPdf {standard: "x4"}`): an output intent with our own Generic CMYK ICC profile (lut16 tables generated from the parametric press model), GTS_PDFXVersion in Info and XMP, and built-in PDF/X-4 checks reported as warnings. qpdf finds no errors in the result.+ - PDF/X-4 export (`file.exportPdf {standard: "x4"}`): an output intent with our own Generic CMYK ICC profile (lut16 tables generated from the parametric press model), GTS_PDFXVersion in Info and XMP, `pdf:Trapped` in XMP as in Info, RGB images without a profile tagged sRGB, no image interpolation (none in PDF/A either), and built-in PDF/X-4 checks reported as warnings. qpdf finds no errors in the result.- EPS place: placed at its (high-resolution) bounding box and shown, printed and exported through its TIFF preview, or a placeholder when it has none. PostScript itself isn't interpreted.- 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.diff --cc crates/compose/src/lib.rsindex 23971ec30,3dd7c25b3..f8c77d013--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -691,40 -727,27 +764,42 @@@ fn compose_with_db(doc: &Document, stor);}}+ // Rules in Text Color: the colour of the paragraph's first character (rule above) and last+ // character (rule below).+ let text_color = |g: Option<&Glyph>| {+ g.and_then(|g| table.styles.get(g.style as usize))+ .map_or((base_chars.fill.clone(), base_chars.fill_tint), |s| (s.fill.clone(), s.fill_tint))+ };+ let (above, below) = (text_color(sp.glyphs.iter().find(|g| g.len > 0)), text_color(sp.glyphs.iter().rev().find(|g| g.len > 0)));+ let rule_color = |r: &designcraft_doc::Rule, text: &(String, f32)| {+ if r.color == designcraft_doc::TEXT_COLOR { text.clone() } else { (r.color.clone(), r.tint) }+ };+ let drop_cap = split_drop_cap(db, &mut sp.glyphs, drop_end, pp.drop_cap_lines, base_leading, base_cap, drop_grid, drop_align);// List labels take the default super/subscript settings.let label_env = shape::TypeEnv { adv: Default::default(), ..env };- match pp.list_type {+ let list_label = match pp.list_type {+ // An empty paragraph has no bullet or number, and the numbering carries on past it.- designcraft_doc::ListType::Numbers | designcraft_doc::ListType::Bullets if prange.is_empty() => {}++ designcraft_doc::ListType::Numbers | designcraft_doc::ListType::Bullets if prange.is_empty() => None,designcraft_doc::ListType::Numbers if !pp.list_name.is_empty() => {// A named list: carries on past other paragraphs (and from earlier stories).let n = named_numbers.get(pi).copied().flatten().unwrap_or(1);- Some(format!("{}.{}", pp.number_style.format(n), pp.list_separator))- let label = pp.number_label(n);- prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);++ Some(pp.number_label(n))}designcraft_doc::ListType::Numbers => {- list_counter = pp.start_at.map_or(list_counter + 1, |s| s.max(1));- Some(format!("{}.{}", pp.number_style.format(list_counter), pp.list_separator))+ list_counter = pp.start_at.map_or(list_counter.saturating_add(1), |s| s.max(1));- let label = pp.number_label(list_counter);- prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);++ Some(pp.number_label(list_counter))+ }- designcraft_doc::ListType::Bullets => Some(format!("{}{}", pp.bullet_char, pp.list_separator)),++ designcraft_doc::ListType::Bullets => Some(pp.bullet_label()),+ designcraft_doc::ListType::None => {+ list_counter = 0;+ None}- designcraft_doc::ListType::Bullets => {- let label = pp.bullet_label();- prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);+ };+ if let Some(label) = list_label {+ let n = prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);+ for g in sp.glyphs.iter_mut().take(n) {+ g.list_label = true;}- designcraft_doc::ListType::None => list_counter = 0,}if pi == 0&& let Some(label) = &opts.label@@@ -741,16 -764,88 +816,84 @@@apply_desired_spacing(&mut glyphs, &pp);let hyph_after = hyphenation_points(&story.text, &glyphs, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars));let base_size = base_chars.size;- let base_leading = match base_chars.leading {- designcraft_doc::Leading::Auto => base_size * pp.auto_leading,- designcraft_doc::Leading::Points(v) => v,- };let spacing = spacing_for(&pp, base_size);+ // A paragraph set across the columns moves on to the next frame where others move on to+ // the next column.+ let spanning = matches!(pp.span_columns, SpanColumns::Span(n) if n != 1);+ span_paras[pi] = spanning;+ // Consecutive paragraphs with the same Split Columns settings share a split block; within+ // it, a paragraph moves on to the next sub-column.+ let split_cfg = SplitCfg::of(&pp);+ split_paras[pi] = split_cfg.is_some();+ if cur.split.is_some_and(|s| Some(s.cfg) != split_cfg) {+ cur.split = None;+ }+ let next_column = |cur: &mut Cursor| {+ if spanning {+ cur.next_frame()+ } else if cur.can_next_sub() {+ cur.next_sub()+ } else {+ cur.next_column(&cols)+ }+ };+ // A paragraph start or a break character; Next Column while a paragraph spans columns is+ // the next frame, as above.+ let begin_at = |cur: &mut Cursor, start: StartParagraph| match start {+ StartParagraph::NextColumn => next_column(cur),+ other => cur.start(other, &cols, frames, doc),+ };// Paragraph start options.+ if let Some(start) = after_break+ && cur.last_baseline.is_some()+ {+ begin_at(&mut cur, start);+ }if force_col[pi] {- cur.next_column(&cols);+ next_column(&mut cur);}if cur.last_baseline.is_some() {- match pp.start_paragraph {- StartParagraph::NextColumn => cur.next_column(&cols),- StartParagraph::NextFrame | StartParagraph::NextPage | StartParagraph::NextOddPage | StartParagraph::NextEvenPage => cur.next_frame(),- StartParagraph::Anywhere => {}+ begin_at(&mut cur, pp.start_paragraph);+ }+ if spanning && cur.fi < frames.len() {+ // Close the band: the paragraph goes below the deepest of its columns, which are+ // balanced first.+ let key = cur.band_key();+ let deepest = out.frames[cur.fi]+ .lines+ .get(cur.band.line0..)+ .unwrap_or_default()+ .iter()+ .map(|l| (l.baseline, l.descent))+ .max_by(|a, b| (a.0 + a.1).total_cmp(&(b.0 + b.1)));+ if let Some((baseline, descent)) = deepest {+ let bottom = baseline + descent;+ let multi = cols[cur.fi].len() > 1;+ let active = trial.as_ref().is_some_and(|t| t.key == key && t.span == pi);+ if !active && let Some(t) = trial.take() {+ set_limit(&mut limits, t.key, None);+ }+ if multi && (active || limit_of(&limits, key).is_none() && balance_runs < balance_budget) {+ let top = cur.clip(cols[cur.fi][0]).y0;+ let mut t = trial.take().unwrap_or(Trial { key, span: pi, lo: top, hi: bottom, tries: 0, done: false });+ // This layout fits: its bottom is the best so far.+ t.hi = t.hi.min(bottom);+ let next = if t.done { t.hi } else { t.next() };+ set_limit(&mut limits, key, Some(next));+ if !t.done {+ trial = Some(t);+ balance_runs += 1;+ rewind(key.1, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap);+ pi = key.1;+ continue 'paras;+ }+ }+ cur.col = 0;+ cur.last_baseline = Some(baseline);+ cur.last_descent = descent;+ } else if cur.col != 0 {+ cur.col = 0;+ cur.resume();}}if cur.last_baseline.is_some() {@@@ -765,44 -867,31 +915,46 @@@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;+ // The drop cap's line (frame, index) and the baseline it sits on, once that line is set.+ let mut drop_line: Option<(usize, usize)> = None;+ let mut drop_baseline: Option<f64> = None;loop {if cur.fi >= frames.len() {+ if let Some(j) = trial_failed(&mut trial, &mut limits, balance_runs < balance_budget) {+ balance_runs += 1;+ rewind(j, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap);+ pi = j;+ continue 'paras;+ }out.overset_at = Some(glyphs.get(g0).map(|g| g.byte).unwrap_or(prange.start));// The part of the paragraph that fits keeps its shading and border.para_box_decos(&mut out, pi, &pp);break 'paras;}let f = &frames[cur.fi];- let col = cols[cur.fi][cur.col.min(cols[cur.fi].len() - 1)];- let col = match pp.span_columns {- SpanColumns::Span(n) if cur.col == 0 => {- let n = if n == 0 { cols[cur.fi].len() } else { (n as usize).min(cols[cur.fi].len()) };- let other = cols[cur.fi][n - 1];- Rect::new(col.x0.min(other.x0), col.y0, col.x1.max(other.x1), col.y1)- }- _ => col,- };+ let base = cols[cur.fi][cur.col.min(cols[cur.fi].len() - 1)];+ let col = cur.clip(base);+ // A spanning paragraph isn't held to the balanced bottom of the columns above it.+ let col = if spanning { span_rect(&cols[cur.fi], Rect::new(col.x0, col.y0, col.x1, base.y1), pp.span_columns) } else { col };+ let col = cur.split_rect(col);// Estimate slots for the breaker with the paragraph's base leading.- let est_first = cur.next_baseline(f, col, base_leading, base_chars.size * 0.75, &pp);- let slots = estimate_slots(f, col, est_first, base_leading, base_chars.size, &glyphs[g0..], &pp, line_no);+ let est_asc = base_chars.size * 0.75;+ let est_tops = Tops { typo_ascent: est_asc, cap: est_asc * 0.72, xh: est_asc * 0.5 };+ let est_first = cur.next_baseline(f, col, base_leading, est_asc, est_tops, &pp);+ let est_jump = cur.jump(f, base_leading, est_asc, est_tops);+ let slots = estimate_slots(f, col, est_first, est_jump, base_leading, base_chars.size, &glyphs[g0..], &pp, line_no);let width = |j: usize| -> f64 {let (x0, x1) = slots.get(j).copied().unwrap_or((col.x0, col.x1));- let ind = pp.left_indent + pp.right_indent + if line_no + j == 0 { pp.first_line_indent } else { 0.0 };+ // Beside the drop cap (in the column the paragraph starts in), its width; else the+ // first-line indent.+ let ind = pp.left_indent+ + pp.right_indent+ + match &drop_cap {+ Some(dc) if line_no + j < dc.lines && col_first_line == 0 => dc.indent(),+ _ if line_no + j == 0 => pp.first_line_indent,+ _ => 0.0,+ };(x1 - x0 - ind).max(1.0)};let rest = &glyphs[g0..];@@@ -829,28 -919,36 +987,28 @@@if cur.last_baseline.is_some() {baseline += cur.last_reference - reference;}- // Baseline grid.- if let Some((g_start, inc)) = f.grid- && (pp.grid_align == GridAlign::AllLines || (pp.grid_align == GridAlign::FirstLineOnly && line_no == 0))- && inc > 0.0- {- let n = ((baseline - g_start) / inc - 1e-6).ceil();- baseline = g_start + n * inc;- }- // Wrap: push the line down until a slot exists.+ baseline = snap(baseline);+ // 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);}}- let capped = line_cap[pi] == Some(line_no) && line_no > col_first_line;+ 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).let line_notes = if notes.active() { notes.refs_in(line_glyphs) } else { Vec::new() };@@@ -900,39 -1021,24 +1081,52 @@@moved = true;break;}- let ind_l = pp.left_indent + if line_no == 0 { pp.first_line_indent } else { 0.0 };+ // A drop cap sits at the start-side indent; the first-line indent doesn't move it.+ let beside = drop_cap.as_ref().filter(|dc| line_no < dc.lines && col_first_line == 0).map(DropCap::indent);+ let (ind_l, ind_r) = match beside {+ Some(w) if rtl => (pp.left_indent, pp.right_indent + w),+ Some(w) => (pp.left_indent + w, pp.right_indent),+ None => (pp.left_indent + if line_no == 0 { pp.first_line_indent } else { 0.0 }, pp.right_indent),+ };let lx0 = x0 + ind_l;- let lx1 = x1 - pp.right_indent;+ let lx1 = x1 - ind_r;let last = k + 1 == breaks.len();+ // The break character that ends this line, if any (it is the line's last glyph).+ let brk = if b.forced && e > s {+ e.checked_sub(1).and_then(|i| glyphs.get(i)).map(|g| g.ch).filter(|&c| breaker::is_forced(c))+ } else {+ None+ };+ // A column, frame or page break ends the line as a paragraph's last line (last-line+ // alignment); a justified line ended by a forced line break stays justified.+ let ends_para = last || matches!(brk, Some(story::COLUMN_BREAK | story::FRAME_BREAK | story::PAGE_BREAK));+ 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, last, b.forced && !last, f.left_page, &bidi_info);+ 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.++ // 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);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);@@@ -1049,9 -1140,17 +1251,14 @@@if pp.rule_above.on {let r = &pp.rule_above;let y = bl - asc - r.offset;- let col = ft.lines.iter().rev().find(|l| l.para == pi).map(|l| (l.x0, l.x1)).unwrap_or((0.0, 0.0));+ let col = ft+ .lines+ .iter()+ .find(|l| l.para == pi && l.first_in_para)+ .map(|l| if r.column_width { (l.x0, l.x1) } else { (l.x0, l.end_x) })+ .unwrap_or((0.0, 0.0));- ft.decos.push(Deco {- rect: Rect::new(col.0 + r.left_indent, y - r.weight, col.1 - r.right_indent, y),- color: r.color.clone(),- tint: r.tint,- });+ let (color, tint) = rule_color(r, &above);+ ft.decos.push(Deco { rect: Rect::new(col.0 + r.left_indent, y - r.weight, col.1 - r.right_indent, y), color, tint });}}para_box_decos(&mut out, pi, &pp);@@@ -1062,9 -1161,49 +1269,50 @@@let r = &pp.rule_below;let y = l.baseline + r.offset;let (x0, x1) = if r.column_width { (l.x0, l.x1) } else { (l.x0, l.end_x) };- ft.decos.push(Deco { rect: Rect::new(x0 + r.left_indent, y, x1 - r.right_indent, y + r.weight), color: r.color.clone(), tint: r.tint });+ let (color, tint) = rule_color(r, &below);+ ft.decos.push(Deco { rect: Rect::new(x0 + r.left_indent, y, x1 - r.right_indent, y + r.weight), color, tint });}+ // The end of a split block: text after it continues below its deepest sub-column, which+ // are balanced first. A block that ends the story fills its sub-columns in turn.+ if let Some(sb) = cur.split {+ let next =+ story.paras.get(pi + 1).filter(|_| story.para_table(pi + 1).is_none()).and_then(|p| SplitCfg::of(&doc.styles.resolve_para(p).0));+ if next != Some(sb.cfg) {+ cur.split = None;+ let part = out.frames.get(cur.fi).and_then(|ft| {+ let lines = ft.lines.get(sb.line0?..)?;+ let top = lines.first().map(|l| l.baseline - l.ascent)?;+ let deepest = lines.iter().map(|l| (l.baseline, l.descent)).max_by(|a, b| (a.0 + a.1).total_cmp(&(b.0 + b.1)))?;+ Some((sb.top.unwrap_or(top), deepest))+ });+ if pi + 1 < np+ && let Some((top, (baseline, descent))) = part+ {+ let key = (cur.fi, cur.col, sb.para);+ let active = split_trial.as_ref().is_some_and(|t| t.key == key);+ if !active && let Some(t) = split_trial.take() {+ set_limit(&mut split_limits, t.key, None);+ }+ if sb.part_lines > 1 && (active || limit_of(&split_limits, key).is_none() && split_runs < split_budget) {+ let bottom = baseline + descent;+ let mut t = split_trial.take().unwrap_or(Trial { key, span: pi, lo: top, hi: bottom, tries: 0, done: false });+ // This layout fits: its bottom is the best so far.+ t.hi = t.hi.min(bottom);+ let next = if t.done { t.hi } else { t.next() };+ set_limit(&mut split_limits, key, Some(next));+ if !t.done {+ split_trial = Some(t);+ split_runs += 1;+ rewind(key.2, &snaps, ¬e_snaps, &mut notes, &mut out, &mut cur, &mut list_counter, &mut force_col, &mut line_cap);+ pi = key.2;+ continue 'paras;+ }+ }+ cur.last_baseline = Some(baseline);+ cur.last_descent = descent;+ }+ }+ }cur.pending += pp.space_after;pi += 1;}@@@ -1479,51 -1903,112 +2012,138 @@@ impl Cursorfn next_frame(&mut self) {self.fi += 1;self.col = 0;- self.last_baseline = None;- self.pending = 0.0;+ self.band = Band { para: self.pi, ..Band::default() };+ self.resume();+ self.split_part();+ }+ fn state(&self) -> Resume {+ Resume { last_baseline: self.last_baseline, last_descent: self.last_descent, last_reference: self.last_reference, pending: self.pending }+ }+ /// Start a split block (or its part in a new column) here.+ fn split_part(&mut self) {+ let start = self.state();+ let top = start.last_baseline.map(|b| b + start.last_descent);+ let para = self.pi;+ if let Some(s) = self.split.as_mut() {+ *s = SplitBlock { sub: 0, sub_lines: 0, part_lines: 0, line0: None, para, start, top, ..*s };+ }+ }+ /// Move on to the next sub-column of the split block, back at the block's top.+ fn next_sub(&mut self) {+ let Some(s) = self.split.as_mut() else { return };+ s.sub += 1;+ s.sub_lines = 0;+ let r = s.start;+ self.last_baseline = r.last_baseline;+ self.last_descent = r.last_descent;+ self.last_reference = r.last_reference;+ self.pending = r.pending;+ }+ /// Within a split block, the next sub-column when there's one to go to.+ fn can_next_sub(&self) -> bool {+ self.split.is_some_and(|s| s.sub_lines > 0 && s.sub + 1 < s.cfg.n)+ }+ fn split_key(&self) -> Option<SplitKey> {+ self.split.map(|s| (self.fi, self.col, s.para))+ }+ /// The sub-column the split block's text is in, within `col` and above its balanced bottom.+ fn split_rect(&self, col: Rect) -> Rect {+ let Some(s) = self.split else { return col };+ let r = s.cfg.sub_rect(col, s.sub);+ let y1 = self.split_key().and_then(|k| limit_of(&self.split_limits, k)).map_or(col.y1, |b| b.min(col.y1).max(col.y0));+ Rect::new(r.x0, r.y0, r.x1, y1)+ }+ /// Start the current column at the top of the band.+ fn resume(&mut self) {+ match self.band.above {+ Some(a) => {+ self.last_baseline = Some(a.baseline);+ self.last_descent = a.descent;+ self.last_reference = a.reference;+ self.pending = a.pending;+ }+ None => {+ self.last_baseline = None;+ self.pending = 0.0;+ }+ }+ }+ fn band_key(&self) -> BandKey {+ (self.fi, self.band.para)+ }+ /// Column `col` of the current frame limited to the band: below the spanning paragraph above+ /// it and, while balancing, above the trial bottom.+ fn clip(&self, col: Rect) -> Rect {+ let y0 = self.band.above.map_or(col.y0, |a| a.top.max(col.y0).min(col.y1.max(col.y0)));+ let y1 = limit_of(&self.limits, self.band_key()).map_or(col.y1, |b| b.min(col.y1).max(y0));+ Rect::new(col.x0, y0, col.x1, y1)+ }+ /// Move on as a paragraph start option (or a break character) asks.+ fn start(&mut self, start: StartParagraph, cols: &[Vec<Rect>], frames: &[FrameSpec], doc: &Document) {+ match start {+ StartParagraph::Anywhere => {}+ StartParagraph::NextColumn => self.next_column(cols),+ StartParagraph::NextFrame => self.next_frame(),+ StartParagraph::NextPage => self.next_page(frames, doc, None),+ StartParagraph::NextOddPage => self.next_page(frames, doc, Some(true)),+ StartParagraph::NextEvenPage => self.next_page(frames, doc, Some(false)),+ }+ }+ /// Move to the next frame on a later page, one with an odd page number (`odd` true) or an+ /// even one (false) when asked. Frames without a page (parent pages) qualify; with no frame+ /// left, the rest of the story is overset.+ fn next_page(&mut self, frames: &[FrameSpec], doc: &Document, odd: Option<bool>) {+ let from = frames.get(self.fi).and_then(|f| f.page);+ let skip = |f: &FrameSpec| f.page.is_some_and(|p| Some(p) == from || odd.is_some_and(|o| (doc.page_number(p) % 2 == 1) != o));+ let mut fi = self.fi.saturating_add(1);+ while frames.get(fi).is_some_and(skip) {+ fi += 1;+ }+ self.next_frame();+ self.fi = fi;}- /// Baseline for the next line with leading `lead` and ascent `asc`.- fn next_baseline(&self, f: &FrameSpec, col: Rect, lead: f64, asc: f64, _pp: &ParaProps) -> f64 {+ /// Baseline for the next line with leading `lead`, ascent `asc` and first baseline heights+ /// `tops`.+ fn next_baseline(&self, f: &FrameSpec, col: Rect, lead: f64, asc: f64, tops: Tops, _pp: &ParaProps) -> f64 {match self.last_baseline {Some(b) => b + lead + self.pending,- None => {- let off = match f.opts.first_baseline {- FirstBaseline::Ascent => asc,- FirstBaseline::CapHeight => asc * 0.72,- FirstBaseline::XHeight => asc * 0.5,- FirstBaseline::Leading => lead,- FirstBaseline::Fixed => 0.0,- };- col.y0 + off.max(f.opts.first_baseline_min)- }+ None => col.y0 + first_baseline_offset(f, lead, asc, tops),}}+ /// How the next line clears a Jump Object wrap: by whole leadings below the line above, or, first+ /// in its column, as at the top of a frame whose top is the wrap bottom.+ fn jump(&self, f: &FrameSpec, lead: f64, asc: f64, tops: Tops) -> Jump {+ match self.last_baseline {+ Some(_) => Jump { top: lead, step: lead },+ None => Jump { top: first_baseline_offset(f, lead, asc, tops), step: 0.0 },+ }+ }+}++/// The frame's first baseline offset below the top of a column, for a line with leading `lead`,+/// ascent `asc` and first baseline heights `tops`.+fn first_baseline_offset(f: &FrameSpec, lead: f64, asc: f64, tops: Tops) -> f64 {+ let off = match f.opts.first_baseline {+ // Vertical frames measure from the ascent.+ FirstBaseline::Ascent if f.vertical => asc,+ FirstBaseline::CapHeight if f.vertical => asc * 0.72,+ FirstBaseline::XHeight if f.vertical => asc * 0.5,+ FirstBaseline::Ascent => tops.typo_ascent,+ FirstBaseline::CapHeight => tops.cap,+ FirstBaseline::XHeight => tops.xh,+ FirstBaseline::Leading => lead,+ FirstBaseline::Fixed => 0.0,+ };+ off.max(f.opts.first_baseline_min)+}++/// A line's tallest typographic ascender, cap height and x height above its baseline: the+/// first baseline offsets.+#[derive(Clone, Copy, Default)]+struct Tops {+ typo_ascent: f64,+ cap: f64,+ xh: f64,}/// Em box relative to the baseline. Font ascender/descender proportions locate it;@@@ -2478,16 -2815,132 +3154,138 @@@ fn vertical_justify(ft: &mut FrameText// ---------- caret and hit testing (Type tool) ----------+ /// Two stacked glyphs this far apart in `y` sit on different rows (warichu).+ const ROW_Y: f64 = 0.25;++ /// (ascent, descent) of `g` in points, both positive.+ fn glyph_extents(g: &PlacedGlyph) -> (f64, f64) {+ let (asc, desc) = g.face.vertical_metrics();+ let sy = g.sy.abs();+ (asc * sy, desc * sy)+ }++ fn x_span(g: &PlacedGlyph) -> (f64, f64) {+ (g.x.min(g.x + g.adv), g.x.max(g.x + g.adv))+ }++ fn x_ranges_overlap(a: &PlacedGlyph, b: &PlacedGlyph) -> bool {+ let (a0, a1) = x_span(a);+ let (b0, b1) = x_span(b);+ a0 < b1 - 0.2 && b0 < a1 - 0.2+ }++ fn line_glyphs(l: &Line) -> Vec<&PlacedGlyph> {+ l.glyphs.iter().filter(|g| g.len > 0).collect()+ }++ /// `g` shares its x with another glyph on a different baseline (a stacked warichu row).+ fn on_stacked_row(glyphs: &[&PlacedGlyph], g: &PlacedGlyph) -> bool {+ glyphs.iter().any(|o| (o.y - g.y).abs() > ROW_Y && x_ranges_overlap(o, g))+ }++ fn line_has_stacked_rows(l: &Line) -> bool {+ let glyphs = line_glyphs(l);+ glyphs.iter().any(|g| on_stacked_row(&glyphs, g))+ }++ /// The glyph `caret_x` anchors `pos` to, if the caret is not the line end.+ fn caret_anchor(l: &Line, pos: usize) -> Option<&PlacedGlyph> {+ for g in l.glyphs.iter().filter(|g| g.len > 0) {+ if pos >= g.byte && pos < g.byte + g.len {+ return Some(g);+ }+ if g.byte >= pos {+ return Some(g);+ }+ }+ None+ }++ /// Baseline an underline or strikethrough uses. Warichu follows the small line; everything else+ /// stays on the parent baseline (a baseline shift does not move the rule).+ pub fn rule_baseline(style: &RunStyle, line: &Line, g: &PlacedGlyph) -> f64 {+ if style.warichu { line.baseline + g.y } else { line.baseline }+ }++ fn band_quad(x0: f64, x1: f64, top: f64, bot: f64) -> [Point; 4] {+ [Point::new(x0, top), Point::new(x1, top), Point::new(x1, bot), Point::new(x0, bot)]+ }++ /// Highlight rectangles for bytes `s..e` on `l`. `past_end` extends the line-end caret when the+ /// selection continues onto the next line. Stacked rows (warichu) each get their own band.+ pub fn highlight_quads(l: &Line, s: usize, e: usize, past_end: bool) -> Vec<[Point; 4]> {+ let selected: Vec<&PlacedGlyph> = l.glyphs.iter().filter(|g| g.len > 0 && g.byte >= s && g.byte < e).collect();+ let stacked = selected.iter().any(|g| on_stacked_row(&selected, g));+ if stacked {+ let mut items: Vec<(f64, f64, f64, f64, f64)> = selected+ .iter()+ .map(|g| {+ let (asc, desc) = glyph_extents(g);+ let (x0, x1) = x_span(g);+ let y = l.baseline + g.y;+ (g.y, x0, x1, y - asc, y + desc)+ })+ .collect();+ items.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));+ let mut quads = Vec::new();+ let mut cur: Option<(f64, f64, f64, f64, f64)> = None;+ for (y, x0, x1, top, bot) in items {+ match cur {+ Some(c) if (c.0 - y).abs() <= ROW_Y && x0 <= c.2 + 0.5 => {+ cur = Some((c.0, c.1, c.2.max(x1), c.3.min(top), c.4.max(bot)));+ }+ Some(c) => {+ quads.push(band_quad(c.1, c.2, c.3, c.4));+ cur = Some((y, x0, x1, top, bot));+ }+ None => cur = Some((y, x0, x1, top, bot)),+ }+ }+ if let Some(c) = cur {+ quads.push(band_quad(c.1, c.2, c.3, c.4));+ }+ if past_end {+ quads.push(band_quad(l.end_x, l.end_x + 3.0, l.baseline - l.ascent, l.baseline + l.descent));+ }+ return quads;+ }+ let top = l.baseline - l.ascent;+ let bot = l.baseline + l.descent;+ if l.glyphs.iter().any(|g| g.rtl) {+ let mut spans: Vec<(f64, f64)> = selected.iter().map(|g| (g.x, g.x + g.adv)).collect();+ spans.sort_by(|a, b| a.0.total_cmp(&b.0));+ let mut merged: Vec<(f64, f64)> = Vec::new();+ for (a, b) in spans {+ match merged.last_mut() {+ Some(m) if a <= m.1 + 0.5 => m.1 = m.1.max(b),+ _ => merged.push((a, b)),+ }+ }+ return merged.into_iter().map(|(a, b)| band_quad(a, b, top, bot)).collect();+ }+ let x0 = caret_x(l, s);+ let x1 = if past_end { l.end_x.max(x0 + 3.0) } else { caret_x(l, e) };+ vec![band_quad(x0, x1, top, bot)]+ }+/// Caret geometry for story byte `pos`: (frame index, x, baseline, ascent, descent).+ /// A stacked warichu row reports that row's baseline and em, not the parent line's.pub fn caret(cs: &ComposedStory, pos: usize) -> Option<(usize, f64, f64, f64, f64)> {let (fi, l) = caret_line(cs, pos)?;+ // In the drop cap the caret is as tall as it.+ if let Some(dc) = l.drop_cap+ && pos < dc.end+ {+ return Some((fi, caret_x(l, pos), dc.baseline, dc.baseline - dc.rect.y0, l.descent));+ }- Some((fi, caret_x(l, pos), l.baseline, l.ascent, l.descent))+ let x = caret_x(l, pos);+ let glyphs = line_glyphs(l);+ let metrics = caret_anchor(l, pos).filter(|g| on_stacked_row(&glyphs, g)).map(|g| {+ let (asc, desc) = glyph_extents(g);+ (l.baseline + g.y, asc, desc)+ });+ let (bl, asc, desc) = metrics.unwrap_or((l.baseline, l.ascent, l.descent));+ Some((fi, x, bl, asc, desc))}/// The line the caret at `pos` is drawn on (and its frame index).diff --cc crates/compose/src/tests.rsindex a9ebce96c,0d1fe2d27..c32672c63--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -1308,706 -1350,27 +1589,727 @@@ fn only_english_text_gets_english_hypheassert_eq!(hyphenated(&d2, sid), 0, "French isn't hyphenated with English rules");}+/// 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 0.5 of the+ // (1 em) ascent.+ 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, face.ascent * 0.5), "{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 + 10.0)).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 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]");+ // 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_sits_on_its_line_as_set() {+ // Lines on a 15 pt baseline grid (not the 12 pt leading): the drop cap follows 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 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 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());@@@ -2843,28 -2180,594 +3145,620 @@@ fn vertical_lines_fit_the_em_box()}}+/// A drop cap set in one of the document's own fonts measures its side bearing in that font.+#[test]+fn drop_cap_in_a_document_font_aligns_its_left_edge() {+ use designcraft_geom::Shape as _;+ const FAMILY: &str = "DocFont Drop Cap";+ let text = format!("Once {LOREM}");+ let mut chars: Vec<char> = text.chars().collect();+ chars.sort_unstable();+ chars.dedup();+ let folder = std::env::temp_dir().join(format!("dc-compose-dropcap-docfont-{}", std::process::id()));+ std::fs::create_dir_all(&folder).unwrap();+ std::fs::write(folder.join("dropcap.ttf"), designcraft_fonts::testing::font_with_glyph(FAMILY, &chars, 'O').unwrap()).unwrap();+ let scope = designcraft_fonts::FontDb::global().load_document_fonts(&folder).scope;+ let para = ParaAttrs { left_indent: Some(10.0), ..drop_cap(2, 1) };+ let (mut d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, 300.0, 1000.0), para);+ d.font_scope = scope;+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.font_family = Some(FAMILY.into()));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let dc = &all_lines(&cs)[0].glyphs[0];+ assert_eq!(dc.face.family, FAMILY);+ let ink_left = dc.x + designcraft_fonts::FontDb::global().outline(dc.face.get(), dc.gid).bounding_box().x0 * dc.sx;+ assert!(ink_left - dc.x > 0.5, "the O has a visible side bearing");+ assert!((ink_left - 10.0).abs() < 1e-6, "ink at {ink_left}");+ let _ = std::fs::remove_dir_all(&folder);+}+++ /// Lines of `text` set in a frame `width` wide, with `tracking` on every character.+ fn tracked_lines(text: &str, width: f64, para: ParaAttrs, tracking: f64) -> Vec<Line> {+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, width, 4000.0), para);+ d.story_mut(sid).unwrap().format_chars(0..text.len(), |f| f.over.tracking = Some(tracking));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset(), "overset at width {width}");+ all_lines(&cs).into_iter().cloned().collect()+ }++ #[test]+ fn a_word_longer_than_the_line_breaks_at_the_column_edge() {+ use designcraft_doc::Composer;+ let word = "n".repeat(60);+ let long = format!("Then {word} and on");+ for tracking in [0.0, 740.0] {+ // Natural advances, from one unbroken line.+ let natural: HashMap<usize, f64> =+ tracked_lines(&long, 1e5, ParaAttrs::default(), tracking)[0].glyphs.iter().map(|g| (g.byte, g.adv)).collect();+ for composer in [Composer::Paragraph, Composer::SingleLine] {+ for align in [Align::Left, Align::LeftJustified] {+ let para = ParaAttrs { composer: Some(composer), align: Some(align), hyphenate: Some(false), ..Default::default() };+ let lines = tracked_lines(&long, 72.0, para, tracking);+ let what = format!("{composer:?} {align:?} tracking {tracking}");+ assert!(lines.len() >= 4, "{what}: {} lines", lines.len());+ for l in &lines {+ let ink: Vec<_> = l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).collect();+ let right = ink.iter().map(|g| g.x + g.adv.min(natural[&g.byte])).fold(l.x0, f64::max);+ assert!(l.end_x <= l.x1 + 0.02 && right <= l.x1 + 0.02, "{what}: line {:?} ends at {} past {}", l.range, l.end_x, l.x1);+ for w in ink.windows(2) {+ assert!(w[1].x >= w[0].x + natural[&w[0].byte] - 1e-6, "{what}: glyphs overlap at {}", w[1].byte);+ }+ }+ }+ }+ }+ }++ #[test]+ fn a_line_that_exactly_fills_the_measure_fits() {+ use designcraft_doc::Composer;+ let text = "#knowyourplastic";+ let one = &tracked_lines(text, 1e5, ParaAttrs::default(), 0.0)[0];+ // The measure a rounding error short of the natural width.+ let width = one.end_x - one.x0 - 0.005;+ for composer in [Composer::Paragraph, Composer::SingleLine] {+ for align in [Align::Left, Align::LeftJustified] {+ let para = ParaAttrs { composer: Some(composer), align: Some(align), ..Default::default() };+ let lines = tracked_lines(text, width, para, 0.0);+ assert_eq!(lines.len(), 1, "{composer:?} {align:?}: {:?}", lines.iter().map(|l| l.range.clone()).collect::<Vec<_>>());+ }+ }+ }++ #[test]+ fn justified_line_with_a_tab_justifies_the_text_after_its_last_tab() {+ // InDesign justifies only the text after a line's last (left) tab; tab stops stay aligned.+ let stop = |align| designcraft_doc::TabStop { position: 100.0, align, leader: String::new(), align_on: String::new() };+ let text = "Name\t42 and some words\u{2028}more";+ let x_of = |l: &Line, byte: usize| l.glyphs.iter().find(|g| g.byte == byte && g.len > 0).map(|g| g.x).unwrap();+ let left = ParaAttrs { align: Some(Align::LeftJustified), tabs: Some(vec![stop(TabAlign::Left)]), ..Default::default() };+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), left.clone());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = all_lines(&cs)[0];+ assert!((l.end_x - l.x1).abs() < 0.6, "line with a left tab ends at {} not {}", l.end_x, l.x1);+ assert!((x_of(l, 5) - 100.0).abs() < 0.5, "text after the tab starts at the stop: {}", x_of(l, 5));+ let (d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 300.0, 100.0), ParaAttrs { align: Some(Align::Left), ..left });+ let ragged = compose_story(&d, sid, &ComposeOptions::default());+ let r = all_lines(&ragged)[0];+ for byte in 0..4 {+ assert!((x_of(l, byte) - x_of(r, byte)).abs() < 1e-6, "text before the tab keeps its natural position");+ }++ // After a right tab the line stays as set.+ let right = ParaAttrs { align: Some(Align::LeftJustified), tabs: Some(vec![stop(TabAlign::Right)]), ..Default::default() };+ let (d, sid, _) = doc_with("Name\t42\u{2028}more", Rect::new(0.0, 0.0, 300.0, 100.0), right);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let l = all_lines(&cs)[0];+ assert!((l.end_x - 100.0).abs() < 0.5, "right-tab line ends at its stop: {}", l.end_x);++ // A footnote's number and tab separator: its first line is justified like the others.+ let (mut d, sid, fid) = doc_with("Body text.", Rect::new(0.0, 0.0, 200.0, 400.0), ParaAttrs::default());+ let note = ParaFormat { para: ParaAttrs { align: Some(Align::LeftJustified), ..Default::default() }, ..Default::default() };+ d.story_mut(sid).unwrap().insert_note(4, LOREM, note);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let n = &cs.frame(fid).unwrap().notes[0];+ let lines = all_lines(&n.text);+ assert!(lines.len() > 2);+ for l in &lines[..lines.len() - 1] {+ assert!((l.end_x - l.x1).abs() < 0.6, "footnote line ends at {} not {}", l.end_x, l.x1);+ }+ assert!((x_of(lines[0], 0) - 36.0).abs() < 0.5, "note text starts at the default tab stop: {}", x_of(lines[0], 0));+ }++ #[test]+ fn list_first_line_wraps_at_the_column_edge_after_its_label() {+ use designcraft_doc::{ListType, TabStop};+ // A hanging indent (left 18, first line −18): the label sits at the column start, a tab+ // after it reaches the left indent (an implicit stop when no explicit stop comes first), and+ // the first line wraps at the same right edge as the others.+ let right_edge = |l: &Line, source: &str| {+ let space = |g: &&PlacedGlyph| g.len > 0 && source.get(g.byte..).and_then(|s| s.chars().next()).is_some_and(char::is_whitespace);+ l.glyphs.iter().filter(|g| g.visible && !space(g)).map(|g| g.x + g.adv).fold(0.0, f64::max)+ };+ let text_start = |l: &Line| l.glyphs.iter().find(|g| g.len > 0 && g.visible).map_or(f64::NAN, |g| g.x);+ let stop = |position: f64| TabStop { position, align: TabAlign::Left, leader: String::new(), align_on: String::new() };+ let text = format!("{LOREM}\n{LOREM}");+ // (list, separator, explicit tab stops, where line 0's text starts past the column start:+ // None = right after the label, wherever that is).+ let cases = [+ (ListType::Bullets, "\t", None, Some(18.0)),+ (ListType::Numbers, "\t", None, Some(18.0)),+ (ListType::Numbers, "\t", Some(vec![stop(12.0)]), Some(12.0)),+ (ListType::Numbers, "\t", Some(vec![stop(30.0)]), Some(18.0)),+ (ListType::Bullets, " ", None, None),+ (ListType::Numbers, "\u{2003}", None, None),+ ];+ for (list, sep, tabs, first_at) in cases {+ let para = ParaAttrs {+ list_type: Some(list),+ list_separator: Some(sep.into()),+ left_indent: Some(18.0),+ first_line_indent: Some(-18.0),+ tabs: tabs.clone(),+ ..Default::default()+ };+ let (d, sid, _) = doc_with(&text, Rect::new(36.0, 36.0, 300.0, 400.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let col = cs.frames[0].columns[0];+ let lines = &cs.frames[0].lines;+ let what = format!("{list:?} {sep:?} {tabs:?}");+ assert!(lines.len() >= 6, "{what}: {} lines", lines.len());+ for (i, l) in lines.iter().enumerate() {+ let right = right_edge(l, &text);+ assert!(right <= col.x1 + 0.01, "{what}: line {i} ends at {right}, past the column's {}", col.x1);+ let start = text_start(l) - col.x0;+ if !l.first_in_para {+ assert!((start - 18.0).abs() < 0.01, "{what}: line {i} text starts at {start}, not the left indent");+ } else if let Some(at) = first_at {+ assert!((start - at).abs() < 0.01, "{what}: line {i} text starts at {start}, not {at}");+ } else {+ assert!(start > 0.0, "{what}: line {i} text starts at {start}");+ }+ if l.first_in_para {+ assert!(l.glyphs.first().is_some_and(|g| g.len == 0 && (g.x - col.x0).abs() < 0.01), "{what}: the label leads line {i}");+ }+ }+ }+ }++ fn ruled(text: &str, rect: Rect, columns: u32, edit: impl FnOnce(&mut Document, StoryId)) -> (Document, ItemId, Vec<Rect>) {+ let (mut d, sid, fid) = doc_with(text, rect, ParaAttrs::default());+ {+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.columns = columns;+ o.gutter = 12.0;+ o.inset = [10.0, 6.0, 20.0, 6.0];+ o.column_rule = true;+ o.column_rule_weight = 2.0;+ o.column_rule_color = "[Black]".into();+ }+ edit(&mut d, sid);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let rules = cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect).collect();+ (d, fid, rules)+ }++ #[test]+ fn column_rules_sit_in_the_gutters_inside_the_insets() {+ // Two columns in 0..300 with 6 pt side insets: the gutter is centred on 150.+ let (_, _, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 2, |_, _| {});+ assert_eq!(rules.len(), 1, "{rules:?}");+ let r = rules[0];+ assert!((r.center().x - 150.0).abs() < 1e-9 && (r.width() - 2.0).abs() < 1e-9, "{r:?}");+ assert!((r.y0 - 10.0).abs() < 1e-9 && (r.y1 - 180.0).abs() < 1e-9, "{r:?}");+ // Three columns: one rule per gutter, each centred between its two columns.+ let (_, _, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 3, |_, _| {});+ assert_eq!(rules.len(), 2, "{rules:?}");+ let w = (288.0 - 24.0) / 3.0;+ for (i, r) in rules.iter().enumerate() {+ let edge = 6.0 + w * (i + 1) as f64 + 12.0 * i as f64;+ assert!((r.center().x - (edge + 6.0)).abs() < 1e-9, "{i}: {r:?}");+ }+ // Off, or a single column: no rule.+ let (_, _, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 1, |_, _| {});+ assert!(rules.is_empty());+ let (_, _, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 2, |d, sid| {+ let fid = d.story(sid).unwrap().frames[0];+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.column_rule = false;+ });+ assert!(rules.is_empty());+ }++ #[test]+ fn column_rules_centre_on_unequal_gutters_and_ignore_bad_weights() {+ let cols = [Rect::new(200.0, 0.0, 300.0, 50.0), Rect::new(0.0, 0.0, 100.0, 50.0), Rect::new(110.0, 0.0, 180.0, 50.0)];+ let weight = |w: f64| TextFrameOptions { column_rule_weight: w, ..Default::default() };+ let rules = column_rule_rects(&cols, &[], &weight(1.0));+ let centres: Vec<f64> = rules.iter().map(|r| r.center().x).collect();+ assert_eq!(centres, [105.0, 190.0]);+ assert!(column_rule_rects(&cols, &[], &weight(f64::NAN)).is_empty());+ assert!(column_rule_rects(&cols, &[], &weight(-1.0)).is_empty());+ assert!((column_rule_rects(&cols, &[], &weight(1e12))[0].width() - 1000.0).abs() < 1e-9);+ }++ #[test]+ fn column_rules_in_right_to_left_and_vertical_frames() {+ let (_, _, rules) = ruled("نص", Rect::new(0.0, 0.0, 300.0, 200.0), 2, |d, sid| {+ d.story_mut(sid).unwrap().direction = designcraft_doc::TextDirection::RightToLeft;+ });+ assert_eq!(rules.len(), 1);+ assert!((rules[0].center().x - 150.0).abs() < 1e-9, "{rules:?}");+ // Vertical type: the columns stack top to bottom, so the rule runs across the frame.+ let (d, fid, rules) = ruled("縦書き", Rect::new(100.0, 100.0, 400.0, 300.0), 2, |d, sid| d.story_mut(sid).unwrap().vertical = true);+ assert_eq!(rules.len(), 1);+ let r = d.text_xf(d.item(fid).unwrap()).transform_rect_bbox(rules[0]);+ // Text area: x 106..394, y 110..280; the gutter is centred on y 195.+ assert!((r.x0 - 106.0).abs() < 1e-6 && (r.x1 - 394.0).abs() < 1e-6, "{r:?}");+ assert!((r.center().y - 195.0).abs() < 1e-6 && (r.height() - 2.0).abs() < 1e-6, "{r:?}");+ }++ #[test]+ fn column_rules_break_around_paragraphs_that_span_columns() {+ let text = format!("A heading that spans both columns\n{LOREM} {LOREM}");+ let (d, fid, rules) = ruled(&text, Rect::new(0.0, 0.0, 300.0, 400.0), 2, |d, sid| {+ d.story_mut(sid).unwrap().paras[0].para.span_columns = Some(designcraft_doc::SpanColumns::Span(0));+ });+ let sid = d.item(fid).unwrap().text_frame().unwrap().story;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let span: Vec<&Line> = cs.frames[0].lines.iter().filter(|l| l.para == 0).collect();+ assert!(!span.is_empty() && span.iter().all(|l| l.x0 < 150.0 && l.x1 > 150.0), "the heading spans");+ let (top, bottom) = (span[0].baseline - span[0].ascent, span[span.len() - 1].baseline + span[span.len() - 1].descent);+ assert!(!rules.is_empty());+ for r in &rules {+ assert!(r.y1 <= top + 1e-9 || r.y0 >= bottom - 1e-9, "rule {r:?} cuts the span {top}..{bottom}");+ }+ // The rule resumes below the span and runs to the bottom of the columns.+ assert!(rules.iter().any(|r| (r.y0 - bottom).abs() < 1e-9 && (r.y1 - 380.0).abs() < 1e-9), "{rules:?}");+ }++ #[test]+ fn column_rules_take_their_offset_insets_and_tint() {+ let (d, fid, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 2, |d, sid| {+ let fid = d.story(sid).unwrap().frames[0];+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.column_rule_offset = 3.0;+ o.column_rule_top_inset = 15.0;+ o.column_rule_bottom_inset = 25.0;+ o.column_rule_tint = 0.4;+ });+ // Gutter centre 150 moved 3 pt; columns 10..180 shortened to 25..155.+ assert_eq!(rules.len(), 1, "{rules:?}");+ let r = rules[0];+ assert!((r.center().x - 153.0).abs() < 1e-9 && (r.y0 - 25.0).abs() < 1e-9 && (r.y1 - 155.0).abs() < 1e-9, "{r:?}");+ let sid = d.item(fid).unwrap().text_frame().unwrap().story;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(cs.frames[0].decos.iter().any(|dc| dc.rect == r && (dc.tint - 0.4).abs() < 1e-6));+ // Insets that meet leave no rule.+ let (_, _, rules) = ruled("Text", Rect::new(0.0, 0.0, 300.0, 200.0), 2, |d, sid| {+ let fid = d.story(sid).unwrap().frames[0];+ let o = &mut d.item_mut(fid).unwrap().text_frame_mut().unwrap().options;+ o.column_rule_top_inset = 100.0;+ o.column_rule_bottom_inset = 100.0;+ });+ assert!(rules.is_empty(), "{rules:?}");+ }++ // ---------- span columns ----------++ /// A story of `before` body paragraphs, a heading spanning all columns, and `after` body+ /// paragraphs, in a three-column frame. Returns the heading's paragraph index.+ fn span_doc(before: usize, after: usize, rect: Rect) -> (Document, StoryId, ItemId, usize) {+ let mut paras: Vec<&str> = vec![LOREM; before];+ paras.push("A heading across the columns");+ paras.extend(vec![LOREM; after]);+ let (mut d, sid, fid) = doc_with(¶s.join("\n"), rect, ParaAttrs::default());+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 3;+ d.story_mut(sid).unwrap().paras[before].para.span_columns = Some(SpanColumns::Span(0));+ (d, sid, fid, before)+ }++ /// The line's leading slot (glyph ascent and descent may reach into the neighbouring lines).+ fn line_box(l: &Line) -> (f64, f64) {+ (l.baseline - 0.75 * l.leading, l.baseline + 0.25 * l.leading)+ }++ /// No two lines of a frame share any area.+ fn assert_no_overlap(ft: &FrameText) {+ for (i, a) in ft.lines.iter().enumerate() {+ for b in &ft.lines[i + 1..] {+ let ((at, ab), (bt, bb)) = (line_box(a), line_box(b));+ let x_overlap = a.x0 < b.x1 - 0.5 && b.x0 < a.x1 - 0.5;+ let y_overlap = at < bb - 0.5 && bt < ab - 0.5;+ assert!(+ !(x_overlap && y_overlap),+ "lines overlap: para {} col {} y {:.1}..{:.1} and para {} col {} y {:.1}..{:.1}",+ a.para,+ a.column,+ at,+ ab,+ b.para,+ b.column,+ bt,+ bb+ );+ }+ }+ }++ /// The heading spans the frame; text before it sits above it and text after it below it.+ fn assert_span_layout(ft: &FrameText, h: usize) {+ let heading: Vec<&Line> = ft.lines.iter().filter(|l| l.para == h).collect();+ assert!(!heading.is_empty());+ let (c0, cn) = (ft.columns[0], ft.columns[ft.columns.len() - 1]);+ for l in &heading {+ assert!((l.x0 - c0.x0.min(cn.x0)).abs() < 1e-6 && (l.x1 - c0.x1.max(cn.x1)).abs() < 1e-6, "heading spans {}..{}", l.x0, l.x1);+ }+ let top = heading.iter().map(|l| line_box(l).0).fold(f64::INFINITY, f64::min);+ let bottom = heading.iter().map(|l| line_box(l).1).fold(f64::NEG_INFINITY, f64::max);+ for l in ft.lines.iter().filter(|l| l.para < h) {+ assert!(line_box(l).1 <= top + 0.5, "para {} col {} ends at {} below the heading top {top}", l.para, l.column, line_box(l).1);+ }+ for l in ft.lines.iter().filter(|l| l.para > h) {+ assert!(line_box(l).0 >= bottom - 0.5, "para {} col {} starts at {} above the heading bottom {bottom}", l.para, l.column, line_box(l).0);+ }+ assert_no_overlap(ft);+ }++ #[test]+ fn text_after_a_spanning_paragraph_flows_below_it() {+ let (d, sid, _, h) = span_doc(2, 3, Rect::new(0.0, 0.0, 540.0, 300.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ let ft = &cs.frames[0];+ assert_span_layout(ft, h);+ // The text before is balanced across the three columns above the heading.+ let before: Vec<&Line> = ft.lines.iter().filter(|l| l.para < h).collect();+ let per_col = |c: u32| before.iter().filter(|l| l.column == c).count();+ let counts = [per_col(0), per_col(1), per_col(2)];+ assert!(counts.iter().all(|&n| n > 0), "{counts:?}");+ assert!(counts.iter().max().unwrap() - counts.iter().min().unwrap() <= 1, "{counts:?}");+ // The text after starts right below the heading in every column, on the same baseline.+ let bottom = ft.lines.iter().filter(|l| l.para == h).map(|l| l.baseline).fold(f64::NEG_INFINITY, f64::max);+ let firsts: Vec<f64> = (0..3).map(|c| ft.lines.iter().find(|l| l.para > h && l.column == c).map(|l| l.baseline).unwrap()).collect();+ for b in &firsts {+ assert!(*b > bottom && *b < bottom + 40.0, "{firsts:?} after {bottom}");+ }+ assert!((firsts[1] - firsts[2]).abs() < 1e-6, "{firsts:?}");+ }++ #[test]+ fn spanning_heading_kept_with_next_and_spanning_two_of_three_columns() {+ let (mut d, sid, _, h) = span_doc(2, 3, Rect::new(0.0, 0.0, 540.0, 300.0));+ d.story_mut(sid).unwrap().paras[h].para.keep_with_next = Some(2);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ assert_span_layout(&cs.frames[0], h);+ // Spanning two of three columns: the third column beside the heading stays empty.+ d.story_mut(sid).unwrap().paras[h].para.span_columns = Some(SpanColumns::Span(2));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let ft = &cs.frames[0];+ let heading = ft.lines.iter().find(|l| l.para == h).unwrap();+ assert!((heading.x0 - ft.columns[0].x0).abs() < 1e-6 && (heading.x1 - ft.columns[1].x1).abs() < 1e-6);+ assert_no_overlap(ft);+ let bottom = heading.baseline + 0.25 * heading.leading;+ assert!(ft.lines.iter().filter(|l| l.para > h).all(|l| line_box(l).0 >= bottom - 0.5));+ assert!((0..3).all(|c| ft.lines.iter().any(|l| l.para > h && l.column == c)));+ }++ #[test]+ fn spanning_paragraph_at_the_top_and_end_of_a_frame() {+ let (d, sid, _, h) = span_doc(0, 4, Rect::new(0.0, 0.0, 540.0, 300.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ let ft = &cs.frames[0];+ assert_span_layout(ft, h);+ assert!(ft.lines[0].para == h && ft.lines[0].baseline < 20.0);+ assert!((1..3).all(|c| ft.lines.iter().any(|l| l.column == c)));++ let (d, sid, _, h) = span_doc(3, 0, Rect::new(0.0, 0.0, 540.0, 300.0));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ assert_span_layout(&cs.frames[0], h);+ }++ #[test]+ fn text_after_a_spanning_paragraph_threads_into_the_next_frame() {+ let (mut d, sid, f1, h) = span_doc(2, 8, Rect::new(0.0, 0.0, 540.0, 200.0));+ let lid = d.default_layer();+ let (f2, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 300.0, 540.0, 700.0), lid, "", ParaFormat::default()).unwrap();+ d.item_mut(f2).unwrap().text_frame_mut().unwrap().options.columns = 3;+ d.thread(f1, f2).unwrap();+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset(), "overset at {:?}", cs.overset_at);+ assert_span_layout(&cs.frames[0], h);+ let (a, b) = (&cs.frames[0], &cs.frames[1]);+ assert!((0..3).all(|c| a.lines.iter().any(|l| l.para > h && l.column == c)));+ assert!(!b.lines.is_empty() && b.lines[0].para > h && b.lines[0].baseline < 320.0);+ assert_no_overlap(b);+ // Every line of the story is set once, in order.+ let lines = all_lines(&cs);+ for w in lines.windows(2) {+ assert!(w[1].range.start >= w[0].range.end, "{:?} then {:?}", w[0].range, w[1].range);+ }+ assert_eq!(lines.last().unwrap().range.end, d.story(sid).unwrap().text.len());+ }++ #[test]+ fn spanning_paragraph_in_rtl_and_vertical_frames() {+ let (mut d, sid, _, h) = span_doc(2, 4, Rect::new(0.0, 0.0, 540.0, 500.0));+ d.story_mut(sid).unwrap().direction = designcraft_doc::TextDirection::RightToLeft;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ assert_span_layout(&cs.frames[0], h);++ let (mut d, sid, _, h) = span_doc(2, 4, Rect::new(0.0, 0.0, 540.0, 540.0));+ d.story_mut(sid).unwrap().vertical = true;+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.frames[0].lines.is_empty());+ assert_no_overlap(&cs.frames[0]);+ assert!(cs.frames[0].lines.iter().any(|l| l.para == h));+ }++ // ---------- split columns ----------++ /// A story of a body paragraph, `split` paragraphs in split columns and `after` body paragraphs.+ /// Returns the index of the first split paragraph.+ fn split_doc(split: usize, after: usize, rect: Rect, cfg: (u32, f64, f64)) -> (Document, StoryId, ItemId, usize) {+ let mut paras: Vec<&str> = vec![LOREM; 1 + split + after];+ paras[0] = "An introduction set at the full measure of the column, before the split block.";+ let (mut d, sid, fid) = doc_with(¶s.join("\n"), rect, ParaAttrs::default());+ let st = d.story_mut(sid).unwrap();+ for p in &mut st.paras[1..=split] {+ p.para.span_columns = Some(SpanColumns::Split(cfg.0));+ p.para.split_inside_gutter = Some(cfg.1);+ p.para.split_outside_gutter = Some(cfg.2);+ }+ (d, sid, fid, 1)+ }++ /// The sub-columns of `col`: (x0, x1) of each.+ fn sub_columns(col: Rect, (n, inside, outside): (u32, f64, f64)) -> Vec<(f64, f64)> {+ let w = (col.width() - 2.0 * outside - inside * (n - 1) as f64) / n as f64;+ (0..n).map(|k| col.x0 + outside + k as f64 * (w + inside)).map(|x| (x, x + w)).collect()+ }++ /// The split paragraphs' lines, by sub-column.+ fn split_lines<'a>(ft: &'a FrameText, paras: std::ops::Range<usize>, subs: &[(f64, f64)]) -> Vec<Vec<&'a Line>> {+ let mut by_sub = vec![Vec::new(); subs.len()];+ for l in ft.lines.iter().filter(|l| paras.contains(&l.para)) {+ let k = subs.iter().position(|&(x0, x1)| (l.x0 - x0).abs() < 1e-6 && (l.x1 - x1).abs() < 1e-6);+ let k = k.unwrap_or_else(|| panic!("line of para {} at {}..{} is in no sub-column of {subs:?}", l.para, l.x0, l.x1));+ by_sub[k].push(l);+ }+ by_sub+ }++ #[test]+ fn split_paragraphs_are_set_in_balanced_sub_columns() {+ for cfg in [(2, 12.0, 10.0), (3, 6.0, 0.0)] {+ let (d, sid, _, s) = split_doc(2, 1, Rect::new(0.0, 0.0, 400.0, 700.0), cfg);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ let ft = &cs.frames[0];+ assert_no_overlap(ft);+ let by_sub = split_lines(ft, s..s + 2, &sub_columns(ft.columns[0], cfg));+ let counts: Vec<usize> = by_sub.iter().map(Vec::len).collect();+ assert!(counts.iter().all(|&n| n > 0), "{cfg:?}: {counts:?}");+ assert!(counts.iter().max().unwrap() - counts.iter().min().unwrap() <= 1, "{cfg:?}: balanced {counts:?}");+ // Every sub-column starts on the same baseline, below the paragraph before the block.+ let firsts: Vec<f64> = by_sub.iter().map(|v| v[0].baseline).collect();+ assert!(firsts.iter().all(|b| (b - firsts[0]).abs() < 1e-6), "{cfg:?}: {firsts:?}");+ let intro = ft.lines.iter().filter(|l| l.para == 0).map(|l| line_box(l).1).fold(f64::NEG_INFINITY, f64::max);+ assert!(firsts[0] > intro && firsts[0] < intro + 20.0, "{cfg:?}: block at {} after {intro}", firsts[0]);+ // The text after the block continues at the full measure below its deepest sub-column.+ let bottom = by_sub.iter().flatten().map(|l| line_box(l).1).fold(f64::NEG_INFINITY, f64::max);+ let next = ft.lines.iter().find(|l| l.para == s + 2).unwrap();+ assert!(line_box(next).0 >= bottom - 0.5 && line_box(next).0 < bottom + 20.0, "{cfg:?}: {} after {bottom}", line_box(next).0);+ assert!((next.x0 - ft.columns[0].x0).abs() < 1e-6 && (next.x1 - ft.columns[0].x1).abs() < 1e-6);+ }+ }++ #[test]+ fn split_block_in_the_second_column_and_at_the_story_end() {+ let cfg = (2, 12.0, 0.0);+ let (mut d, sid, fid, s) = split_doc(3, 0, Rect::new(0.0, 0.0, 540.0, 400.0), cfg);+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ d.story_mut(sid).unwrap().paras[s].para.start_paragraph = Some(StartParagraph::NextColumn);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert!(!cs.is_overset());+ let ft = &cs.frames[0];+ assert_no_overlap(ft);+ assert!(ft.lines.iter().filter(|l| l.para >= s).all(|l| l.column == 1));+ let by_sub = split_lines(ft, s..s + 3, &sub_columns(ft.columns[1], cfg));+ // Nothing follows the block: it fills its first sub-column to the bottom of the frame, then+ // the next.+ let (a, b) = (&by_sub[0], &by_sub[1]);+ assert!(!a.is_empty() && !b.is_empty() && a.len() > b.len() + 1, "{} and {} lines", a.len(), b.len());+ let low = a.last().unwrap();+ assert!(low.baseline + low.descent > 400.0 - low.leading, "the first sub-column ends at {}", low.baseline);+ assert!((a[0].baseline - b[0].baseline).abs() < 1e-6);+ }++ #[test]+ fn split_block_flows_into_the_next_column() {+ let cfg = (2, 12.0, 0.0);+ let (mut d, sid, fid, s) = split_doc(6, 1, Rect::new(0.0, 0.0, 540.0, 200.0), cfg);+ 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];+ assert_no_overlap(ft);+ for c in 0..2 {+ let in_col: Vec<&Line> = ft.lines.iter().filter(|l| l.column == c as u32).collect();+ let lines: Vec<&Line> = in_col.iter().copied().filter(|l| (s..s + 6).contains(&l.para)).collect();+ let subs = sub_columns(ft.columns[c], cfg);+ assert!(subs.iter().all(|&(x0, x1)| lines.iter().any(|l| (l.x0 - x0).abs() < 1e-6 && (l.x1 - x1).abs() < 1e-6)), "column {c}");+ }+ // The block continues at the top of the second column.+ let top = ft.lines.iter().find(|l| l.column == 1).unwrap();+ assert!((s..s + 6).contains(&top.para) && top.baseline < 20.0);+ }++ /// Each paragraph's list label as text: its label glyphs (laid before the paragraph's own text)+ /// matched back to characters of the label font; tabs and other invisible glyphs are skipped.+ fn list_labels(cs: &ComposedStory, alphabet: &str) -> Vec<String> {+ all_lines(cs)+ .iter()+ .filter(|l| l.first_in_para)+ .map(|l| {+ l.glyphs+ .iter()+ .take_while(|g| g.len == 0)+ .filter(|g| g.visible)+ .map(|g| alphabet.chars().find(|c| g.face.glyph_for(*c) == g.gid).unwrap_or('?'))+ .collect()+ })+ .collect()+ }++ const LABEL_CHARS: &str = "0123456789ABCDIVXabcdivx.\u{2022} Tabel";++ fn numbered(style: designcraft_doc::NumberStyle, expression: &str) -> ParaAttrs {+ ParaAttrs {+ list_type: Some(designcraft_doc::ListType::Numbers),+ number_style: Some(style),+ number_expression: Some(expression.into()),+ ..Default::default()+ }+ }++ #[test]+ fn numbered_lists_follow_their_format_and_expression() {+ use designcraft_doc::NumberStyle as N;+ let cases: [(N, &str, [&str; 3]); 4] = [+ (N::UpperLetters, "^#.^t", ["A.", "B.", "C."]),+ (N::LowerRoman, "^#.^t", ["i.", "ii.", "iii."]),+ (N::ArabicThreeDigits, "^#.^t", ["001.", "002.", "003."]),+ (N::Arabic, "Tabel ^#^t", ["Tabel 1", "Tabel 2", "Tabel 3"]),+ ];+ for (style, expression, want) in cases {+ let (d, sid, _) = doc_with("One\nTwo\nThree", Rect::new(0.0, 0.0, 300.0, 300.0), numbered(style, expression));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(list_labels(&cs, LABEL_CHARS), want, "{style:?} {expression}");+ }+ }++ #[test]+ fn numbering_from_the_largest_start_number_does_not_overflow() {+ let (mut d, sid, _) = doc_with("One\nTwo", Rect::new(0.0, 0.0, 300.0, 300.0), numbered(designcraft_doc::NumberStyle::Arabic, "^#."));+ d.story_mut(sid).unwrap().paras[0].para.start_at = Some(Some(u32::MAX));+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let max = format!("{}.", u32::MAX);+ assert_eq!(list_labels(&cs, LABEL_CHARS), [max.clone(), max]);+ }++ #[test]+ fn empty_paragraphs_get_no_bullet_or_number() {+ let bullets = ParaAttrs { list_type: Some(designcraft_doc::ListType::Bullets), ..Default::default() };+ let (d, sid, _) = doc_with("One\n\nTwo\n", Rect::new(0.0, 0.0, 300.0, 300.0), bullets);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["\u{2022}", "", "\u{2022}", ""]);+ // An empty paragraph doesn't use up a number, in a story's own list or a named one.+ for name in ["", "Steps"] {+ let attrs = ParaAttrs { list_name: Some(name.into()), ..numbered(designcraft_doc::NumberStyle::Arabic, "^#.^t") };+ let (mut d, sid, _) = doc_with("One\n\nTwo\n", Rect::new(0.0, 0.0, 300.0, 300.0), attrs);+ if !name.is_empty() {+ d.settings.lists.push(designcraft_doc::NumberedList { name: name.into(), continue_across_stories: false });+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.", "", "2.", ""], "list `{name}`");+ }+ }diff --cc crates/engine/src/cmd/text.rsindex 7b620fe48,4950d82b9..e3ede0aa4--- a/crates/engine/src/cmd/text.rs+++ b/crates/engine/src/cmd/text.rs@@@ -138,7 -135,7 +138,7 @@@ pub fn specs() -> Vec<CommandSpec>"Paragraph Formatting",[],None,- "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?, composer?, tabs?, …}}",- "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, hyphenate?, composer?, tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}",++ "{attrs: {align?, leftIndent?, firstLineIndent?, spaceBefore?, spaceAfter?, dropCapLines?, dropCapChars?, dropCapStyle?, dropCapAlignLeft?, dropCapScaleDescenders?, hyphenate?, composer?, tabs?, ruleAbove?/ruleBelow?: {on?, weight?, color?, tint?, columnWidth?, offset?, leftIndent?, rightIndent?} (only the named rule fields change), …}}",has_text_or_frames,|s, p| format_paras(s, p.get("attrs").unwrap_or(p))),@@@ -831,23 -782,43 +877,60 @@@ pub(crate) fn format_targets(s: &Sessiov}+/// Character formatting chosen at a bare caret in text: applied to what is typed there next.+#[derive(Clone, Debug)]+pub(crate) struct TypingFormat {+ doc: u64,+ at: TextSel,+ attrs: CharAttrs,+ /// Overrides removed (`null` in `type.char`).+ cleared: Vec<String>,+}++/// The typing format for the active document's caret, if it was chosen at this caret.+fn typing_format(s: &Session) -> Option<&TypingFormat> {+ let st = s.active()?;+ let t = st.selection.text?;+ s.typing_format.as_ref().filter(|f| f.doc == st.uid && f.at.story == t.story && f.at.cell == t.cell && f.at.range() == t.range())+}++ fn warichu_cmd(s: &mut Session, p: &Value) -> Result<Value> {+ let has_opts = ["lines", "size", "lineSpacing", "align", "charsBeforeBreak", "charsAfterBreak"].iter().any(|k| p.get(k).is_some());+ let on = match p.get("on").and_then(Value::as_bool) {+ Some(v) => v,+ None if has_opts => true,+ None => !format_targets(s).first().is_some_and(|t| {+ s.doc()+ .ok()+ .and_then(|d| d.doc.text_story(t.story, t.cell))+ .is_some_and(|st| st.char_format_at(if t.range.is_empty() { t.range.start } else { t.range.start + 1 }).over.warichu == Some(true))+ }),+ };+ let mut body = serde_json::Map::new();+ body.insert("warichu".into(), json!(on));+ if on {+ if let Some(v) = p.get("lines").and_then(Value::as_u64) {+ body.insert("warichuLines".into(), json!(v.clamp(2, 16)));+ }+ if let Some(v) = p.get("size").and_then(Value::as_f64).filter(|v| v.is_finite()) {+ body.insert("warichuSize".into(), json!(v.clamp(1.0, 1000.0)));+ }+ if let Some(v) = p.get("lineSpacing").and_then(Value::as_f64).filter(|v| v.is_finite()) {+ body.insert("warichuLineSpacing".into(), json!(v.clamp(-10_000.0, 10_000.0)));+ }+ if let Some(v) = p.get("align").and_then(Value::as_str) {+ body.insert("warichuAlignment".into(), json!(v));+ }+ if let Some(v) = p.get("charsBeforeBreak").and_then(Value::as_u64) {+ body.insert("warichuCharsBeforeBreak".into(), json!(v.min(100)));+ }+ if let Some(v) = p.get("charsAfterBreak").and_then(Value::as_u64) {+ body.insert("warichuCharsAfterBreak".into(), json!(v.min(100)));+ }+ }+ format_chars(s, &Value::Object(body))+ }+pub(crate) fn format_chars(s: &mut Session, attrs: &Value) -> Result<Value> {let mut a = CharAttrs::default();if let Some(o) = attrs.as_object() {@@@ -877,41 -854,20 +960,44 @@@})}+/// Character attributes `a` (and the overrides `cleared` removed) over each target's text.+pub(crate) fn apply_char_attrs(d: &mut designcraft_doc::Document, targets: &[Target], a: &CharAttrs, cleared: &[String]) {+ for t in targets {+ let r = &t.range;+ let Some(st) = d.text_story_mut(t.story, t.cell) else { continue };+ if r.is_empty() {+ // An empty story: its one (empty) run is the format typing takes.+ if st.is_empty()+ && let Some(run) = st.chars.first_mut()+ {+ run.format.over.merge(a);+ st.rev += 1;+ }+ continue;+ }+ st.format_chars(r.clone(), |f| {+ f.over.merge(a);+ for k in cleared {+ let _ = f.over.set_json(k, &Value::Null);+ }+ });+ }+}+pub(crate) fn format_paras(s: &mut Session, attrs: &Value) -> Result<Value> {+ let empty = serde_json::Map::new();+ let obj = attrs.as_object().unwrap_or(&empty);+ // A rule object changes only the rule fields it names, so each paragraph gets its own attrs+ // over its resolved rule; this pass validates them.let mut a = ParaAttrs::default();- if let Some(o) = attrs.as_object() {- for (k, v) in o {- a.set_json(k, v).map_err(|e| bad("type.para", e))?;- }+ for (k, v) in obj {+ a.set_json_over(k, v, &designcraft_doc::ParaProps::default()).map_err(|e| bad("type.para", e))?;}// `null` removes the override (back to the style's value).- let cleared: Vec<String> = attrs.as_object().map(|o| o.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect()).unwrap_or_default();+ let cleared: Vec<String> = obj.iter().filter(|(_, v)| v.is_null()).map(|(k, _)| k.clone()).collect();let targets = format_targets(s);s.edit(|d, _| {+ let styles = d.styles.clone();for t in &targets {if let Some(st) = d.text_story_mut(t.story, t.cell) {st.format_paras(t.range.clone(), |p| {diff --cc crates/fonts/src/fontdb.rsindex 49e92ce91,14441e144..92afc91e6--- a/crates/fonts/src/fontdb.rs+++ b/crates/fonts/src/fontdb.rs@@@ -724,24 -712,15 +724,33 @@@ fn make_face(bytes: FontBytes, source:})}+/// A font's height above the baseline (font units) if it is plausible: above 0 and at most 4 em.+fn plausible(v: Option<f64>, upem: f64) -> Option<f64> {+ v.filter(|v| *v > 0.0 && *v <= 4.0 * upem)+}++/// The OS/2 typographic ascender in font units at `location`, if the font has an OS/2 table and+/// the value is [`plausible`].+fn typo_ascent(f: &skrifa::FontRef<'_>, location: &Location, upem: f64) -> Option<f64> {+ use skrifa::raw::TableProvider;+ let mut v = f.os2().ok()?.s_typo_ascender() as f64;+ if !location.coords().is_empty()+ && let Ok(mvar) = f.mvar()+ {+ v += mvar.metric_delta(skrifa::raw::tables::mvar::tags::HASC, location.coords()).map_or(0.0, |d| d.to_f64());+ }+ plausible(Some(v), upem)+}++ /// `family` without the font-format suffix layout apps append when a family is installed in+ /// several formats (`Minion Pro (OTF)` → `Minion Pro`), if it has one.+ fn without_format_suffix(family: &str) -> Option<&str> {+ const FORMATS: [&str; 5] = ["OTF", "TT", "TTF", "TTC", "T1"];+ let (base, suffix) = family.trim_end().strip_suffix(')')?.rsplit_once('(')?;+ let base = base.trim_end();+ (!base.is_empty() && FORMATS.iter().any(|f| f.eq_ignore_ascii_case(suffix.trim()))).then_some(base)+ }+/// The named style part of a style with axis settings (`Bold {wght:650}` → `Bold`).pub fn base_style(style: &str) -> &str {style.split('{').next().unwrap_or(style).trim()@@@ -1258,51 -1227,14 +1267,59 @@@ impl ScopedFonts<'_>/// Style names available for `family` (Regular first, then by weight).pub fn styles(&self, family: &str) -> Vec<String> {- let v = self.exact_styles(family);+ self.style_traits(family).into_iter().map(|t| t.2).collect()+ }++ /// Weight and italic of a style of `family`: from the font when it is known, else from the+ /// style's name.+ pub fn traits_of(&self, family: &str, style: &str) -> (f32, bool) {+ let base = base_style(style);+ self.style_traits(family)+ .into_iter()+ .find(|t| t.2.eq_ignore_ascii_case(base))+ .map_or((style_weight(base), style_italic(base)), |(italic, weight, _)| (weight, italic))+ }++ /// Style linking: the style of `family` that sets bold (`bold`) and italic (`italic`) as asked+ /// and keeps the other from `current` (Bold from Italic is Bold Italic). `None` when the+ /// family has no such style.+ pub fn linked_style(&self, family: &str, current: &str, bold: Option<bool>, italic: Option<bool>) -> Option<String> {+ let (weight, cur_italic) = self.traits_of(family, current);+ let want_italic = italic.unwrap_or(cur_italic);+ let want_weight = match bold {+ Some(true) => 700.0,+ Some(false) => 400.0,+ None => weight,+ };+ // Width words (Condensed, Extended…) of the current style are kept when the family allows.+ const WIDTHS: &[&str] = &["condensed", "compressed", "narrow", "extended", "expanded", "wide"];+ let widths = |s: &str| {+ let n = norm(s);+ WIDTHS.iter().filter(|w| n.contains(*w)).count()+ };+ let cur_widths = widths(current);+ self.style_traits(family)+ .into_iter()+ .filter(|(i, w, _)| *i == want_italic && bold.is_none_or(|b| b == (*w >= 600.0)))+ .min_by(|a, b| {+ let key = |t: &(bool, f32, String)| ((t.1 - want_weight).abs(), usize::from(widths(&t.2) != cur_widths), t.2.len());+ let (ka, kb) = (key(a), key(b));+ ka.0.total_cmp(&kb.0).then(ka.1.cmp(&kb.1)).then(ka.2.cmp(&kb.2))+ })+ .map(|t| t.2)+ }++ /// `(italic, weight, name)` of each style of `family` (the document's, loaded, or installed),+ /// Regular first, then by weight.+ fn style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {++ let v = self.exact_style_traits(family);+ match without_format_suffix(family) {- Some(base) if v.is_empty() => self.exact_styles(base),++ Some(base) if v.is_empty() => self.exact_style_traits(base),+ _ => v,+ }+ }+- fn exact_styles(&self, family: &str) -> Vec<String> {++ fn exact_style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {let mut v: Vec<(bool, f32, String)> = self.own().iter()diff --cc crates/idml/src/import.rsindex 440047054,d85d9ee02..34cdeb836--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -689,6 -701,15 +704,15 @@@ impl<'r> Importer<'r>}/// A swatch reference (Self id) → our swatch name; unnamed colours become value-named swatches.+ /// A `TextFramePreference`, with its column rule colour resolved to a swatch.- fn frame_options(&mut self, e: &El) -> TextFrameOptions {- let mut o = text_frame_options(e);- if let Some(r) = e.get("ColumnRuleStrokeColor") {++ fn frame_options(&mut self, prefs: &[&El]) -> TextFrameOptions {++ let mut o = text_frame_options(prefs);++ if let Some(r) = Prefs(prefs).get("ColumnRuleStrokeColor") {+ o.column_rule_color = self.swatch_ref(r);+ }+ o+ }+fn swatch_ref(&mut self, r: &str) -> String {if let Some(n) = self.swatch_names.get(r) {return n.clone();@@@ -889,7 -914,7 +917,7 @@@.then(|| e.get("AppliedParagraphStyle").map(|r| self.para_style_ref(r))).flatten();let text_frame = if e.get("EnableTextFrameGeneralOptions") == Some("true") {- e.find("TextFramePreference").map(|t| text_frame_options(&[t]))- e.find("TextFramePreference").map(|t| self.frame_options(t))++ e.find("TextFramePreference").map(|t| self.frame_options(&[t]))} else {None};@@@ -1090,8 -1115,10 +1118,10 @@@// Underline / strikethrough options (-9999 = automatic).for k in ["Underline", "StrikeThru"] {let num = |n: &str| e.num(&format!("{k}{n}")).filter(|v| *v > -9000.0);- let color = e.prop(&format!("{k}Color")).map(|r| self.swatch_ref(r.trim())).filter(|r| r != "Text Color" && !r.is_empty());+ // An explicit Text Color resets an inherited swatch; absence still inherits.+ // Resolve the sentinel before swatch_ref, which maps unknown names to [None].+ let color = e.prop(&format!("{k}Color")).map(|r| if r.trim() == "Text Color" { String::new() } else { self.swatch_ref(r.trim()) });- let tint = e.num(&format!("{k}Tint")).filter(|v| *v >= 0.0).map(|v| (v / 100.0) as f32);+ let tint = tint(e.num(&format!("{k}Tint")));if k == "Underline" {a.underline_weight = num("Weight").map(Some);a.underline_offset = num("Offset").map(Some);@@@ -2058,9 -2138,7 +2160,13 @@@sid}};- let mut options = e.find("TextFramePreference").map(|t| self.frame_options(t)).unwrap_or_default();+ // Options the frame doesn't set come from its object style chain.+ let prefs: Vec<&El> = std::iter::once(e).chain(self.object_style_chain(e)).filter_map(|s| s.find("TextFramePreference")).collect();+ let mut options = text_frame_options(&prefs);++ // `prefs` borrows the object styles, so the rule colour's swatch is resolved after it.++ if let Some(r) = Prefs(&prefs).get("ColumnRuleStrokeColor").map(str::to_string) {++ options.column_rule_color = self.swatch_ref(&r);++ }if let Some(g) = e.find("BaselineFrameGridOption")&& g.get("UseCustomBaselineFrameGrid") == Some("true"){diff --cc crates/idml/src/tests.rsindex 6630ac1ad,7b747587a..4afe19ca4--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -992,381 -1358,44 +1372,543 @@@ fn split_columns_import_and_round_trip(}#[test]- fn round_trips_index_references() {- use designcraft_doc::index::IndexRange;- let mut d = Document::new(&NewDocument::default());- let lid = d.default_layer();- let (_, sid) = d- .add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Kerning adjusts pairs.\nMore.", ParaFormat::default())- .unwrap();- {- let s = d.story_mut(sid).unwrap();- s.insert_index_ref(- 0,- designcraft_doc::IndexRef { topics: vec!["Type".into(), "Kerning".into()], sort: vec![], range: IndexRange::CurrentPage },- );- s.insert_index_ref(5, designcraft_doc::IndexRef { topics: vec!["Pairs".into()], sort: vec![], range: IndexRange::NextParagraphs(2) });- s.insert_index_ref(9, designcraft_doc::IndexRef { topics: vec!["Spacing".into()], sort: vec![], range: IndexRange::See("Type".into()) });- }- d.check().unwrap();- let back = import_idml(&export_idml(&d)).unwrap();- back.check().unwrap();- let s = back.stories.values().next().unwrap();- let mut got: Vec<(Vec<String>, IndexRange)> = s.index_refs.iter().map(|r| (r.topics.clone(), r.range.clone())).collect();- got.sort_by(|a, b| a.0.cmp(&b.0));- assert_eq!(- got,- [- (vec!["Pairs".to_string()], IndexRange::NextParagraphs(2)),- (vec!["Spacing".to_string()], IndexRange::See("Type".into())),- (vec!["Type".to_string(), "Kerning".to_string()], IndexRange::CurrentPage),- ]+ fn list_numbering_format_expression_and_bullet_import_and_round_trip() {+ let styles = STYLES.replace(+ " </ParagraphStyleGroup>",+ r#" <ParagraphStyle Self="ParagraphStyle/Text%3aHead" Name="Text:Head" BulletsAndNumberingListType="NumberedList" NumberingExpression="^#.^t">+ <Properties><NumberingFormat type="string">A, B, C, D...</NumberingFormat></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Text%3aTable" Name="Text:Table" BulletsAndNumberingListType="NumberedList" NumberingExpression="Tabel ^#^t">+ <Properties><NumberingFormat type="string">001, 002, 003...</NumberingFormat></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Text%3aKanji" Name="Text:Kanji" BulletsAndNumberingListType="NumberedList">+ <Properties><NumberingFormat type="string">一, 二, 三, 四...</NumberingFormat></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Text%3aPoint" Name="Text:Point" BulletsAndNumberingListType="BulletList" BulletsTextAfter="^>">+ <Properties><BulletChar BulletCharacterType="UnicodeOnly" BulletCharacterValue="9632"/></Properties>+ </ParagraphStyle>+ </ParagraphStyleGroup>"#,);- // The text survives; page references keep their places (See references, which InDesign keeps- // on topics rather than in text, come back at the story start).- assert_eq!(s.text.replace(designcraft_doc::INDEX_MARK, ""), "Kerning adjusts pairs.\nMore.");- assert!(s.text.starts_with(&format!("{0}{0}Ke{0}rning", designcraft_doc::INDEX_MARK)), "{:?}", s.text);+ 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 check = |d: &Document| {+ let (head, _) = d.styles.resolve_para_style("Text/Head");+ assert_eq!(head.number_style, designcraft_doc::NumberStyle::UpperLetters);+ assert_eq!(head.number_label(2), "B.\t");+ let (table, _) = d.styles.resolve_para_style("Text/Table");+ assert_eq!(table.number_label(7), "Tabel 007\t");+ let (kanji, _) = d.styles.resolve_para_style("Text/Kanji");+ assert_eq!(kanji.number_style, designcraft_doc::NumberStyle::Arabic);+ let (point, _) = d.styles.resolve_para_style("Text/Point");+ assert_eq!(point.bullet_label(), "\u{25A0}\u{2002}");+ };+ let d = import_idml(&bytes).unwrap();+ check(&d);+ check(&import_idml(&export_idml(&d)).unwrap());+ }++++fn fixture_with_styles(styles: &str) -> Vec<u8> {++ 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),++ ])++}++++/// Paragraph styles `Body` (based on the root) and `Loose` (no BasedOn), both with `attrs`.++fn keep_styles(attrs: &str) -> String {++ format!(++ r#"<?xml version="1.0" encoding="UTF-8"?>++<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">++ <RootParagraphStyleGroup Self="rp">++ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12"/>++ <ParagraphStyle Self="ParagraphStyle/Body" Name="Body" {attrs}>++ <Properties><BasedOn type="object">ParagraphStyle/$ID/[No paragraph style]</BasedOn></Properties>++ </ParagraphStyle>++ <ParagraphStyle Self="ParagraphStyle/Loose" Name="Loose" {attrs}/>++ </RootParagraphStyleGroup>++</idPkg:Styles>"#++ )+}+++/// Keep Lines Together whose mode no style sets is InDesign's default: at start/end of paragraph.++/// An explicit mode still wins.+#[test]- fn round_trips_anchored_objects() {- use designcraft_doc::{AnchorPosition, AnchoredObject, anchored::AnchorAlign};- let mut d = Document::new(&NewDocument::default());- let lid = d.default_layer();- let (_, sid) =- d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Inline here.\nAbove.", ParaFormat::default()).unwrap();- let mut a =- designcraft_doc::Item::new(designcraft_doc::ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 16.0)));- a.fill = Fill::swatch(designcraft_color::swatch::BLACK);- let b = designcraft_doc::Item::new(designcraft_doc::ItemId(d.alloc()), lid, Shape::Oval, shapes::ellipse(Rect::new(0.0, 0.0, 60.0, 30.0)));- {- let s = d.story_mut(sid).unwrap();- s.insert_object(7, AnchoredObject::new(a, AnchorPosition::Inline { y_offset: 2.0 }));- let at = s.text.find("Above").unwrap();- s.insert_object(at, AnchoredObject::new(b, AnchorPosition::AboveLine { align: AnchorAlign::Center, space_before: 3.0, space_after: 4.0 }));++fn keep_lines_mode_defaults_to_start_and_end() {++ let keep = r#"KeepLinesTogether="true" KeepFirstLines="2" KeepLastLines="2""#;++ for (attrs, all) in [(keep.to_string(), false), (format!(r#"{keep} KeepAllLinesTogether="true""#), true)] {++ let d = import_idml_with(&fixture_with_styles(&keep_styles(&attrs)), &|_| None).unwrap();++ for name in ["Body", "Loose"] {++ let (pp, _) = d.styles.resolve_para_style(name);++ assert_eq!((pp.keep_lines_together, pp.keep_all_lines, pp.keep_first, pp.keep_last), (true, all, 2, 2), "{name}: {attrs}");++ }+ }- d.check().unwrap();- let back = import_idml(&export_idml(&d)).unwrap();- back.check().unwrap();- let s = back.stories.values().find(|s| !s.objects.is_empty()).unwrap();- assert_eq!(s.text, d.story(sid).unwrap().text);- assert_eq!(s.objects.len(), 2);- let (w, h) = s.objects[0].size();- assert!((w - 20.0).abs() < 1e-6 && (h - 16.0).abs() < 1e-6);- assert_eq!(s.objects[0].position, AnchorPosition::Inline { y_offset: 2.0 });- assert_eq!(s.objects[0].item.fill.swatch, designcraft_color::swatch::BLACK);- assert_eq!(s.objects[1].item.shape, Shape::Oval);- assert_eq!(s.objects[1].position, AnchorPosition::AboveLine { align: AnchorAlign::Center, space_before: 3.0, space_after: 4.0 });+}+- #[test]- fn round_trips_frames_with_pasted_in_items() {- let mut d = Document::new(&NewDocument::default());- let lid = d.default_layer();- let inner = designcraft_doc::Item::new(designcraft_doc::ItemId(d.alloc()), lid, Shape::Oval, shapes::ellipse(Rect::new(0.0, 0.0, 300.0, 300.0)));- let mut frame = designcraft_doc::Item::new(- designcraft_doc::ItemId(d.alloc()),- lid,- Shape::Rectangle,- shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)),- );- frame.content = designcraft_doc::Content::Group { items: vec![std::sync::Arc::new(inner)] };- d.insert_item(SpreadRef::Doc(0), frame, None).unwrap();- let back = import_idml(&export_idml(&d)).unwrap();- let f = &back.spreads[0].items[0];- assert_eq!(f.shape, Shape::Rectangle);- assert!(f.has_nested_items(), "{:?}", f.content);- assert_eq!(f.children()[0].shape, Shape::Oval);- let b = f.bounds();- assert!((b.x0 - 100.0).abs() < 0.01 && (b.x1 - 200.0).abs() < 0.01, "{b:?}");++type Resolved = (designcraft_doc::ParaProps, designcraft_doc::CharProps);++++/// (IDML attribute, InDesign's default as IDML writes it, another value, the resolved field,++/// its value for InDesign's default, its value for the other value).++type AttrRow = (&'static str, &'static str, &'static str, fn(&Resolved) -> String, String, String);++++macro_rules! attr_rows {++ ($($attr:literal: $default:literal => $dv:expr, $other:literal => $ov:expr, |$r:ident| $field:expr;)*) => {++ vec![$(($attr, $default, $other, (|$r: &Resolved| format!("{:?}", $field)) as fn(&Resolved) -> String, format!("{:?}", $dv), format!("{:?}", $ov)),)*]++ };+}+- #[test]- fn vertical_story_orientation_round_trips() {- let mut d = Document::new(&NewDocument::default());- let lid = d.default_layer();- let (a, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 200.0, 400.0), lid, "縦書き", ParaFormat::default()).unwrap();- let (b, _) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(300.0, 72.0, 428.0, 400.0), lid, "", ParaFormat::default()).unwrap();- d.thread(a, b).unwrap();- d.add_text_frame(SpreadRef::Doc(0), Rect::new(450.0, 72.0, 550.0, 400.0), lid, "横", ParaFormat::default()).unwrap();- d.story_mut(sid).unwrap().vertical = true;- // Orientation and column direction are separate settings of the story.- d.story_mut(sid).unwrap().direction = designcraft_doc::TextDirection::RightToLeft;- let back = import_idml(&export_idml(&d)).unwrap();- use designcraft_doc::TextDirection::{LeftToRight, RightToLeft};- let directions: Vec<_> = back.stories.values().map(|s| (s.frames.len(), s.vertical, s.direction)).collect();- assert!(directions.contains(&(2, true, RightToLeft)) && directions.contains(&(1, false, LeftToRight)), "{directions:?}");- let frames: Vec<bool> = back.spreads[0].items.iter().map(|i| back.frame_vertical(i)).collect();- assert_eq!(frames, [true, true, false]);++/// InDesign's defaults for a new document's [No Paragraph Style], for every paragraph and++/// character attribute the importer reads (except the font family: see below).++fn indesign_text_defaults() -> Vec<AttrRow> {++ use designcraft_doc::{Align, Capitalization, Composer, Digits, GridAlign, Leading, ListType, Position, StartParagraph, TextDirection};++ attr_rows! {++ "Justification": "LeftAlign" => Align::Left, "CenterAlign" => Align::Center, |r| r.0.align;++ "ParagraphDirection": "LeftToRightDirection" => TextDirection::LeftToRight, "RightToLeftDirection" => TextDirection::RightToLeft, |r| r.0.direction;++ "LeftIndent": "0" => 0.0, "6" => 6.0, |r| r.0.left_indent;++ "RightIndent": "0" => 0.0, "6" => 6.0, |r| r.0.right_indent;++ "FirstLineIndent": "0" => 0.0, "6" => 6.0, |r| r.0.first_line_indent;++ "LastLineIndent": "0" => 0.0, "6" => 6.0, |r| r.0.last_line_indent;++ "SpaceBefore": "0" => 0.0, "6" => 6.0, |r| r.0.space_before;++ "SpaceAfter": "0" => 0.0, "6" => 6.0, |r| r.0.space_after;++ "DropCapLines": "0" => 0, "3" => 3, |r| r.0.drop_cap_lines;++ "DropCapCharacters": "0" => 0, "1" => 1, |r| r.0.drop_cap_chars;++ "DropcapDetail": "1" => (true, false), "2" => (false, true), |r| (r.0.drop_cap_align_left, r.0.drop_cap_scale_descenders);++ "GridAlignment": "None" => GridAlign::None, "AlignToBaseline" => GridAlign::AllLines, |r| r.0.grid_align;++ "Composer": "HL Composer" => Composer::Paragraph, "HL Single" => Composer::SingleLine, |r| r.0.composer;++ "Hyphenation": "true" => true, "false" => false, |r| r.0.hyphenate;++ "HyphenateWordsLongerThan": "5" => 5, "7" => 7, |r| r.0.hyph_min_word;++ "HyphenateAfterFirst": "2" => 2, "3" => 3, |r| r.0.hyph_after_first;++ "HyphenateBeforeLast": "2" => 2, "3" => 3, |r| r.0.hyph_before_last;++ "HyphenateLadderLimit": "3" => 3, "0" => 0, |r| r.0.hyph_limit;++ "HyphenationZone": "36" => 36.0, "18" => 18.0, |r| r.0.hyph_zone;++ "HyphenateCapitalizedWords": "true" => true, "false" => false, |r| r.0.hyph_capitalized;++ "HyphenateLastWord": "true" => true, "false" => false, |r| r.0.hyph_last_word;++ "HyphenateAcrossColumns": "true" => true, "false" => false, |r| r.0.hyph_across_column;++ "HyphenWeight": "5" => 0.5, "9" => 0.9, |r| r.0.hyph_weight;++ "MinimumWordSpacing": "80" => 0.8, "70" => 0.7, |r| r.0.word_space_min;++ "DesiredWordSpacing": "100" => 1.0, "90" => 0.9, |r| r.0.word_space_desired;++ "MaximumWordSpacing": "133" => 1.33, "150" => 1.5, |r| r.0.word_space_max;++ "MinimumLetterSpacing": "0" => 0.0, "-5" => -0.05, |r| r.0.letter_space_min;++ "DesiredLetterSpacing": "0" => 0.0, "1" => 0.01, |r| r.0.letter_space_desired;++ "MaximumLetterSpacing": "0" => 0.0, "5" => 0.05, |r| r.0.letter_space_max;++ "MinimumGlyphScaling": "100" => 1.0, "97" => 0.97, |r| r.0.glyph_scale_min;++ "DesiredGlyphScaling": "100" => 1.0, "101" => 1.01, |r| r.0.glyph_scale_desired;++ "MaximumGlyphScaling": "100" => 1.0, "103" => 1.03, |r| r.0.glyph_scale_max;++ "AutoLeading": "120" => 1.2, "100" => 1.0, |r| r.0.auto_leading;++ "SingleWordJustification": "FullyJustified" => Align::FullyJustified, "LeftAlign" => Align::Left, |r| r.0.single_word_justify;++ "KeepWithNext": "0" => 0, "1" => 1, |r| r.0.keep_with_next;++ "KeepLinesTogether": "false" => false, "true" => true, |r| r.0.keep_lines_together;++ "KeepAllLinesTogether": "false" => false, "true" => true, |r| r.0.keep_all_lines;++ "KeepFirstLines": "2" => 2, "3" => 3, |r| r.0.keep_first;++ "KeepLastLines": "2" => 2, "3" => 3, |r| r.0.keep_last;++ "StartParagraph": "Anywhere" => StartParagraph::Anywhere, "NextColumn" => StartParagraph::NextColumn, |r| r.0.start_paragraph;++ "BulletsAndNumberingListType": "NoList" => ListType::None, "BulletList" => ListType::Bullets, |r| r.0.list_type;++ "BalanceRaggedLines": "NoBalancing" => false, "FullyBalanced" => true, |r| r.0.balance_ragged;++ "Kashidas": "DefaultKashidas" => true, "KashidasOff" => false, |r| r.0.kashidas;++ "RuleAbove": "false" => false, "true" => true, |r| r.0.rule_above.on;++ "RuleAboveColor": "Text Color" => designcraft_doc::TEXT_COLOR, "Color/Black" => "[Black]", |r| r.0.rule_above.color;++ "RuleAboveTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.rule_above.tint;++ "RuleBelow": "false" => false, "true" => true, |r| r.0.rule_below.on;++ "RuleBelowColor": "Text Color" => designcraft_doc::TEXT_COLOR, "Color/Black" => "[Black]", |r| r.0.rule_below.color;++ "RuleBelowTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.rule_below.tint;++ "ParagraphShadingOn": "false" => false, "true" => true, |r| r.0.shading_on;++ "ParagraphShadingColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.0.shading_color;++ "ParagraphShadingTint": "20" => 0.2f32, "50" => 0.5f32, |r| r.0.shading_tint;++ "ParagraphBorderOn": "false" => false, "true" => true, |r| r.0.border_on;++ "ParagraphBorderColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.0.border_color;++ "ParagraphBorderTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.0.border_tint;++ "FontStyle": "Regular" => "Regular", "Bold" => "Bold", |r| r.1.font_style;++ "PointSize": "12" => 12.0, "9" => 9.0, |r| r.1.size;++ "Leading": "Auto" => Leading::Auto, "14" => Leading::Points(14.0), |r| r.1.leading;++ "KerningMethod": "$ID/Metrics" => designcraft_doc::Kerning::Metrics, "$ID/Optical" => designcraft_doc::Kerning::Optical, |r| r.1.kerning;++ "Tracking": "0" => 0.0, "20" => 20.0, |r| r.1.tracking;++ "HorizontalScale": "100" => 1.0, "90" => 0.9, |r| r.1.h_scale;++ "VerticalScale": "100" => 1.0, "90" => 0.9, |r| r.1.v_scale;++ "BaselineShift": "0" => 0.0, "2" => 2.0, |r| r.1.baseline_shift;++ "Skew": "0" => 0.0, "10" => 10.0, |r| r.1.skew;++ "FillColor": "Color/Black" => "[Black]", "Swatch/None" => "[None]", |r| r.1.fill;++ "FillTint": "-1" => 1.0, "50" => 0.5, |r| r.1.fill_tint;++ "StrokeColor": "Swatch/None" => "[None]", "Color/Black" => "[Black]", |r| r.1.stroke;++ "StrokeTint": "-1" => 1.0, "50" => 0.5, |r| r.1.stroke_tint;++ "StrokeWeight": "1" => 1.0, "2" => 2.0, |r| r.1.stroke_weight;++ "Capitalization": "Normal" => Capitalization::Normal, "AllCaps" => Capitalization::AllCaps, |r| r.1.capitalization;++ "Position": "Normal" => Position::Normal, "Superscript" => Position::Superscript, |r| r.1.position;++ "Underline": "false" => false, "true" => true, |r| r.1.underline;++ "StrikeThru": "false" => false, "true" => true, |r| r.1.strikethrough;++ "UnderlineTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.1.underline_tint;++ "StrikeThruTint": "-1" => 1.0f32, "50" => 0.5f32, |r| r.1.strikethrough_tint;++ "Ligatures": "true" => true, "false" => false, |r| r.1.ligatures;++ "NoBreak": "false" => false, "true" => true, |r| r.1.no_break;++ "OTFContextualAlternate": "true" => true, "false" => false, |r| designcraft_doc::otf::is_on(&r.1.otf_features, "calt");++ "DigitsType": "DefaultDigits" => Digits::Default, "ArabicDigits" => Digits::Arabic, |r| r.1.digits;++ "AppliedLanguage": "$ID/English: USA" => "English: USA", "$ID/German: 2006 Reform" => "German: 2006 Reform", |r| r.1.language;++ }+}+- #[test]- fn cjk_character_attributes_import_from_independent_xml_and_round_trip() {- 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]" BunriKinshi="true" Rensuuji="false" TreatIdeographicSpaceAsSpace="true">- <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" LeadingAki="0.25" TrailingAki="-1" Tsume="20" Jidori="4" LeadingModel="LeadingModelCenter" CharacterAlignment="AlignEmCenter" KentenKind="KentenWhiteCircle"><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 a = &st.runs().next().unwrap().1.over;- assert_eq!(a.leading_aki, Some(Some(0.25)));- assert_eq!(a.trailing_aki, Some(None));- assert_eq!(a.jidori, Some(4));- assert_eq!(a.tsume, Some(0.2));- assert_eq!(a.kenten_character.as_deref(), Some("○"));- assert_eq!(a.leading_model, Some(designcraft_doc::cjk::LeadingModel::Center));- assert_eq!(st.paras[0].para.bunri_kinshi, Some(true));- assert_eq!(st.paras[0].para.rensuuji, Some(false));- let back = import_idml(&export_idml(&doc)).unwrap();- let st2 = back.stories.values().find(|s| s.text.contains("甲乙")).unwrap();- let b = &st2.runs().next().unwrap().1.over;- assert_eq!(a.leading_aki, b.leading_aki);- assert_eq!(a.trailing_aki, b.trailing_aki);- assert_eq!(a.kenten_character, b.kenten_character);- assert_eq!(a.leading_model, b.leading_model);++/// [No paragraph style] with `root` attributes and `Body`, based on it, with `body` attributes.++fn text_styles(root: &str, body: &str) -> String {++ format!(++ r#"<?xml version="1.0" encoding="UTF-8"?>++<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">++ <RootParagraphStyleGroup Self="rp">++ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" {root}/>++ <ParagraphStyle Self="ParagraphStyle/Body" Name="Body" {body}>++ <Properties><BasedOn type="object">ParagraphStyle/$ID/[No paragraph style]</BasedOn></Properties>++ </ParagraphStyle>++ </RootParagraphStyleGroup>++</idPkg:Styles>"#++ )++}++++fn resolve_body(root: &str, body: &str) -> Resolved {++ let d = import_idml_with(&fixture_with_styles(&text_styles(root, body)), &|_| None).unwrap();++ d.styles.resolve_para_style("Body")+}+++/// Text attributes an IDML file leaves unset are InDesign's defaults; written ones win, and a++/// file that writes every default (as InDesign's own exports do) imports the same.+#[test]- fn automatic_kerning_does_not_import_inactive_numeric_values() {- for (attributes, expected) in [- (r#"KerningMethod="$ID/Optical" KerningValue="1e+11""#, Some(designcraft_doc::Kerning::Optical)),- (r#"KerningMethod="$ID/Metrics" KerningValue="0""#, Some(designcraft_doc::Kerning::Metrics)),- (r#"KerningValue="-40""#, Some(designcraft_doc::Kerning::Manual(-40.0))),- (r#"KerningValue="1e+11""#, None),- ] {- let story = format!(- 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]" {attributes}><Content>甲乙</Content></CharacterStyleRange>- </ParagraphStyleRange></Story></idPkg:Story>"#- );- let d = import_idml(&fixture_with_story(&story)).unwrap();- let s = d.stories.values().find(|s| s.text.contains("甲乙")).unwrap();- assert_eq!(s.runs().next().unwrap().1.over.kerning, expected, "{attributes}");++fn absent_text_attributes_take_indesign_defaults() {++ let rows = indesign_text_defaults();++ let all = |pick: fn(&AttrRow) -> &str| rows.iter().map(|r| format!(r#"{}="{}""#, r.0, pick(r))).collect::<Vec<_>>().join(" ");++ let (defaults, others) = (all(|r| r.1), all(|r| r.2));++ let omitted = resolve_body("", "");++ let written = resolve_body(&defaults, "");++ for (attr, _, _, field, want, _) in &rows {++ assert_eq!(field(&omitted), *want, "{attr} omitted");++ assert_eq!(field(&written), *want, "{attr} written as InDesign's default");++ }++ assert_eq!(omitted, written);++ for (root, body) in [(others.as_str(), ""), ("", others.as_str())] {++ let r = resolve_body(root, body);++ for (attr, _, _, field, _, want) in &rows {++ assert_eq!(field(&r), *want, "{attr} written on the {}", if root.is_empty() { "style" } else { "root" });++ }+ }++ // Product difference: InDesign's default face isn't available, so unset fonts are DesignCraft's.++ assert_eq!(omitted.1.font_family, designcraft_doc::CharProps::default().font_family);+}+++/// A tint of -1 is the colour's own tint (100 %): written on a style, it replaces its parent's.++/// Tints are never negative or above 100 %.+#[test]- fn cjk_composite_fonts_and_custom_kinsoku_are_document_resources() {- let map = DESIGNMAP.replace("</Document>", r#"- <KinsokuTable Self="KinsokuTable/Test" Name="Test" CantBeginLineChars="乙" CantEndLineChars="甲" CantBeSeparatedChars="—" HangingPunctuationChars="。"/>- <CompositeFont Self="CompositeFont/Mixed" Name="Mixed"><CompositeFontEntry Self="cf1" Name="Base" FontStyle="Regular"><Properties><AppliedFont type="string">Source Serif 4</AppliedFont></Properties></CompositeFontEntry>- <CompositeFontEntry Self="cf2" Name="Digits" CustomCharacters="0123456789" FontStyle="Regular" RelativeSize="80" BaselineShift="10"><Properties><AppliedFont type="string">Source Sans 3</AppliedFont></Properties></CompositeFontEntry></CompositeFont>- </Document>"#);- let story = STORY.replace("<ParagraphStyleRange ", "<ParagraphStyleRange KinsokuSet=\"KinsokuTable/Test\" ");- let bytes = zip_files(&[- ("designmap.xml", &map),- ("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(&bytes).unwrap();- let f = &d.styles.composite_fonts[0];- assert_eq!(f.entry('1').unwrap().family, "Source Sans 3");- assert_eq!(f.entry('甲').unwrap().family, "Source Serif 4");- assert_eq!(f.entry('1').unwrap().relative_size, 0.8);- let back = import_idml(&export_idml(&d)).unwrap();- assert_eq!(back.styles.composite_fonts, d.styles.composite_fonts);- assert!(- back.stories.values().flat_map(|s| &s.paras).any(|p| p.para.kinsoku.as_ref().and_then(Option::as_ref).is_some_and(|k| k.no_start == "乙"))- );++fn minus_one_tint_is_the_colours_own() {++ let tints = |v: &str| {++ ["UnderlineTint", "StrikeThruTint", "FillTint", "StrokeTint", "ParagraphShadingTint", "ParagraphBorderTint", "RuleAboveTint", "RuleBelowTint"]++ .map(|k| format!(r#"{k}="{v}""#))++ .join(" ")++ + r#" RuleAbove="true" RuleBelow="true""#++ };++ for (body, want) in [("-1", 1.0), ("150", 1.0)] {++ let r = resolve_body(&tints("50"), &tints(body));++ let got = [++ r.1.underline_tint,++ r.1.strikethrough_tint,++ r.1.fill_tint,++ r.1.stroke_tint,++ r.0.shading_tint,++ r.0.border_tint,++ r.0.rule_above.tint,++ r.0.rule_below.tint,++ ];++ assert_eq!(got, [want; 8], "{body}");++ }++ // Footnote rules, table fills and strokes, cell fills.++ let prefs = PREFS.replace("</idPkg:Preferences>", r#"<FootnoteOption RuleTint="-1"/></idPkg:Preferences>"#);++ let story = r#"<?xml version="1.0" encoding="UTF-8"?>++<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">++<Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Table Self="tb" StartRowFillCount="1" StartRowFillTint="-1" EndRowFillTint="-1" TopBorderStrokeTint="-1">++<Row Self="r0" Name="0"/><Column Self="c0" Name="0"/><Cell Self="ce" Name="0:0" FillColor="Color/Black" FillTint="-1" TopEdgeStrokeTint="-1"/></Table></CharacterStyleRange></ParagraphStyleRange></Story>++</idPkg:Story>"#;++ let d = import_idml_with(++ &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),++ ]),++ &|_| None,++ )++ .unwrap();++ assert_eq!(d.footnote_options.rule.tint, 1.0);++ let t = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();++ let alt = t.options.alt_rows.as_ref().unwrap();++ assert_eq!((alt.first_tint, alt.next_tint, t.options.border.tint), (1.0, 1.0, 1.0));++ let c = t.cell(0, 0).unwrap();++ assert_eq!((c.fill_tint, c.strokes[0].tint), (1.0, 1.0));+}+++/// Rules in Text Color take the colour of the paragraph's text; they round-trip as Text Color.+#[test]- fn cjk_unsupported_mojikumi_is_preserved_instead_of_silently_dropped() {- let map = DESIGNMAP.replace("</Document>", r#"<MojikumiTable Self="MojikumiTable/Spacing" Name="Spacing" BasedOnMojikumiSet="SimpChineseDefault"><Properties><OverrideMojikumiAkiList>- <OverrideMojikumiAkiType TargetMojikumiClass="1" SideMojikumiClass="23" SideIsAfterTarget="false" Minimum="-0.1" Desired="0.25" Maximum="0.5" CompressionPriority="3" AkiDoesNotFloat="true"/>- </OverrideMojikumiAkiList></Properties></MojikumiTable></Document>"#);- let story =- STORY.replace("<ParagraphStyleRange ", "<ParagraphStyleRange Mojikumi=\"MojikumiTable/Spacing\" KinsokuType=\"KinsokuPushOutFirst\" ");- let bytes = zip_files(&[- ("designmap.xml", &map),- ("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(&bytes).unwrap();- let t = &d.styles.mojikumi_tables[0];- assert_eq!(t.overrides[0].minimum, -0.1);- assert!(t.overrides[0].does_not_float);- let back = import_idml(&export_idml(&d)).unwrap();- assert_eq!(back.styles.mojikumi_tables, d.styles.mojikumi_tables);- assert!(back.stories.values().flat_map(|s| &s.paras).any(|p| p.para.mojikumi.as_deref() == Some("MojikumiTable/Spacing")));++fn text_color_rules_round_trip() {++ let mut d = Document::new(&NewDocument::default());++ let lid = d.default_layer();++ let rule = designcraft_doc::Rule { on: true, ..Default::default() };++ assert_eq!(rule.color, designcraft_doc::TEXT_COLOR);++ let para = designcraft_doc::ParaAttrs {++ rule_above: Some(rule.clone()),++ rule_below: Some(designcraft_doc::Rule { color: "[Black]".into(), ..rule }),++ kashidas: Some(false),++ ..Default::default()++ };++ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, 40.0, 400.0, 400.0), lid, "Ruled", ParaFormat::default()).unwrap();++ d.story_mut(sid).unwrap().paras[0].para = para.clone();++ let bytes = export_idml(&d);++ let story = zip_text(&bytes, "Stories/");++ assert!(story.contains(r#"<RuleAboveColor type="string">Text Color</RuleAboveColor>"#), "{story}");++ assert!(story.contains(r#"Kashidas="KashidasOff""#), "{story}");++ let back = import_idml(&bytes).unwrap();++ let p = &back.stories.values().find(|s| s.text == "Ruled").unwrap().paras[0];++ assert_eq!((p.para.rule_above.as_ref(), p.para.rule_below.as_ref()), (para.rule_above.as_ref(), para.rule_below.as_ref()));++ assert_eq!(p.para.kashidas, Some(false));+}+++/// `[Basic Paragraph]` is InDesign's `$ID/NormalParagraphStyle`, both ways.+#[test]- fn arabic_controls_import_independent_xml_and_round_trip() {- 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]" ParagraphDirection="RightToLeftDirection" Kashidas="KashidasOff" ParagraphJustification="NaskhJustification" ParagraphKashidaWidth="2">- <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" CharacterDirection="LeftToRightDirection" Kashidas="KashidasOff" DiacriticPosition="OpentypePosition" XOffsetDiacritic="150" YOffsetDiacritic="-100" PositionalForm="Medial"><Properties><DigitsType type="enumeration">FarsiDigits</DigitsType></Properties><Content>بَ123</Content></CharacterStyleRange>- </ParagraphStyleRange></Story></idPkg:Story>"#;- let d = import_idml(&fixture_with_story(story)).unwrap();- let st = d.stories.values().find(|s| s.text.contains('ب')).unwrap();- assert_eq!(st.paras[0].para.kashidas, Some(false));- assert_eq!(st.paras[0].para.arabic_justification.as_deref(), Some("NaskhJustification"));- let a = &st.runs().next().unwrap().1.over;- assert_eq!(a.character_direction, Some(designcraft_doc::arabic::CharacterDirection::LeftToRight));- assert_eq!(a.allow_kashidas, Some(false));- assert_eq!(a.diacritic_x_offset, Some(150.0));- assert_eq!(a.diacritic_y_offset, Some(-100.0));- assert_eq!(a.digits, Some(designcraft_doc::Digits::Farsi));- let back = import_idml(&export_idml(&d)).unwrap();- let b = back.stories.values().find(|s| s.text.contains('ب')).unwrap();- let attrs = &b.runs().next().unwrap().1.over;- assert_eq!(attrs.character_direction, a.character_direction);- assert_eq!(attrs.diacritic_x_offset, a.diacritic_x_offset);- assert_eq!(attrs.diacritic_y_offset, a.diacritic_y_offset);- assert_eq!(attrs.allow_kashidas, a.allow_kashidas);- assert_eq!(attrs.positional_form, a.positional_form);- assert_eq!(b.paras[0].para.paragraph_kashida_width, Some(Some(2.0)));++fn basic_paragraph_is_normal_paragraph_style() {++ let d = import_idml_with(&fixture(), &|_| None).unwrap();++ let basic = d.styles.para(st::BASIC_PARAGRAPH).unwrap();++ assert_eq!(basic.based_on.as_deref(), Some(designcraft_doc::NO_PARA_STYLE));++ assert_eq!(d.styles.para("Text/Body").unwrap().based_on.as_deref(), Some(st::BASIC_PARAGRAPH));++ let s = d.stories.values().find(|s| s.text.starts_with("Hello")).unwrap();++ assert_eq!(s.paras[1].style, st::BASIC_PARAGRAPH);++ assert!(d.styles.paragraph.iter().all(|p| !p.name.contains("NormalParagraphStyle")));++ let bytes = export_idml(&d);++ let styles = zip_text(&bytes, "Resources/Styles.xml");++ assert!(styles.contains(r#"Self="ParagraphStyle/$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle""#), "{styles}");++ assert!(zip_text(&bytes, "Stories/").contains(r#"AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle""#));++ let back = import_idml(&bytes).unwrap();++ assert_eq!(back.styles.paragraph.iter().filter(|p| p.name == st::BASIC_PARAGRAPH).count(), 1);+}+++/// Page items, frames, tables and preferences an IDML file leaves unset are InDesign's defaults++/// for a new document.+#[test]- fn arabic_story_and_table_directions_survive_idml_export() {- let mut d = Document::new(&NewDocument::default());- let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 300.0, 300.0), d.default_layer(), "", ParaFormat::default()).unwrap();- let st = d.story_mut(sid).unwrap();- st.direction = designcraft_doc::TextDirection::RightToLeft;- let mut t = designcraft_doc::Table::new(42, 1, 2, 0, 0, 200.0);- t.options.direction = designcraft_doc::TextDirection::RightToLeft;- st.insert_table(0, t);- let back = import_idml(&export_idml(&d)).unwrap();- let st = back.stories.values().find(|st| !st.tables.is_empty()).unwrap();- assert_eq!(st.direction, designcraft_doc::TextDirection::RightToLeft);- assert_eq!(st.tables.values().next().unwrap().options.direction, designcraft_doc::TextDirection::RightToLeft);++fn absent_item_and_document_attributes_take_indesign_defaults() {++ use designcraft_doc::{Cap, FirstBaseline, Join, StrokeAlign, VerticalJustification};++ use designcraft_geom::corners::CornerShape;++ let path = |x: f64| {++ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]++ .iter()++ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))++ .collect();++ format!(++ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#++ )++ };++ let designmap = format!(++ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>++<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0" Self="d">++<NumberingList Self="NumberingList/Steps" Name="Steps"/>++<RootTableStyleGroup Self="rts"><TableStyle Self="TableStyle/Banded" Name="Banded" StartRowFillCount="1"/></RootTableStyleGroup>++<Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Table Self="tb" StartRowFillCount="1" StartColumnFillCount="2"><Row Self="r0" Name="0"/><Column Self="c0" Name="0"/><Cell Self="ce" Name="0:0"/></Table></CharacterStyleRange></ParagraphStyleRange></Story>++<Spread Self="sp1"><Page Self="p1"/>++<Rectangle Self="plain">{}</Rectangle>++<Rectangle Self="round" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner">{}</Rectangle>++<Rectangle Self="legacy" CornerOption="RoundedCorner">{}</Rectangle>++<Rectangle Self="sized" TopLeftCornerOption="RoundedCorner" TopLeftCornerRadius="5">{}</Rectangle>++<TextFrame Self="tf" ParentStory="s1">{}</TextFrame>++</Spread>++</Document>"#,++ path(0.0),++ path(100.0),++ path(200.0),++ path(300.0),++ path(400.0)++ );++ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();++ // Document Setup, margins and columns, grids, Advanced Type, transparency, black.++ let s = &d.settings;++ assert_eq!((s.page_width, s.page_height, s.facing_pages, s.intent), (612.0, 792.0, true, designcraft_doc::Intent::Print));++ assert_eq!((s.bleed, s.slug), ([0.0; 4], [0.0; 4]));++ let page = &d.spreads[0].pages[0];++ assert_eq!((page.margins.top, page.margins.bottom, page.margins.inside, page.margins.outside), (36.0, 36.0, 36.0, 36.0));++ assert_eq!((page.columns.count, page.columns.gutter), (1, 12.0));++ assert_eq!((s.baseline_grid.start, s.baseline_grid.increment, s.baseline_grid.view_threshold), (36.0, 12.0, 0.75));++ assert_eq!((s.grid.horizontal, s.grid.vertical, s.grid.subdivisions, s.grid.in_back), (72.0, 72.0, 8, true));++ let a = &s.advanced_type;++ assert_eq!((a.superscript_size, a.superscript_position, a.subscript_size, a.subscript_position), (58.3, 33.3, 58.3, 33.3));++ assert_eq!((s.blend_space, s.overprint_black, s.keyboard_increment), (designcraft_doc::BlendSpace::Cmyk, true, 1.0));++ // Fill, stroke, transparency, wrap and corners of a frame with no attributes.++ let item = |n: usize| d.spreads[0].items[n].clone();++ let plain = item(0);++ assert!(plain.fill.is_none() && plain.stroke.is_none());++ let st = &plain.stroke;++ assert_eq!((st.weight, st.miter_limit, st.cap, st.join, st.align), (1.0, 4.0, Cap::Butt, Join::Miter, StrokeAlign::Center));++ assert_eq!((plain.opacity, plain.blend, plain.wrap.mode), (1.0, designcraft_color::BlendMode::Normal, designcraft_doc::WrapMode::None));++ assert!(plain.corners.is_none());++ // A corner shape without a size: 12 pt.++ for n in [1, 2] {++ assert_eq!(item(n).corners.corners.map(|c| (c.shape, c.size)), [(CornerShape::Rounded, 12.0); 4], "item {n}");++ }++ assert_eq!(item(3).corners.corners[0].size, 5.0);++ // Text Frame Options.++ let tf = item(4);++ let o = &tf.text_frame().unwrap().options;++ assert_eq!((o.columns, o.gutter, o.inset, o.balance_columns, o.ignore_wrap), (1, 12.0, [0.0; 4], false, false));++ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Top, FirstBaseline::Ascent, 0.0));++ assert_eq!((o.auto_size, o.auto_size_ref), (designcraft_doc::AutoSize::Off, 4), "auto-size from the centre");++ // Numbered lists don't continue across stories.++ assert_eq!(d.settings.lists, vec![designcraft_doc::NumberedList { name: "Steps".into(), continue_across_stories: false }]);++ // Table and cell options.++ let t = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();++ assert_eq!((t.options.space_before, t.options.space_after, t.options.repeat_header), (4.0, -4.0, true));++ assert_eq!((t.options.border.weight, t.options.border.color.as_str()), (1.0, "[Black]"));++ assert_eq!((t.rows[0].mode, t.rows[0].height), (designcraft_doc::RowHeightMode::AtLeast, 3.0));++ // Alternating fills: the first rows or columns Black 20 %, the next None.++ let fills = |a: &designcraft_doc::AltFills| (a.first_color.clone(), a.first_tint, a.next_color.clone(), a.next_tint, a.next);++ let want = ("[Black]".to_string(), 0.2f32, "[None]".to_string(), 1.0f32, 1);++ assert_eq!(fills(t.options.alt_rows.as_ref().unwrap()), want);++ let cols = t.options.alt_cols.as_ref().unwrap();++ assert_eq!((fills(cols), cols.first), (want.clone(), 2));++ let banded = d.styles.table.iter().find(|s| s.name == "Banded").unwrap();++ assert_eq!(fills(banded.alt_rows.as_ref().unwrap()), want);++ let c = t.cell(0, 0).unwrap();++ assert_eq!((c.insets, c.vj, c.fill.as_str()), ([4.0; 4], VerticalJustification::Top, "[None]"));++ for e in &c.strokes {++ assert_eq!((e.weight, e.color.as_str(), e.tint, &e.kind), (1.0, "[Black]", 1.0, &designcraft_doc::StrokeType::Solid));++ }+}++#[test]+fn drop_caps_import_and_round_trip() {+ // A style with a drop cap, its character style and a nested style through it; a paragraph+ // overriding it locally.+ let opener = r#"<ParagraphStyle Self="ParagraphStyle/Opener" Name="Opener" DropCapCharacters="1" DropCapLines="3">+ <Properties><DropCapStyle type="object">CharacterStyle/Strong</DropCapStyle><AllNestedStyles type="list"><ListItem type="record">+ <AppliedCharacterStyle type="object">CharacterStyle/Strong</AppliedCharacterStyle><Delimiter type="enumeration">Dropcap</Delimiter>+ <Repetition type="long">1</Repetition><Inclusive type="boolean">true</Inclusive></ListItem></AllNestedStyles></Properties>+ </ParagraphStyle>+ </RootParagraphStyleGroup>"#;+ let styles = STYLES.replace("</RootParagraphStyleGroup>", opener);+ let story = r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Opener" DropCapCharacters="2" DropCapLines="2" DropCapStyle="CharacterStyle/$ID/[No character style]">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Once upon a time</Content></CharacterStyleRange>+ </ParagraphStyleRange>+ </Story>+</idPkg:Story>"#;+ 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 check = |d: &Document| {+ let st = d.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines), (Some(1), Some(3)));+ assert_eq!(st.para.drop_cap_style.as_deref(), Some("Strong"));+ let ns = st.para.nested_styles.clone().unwrap();+ assert_eq!((ns[0].style.as_str(), &ns[0].until), ("Strong", &designcraft_doc::NestedUntil::Dropcap));+ let p = &d.stories.values().find(|s| s.text.starts_with("Once")).unwrap().paras[0];+ assert_eq!((p.para.drop_cap_chars, p.para.drop_cap_lines), (Some(2), Some(2)));+ assert_eq!(p.para.drop_cap_style.as_deref(), Some(st::NO_CHAR_STYLE));+ };+ let d = import_idml_with(&bytes, &|_| None).unwrap();+ check(&d);+ // The drop cap's character style isn't written to IDML (InDesign sets it through a Dropcap+ // nested style); Align Left Edge and Scale for Descenders are, as DropcapDetail.+ let mut d = d;+ if let Some(s) = d.styles_mut().para_mut("Opener") {+ s.para.drop_cap_align_left = Some(false);+ s.para.drop_cap_scale_descenders = Some(true);+ }+ let bytes = export_idml(&d);+ assert!(!zip_text(&bytes, "").contains("DropCapStyle"));+ assert!(zip_text(&bytes, "Resources/Styles.xml").contains(r#"DropcapDetail="2""#));+ let back = import_idml(&bytes).unwrap();+ let st = back.styles.para("Opener").unwrap();+ assert_eq!((st.para.drop_cap_chars, st.para.drop_cap_lines, st.para.drop_cap_style.as_deref()), (Some(1), Some(3), None));+ assert_eq!((st.para.drop_cap_align_left, st.para.drop_cap_scale_descenders), (Some(false), Some(true)));+ assert_eq!(st.para.nested_styles.as_ref().map(|n| n[0].until.clone()), Some(designcraft_doc::NestedUntil::Dropcap));+}++/// Frames take the corners and Text Frame Options they don't write from their object style chain,+/// then `[None]`. Per-corner attributes win over the legacy all-corners pair, at each level; a+/// corner shape without a radius takes the chain's radius.+#[test]+fn frames_inherit_object_style_corners_and_text_frame_options() {+ use designcraft_doc::{AutoSize, FirstBaseline, VerticalJustification};+ use designcraft_geom::corners::CornerShape as C;+ // Anchors in the order top-left, bottom-left, bottom-right, top-right.+ let path = |x: f64| {+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]+ .iter()+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))+ .collect();+ format!(+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#+ )+ };+ let corners = |opt: &str, r: &str| {+ ["TopLeft", "TopRight", "BottomLeft", "BottomRight"].map(|n| format!(r#"{n}CornerOption="{opt}" {n}CornerRadius="{r}""#)).join(" ")+ };+ let inset = |v: f64| {+ format!(+ r#"<Properties><InsetSpacing type="list">{}</InsetSpacing></Properties>"#,+ r#"<ListItem type="unit">V</ListItem>"#.replace('V', &v.to_string()).repeat(4)+ )+ };+ let designmap = format!(+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="20.2" Self="d">+<RootObjectStyleGroup Self="ro">+ <ObjectStyle Self="ObjectStyle/$ID/[None]" Name="$ID/[None]" {none}>+ <TextFramePreference TextColumnCount="1" TextColumnGutter="12" AutoSizingReferencePoint="CenterPoint" AutoSizingType="Off"/>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Rounded" Name="Rounded" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner" TopLeftCornerRadius="6">+ <Properties><BasedOn type="object">ObjectStyle/$ID/[None]</BasedOn></Properties>+ <TextFramePreference TextColumnCount="2" TextColumnGutter="18" VerticalJustification="CenterAlign" FirstBaselineOffset="LeadingOffset" MinimumFirstBaselineOffset="4" IgnoreWrap="true" AutoSizingType="HeightOnly">{inset}</TextFramePreference>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Child" Name="Child" TopRightCornerOption="BevelCorner">+ <Properties><BasedOn type="object">ObjectStyle/Rounded</BasedOn></Properties>+ </ObjectStyle>+</RootObjectStyleGroup>+<Story Self="s1"/>+<Spread Self="sp1"><Page Self="p1"/>+<TextFrame Self="tf" ParentStory="s1" AppliedObjectStyle="ObjectStyle/Child" BottomRightCornerOption="InverseRoundedCorner" BottomRightCornerRadius="11.34">{p0}<TextFramePreference TextColumnCount="3"/></TextFrame>+<Rectangle Self="legacy" AppliedObjectStyle="ObjectStyle/Rounded" CornerOption="BevelCorner" CornerRadius="5" TopLeftCornerOption="InsetCorner">{p1}</Rectangle>+<Rectangle Self="one" TopRightCornerOption="RoundedCorner" TopRightCornerRadius="11.34">{p2}</Rectangle>+<Rectangle Self="plain" AppliedObjectStyle="ObjectStyle/Rounded">{p3}</Rectangle>+</Spread>+</Document>"#,+ none = corners("None", "12"),+ inset = inset(3.0),+ p0 = path(0.0),+ p1 = path(100.0),+ p2 = path(200.0),+ p3 = path(300.0),+ );+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();+ let item = |n: usize| d.spreads[0].items[n].clone();+ // Path order: top-left, bottom-left, bottom-right, top-right.+ let shapes = |n: usize| item(n).corners.corners.map(|c| (c.shape, c.size));+ assert_eq!(shapes(0), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::InverseRounded, 11.34), (C::Bevel, 12.0)]);+ assert_eq!(shapes(1), [(C::Inset, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0)]);+ assert!(item(2).corners.corners.iter().enumerate().all(|(i, c)| (c.shape == C::Rounded) == (i == 3)));+ assert_eq!(item(2).corners.corners[3].size, 11.34);+ assert_eq!(shapes(3), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::Rounded, 12.0), (C::Rounded, 12.0)]);+ let tf = item(0);+ let o = &tf.text_frame().unwrap().options;+ assert_eq!((o.columns, o.gutter, o.inset), (3, 18.0, [3.0; 4]));+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Center, FirstBaseline::Leading, 4.0));+ assert_eq!((o.ignore_wrap, o.auto_size, o.auto_size_ref), (true, AutoSize::HeightOnly, 4));+}diff --cc crates/ui-egui/src/canvas.rsindex 98caa51b0,34dd61442..246061a5f--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -1013,41 -986,8 +1014,17 @@@ fn draw_text_selectionif s > e || (s == e && !(l.range.end < range.end && e == l.range.end)) {continue;}- let quad = |x0: f64, x1: f64| {- [- Point::new(x0, l.baseline - l.ascent),- Point::new(x1, l.baseline - l.ascent),- Point::new(x1, l.baseline + l.descent),- Point::new(x0, l.baseline + l.descent),- ]- };- if l.glyphs.iter().any(|g| g.rtl) {- // Mixed directions: the selected glyphs' boxes, joined where they touch.- let mut spans: Vec<(f64, f64)> =- l.glyphs.iter().filter(|g| g.len > 0 && g.byte >= s && g.byte < e).map(|g| (g.x, g.x + g.adv)).collect();- spans.sort_by(|a, b| a.0.total_cmp(&b.0));- let mut merged: Vec<(f64, f64)> = Vec::new();- for (a, b) in spans {- match merged.last_mut() {- Some(m) if a <= m.1 + 0.5 => m.1 = m.1.max(b),- _ => merged.push((a, b)),- }- }- quads.extend(merged.into_iter().map(|(a, b)| quad(a, b)));- } else {- let x0 = compose::caret_x(l, s);- let x1 = if e == l.range.end && range.end > l.range.end { l.end_x.max(x0 + 3.0) } else { compose::caret_x(l, e) };- quads.push(quad(x0, x1));- }+ let past = e == l.range.end && range.end > l.range.end;+ quads.extend(compose::highlight_quads(l, s, e, past));+ // A selected drop cap is highlighted down to its baseline.+ if let Some(dc) = l.drop_cap {+ let sel = l.glyphs.iter().filter(|g| g.len > 0 && g.byte < dc.end && g.byte >= s && g.byte < e);+ let (a, b) = sel.fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), g| (a.min(g.x), b.max(g.x + g.adv)));+ if a < b {+ let r = dc.rect;+ quads.push([Point::new(a, r.y0), Point::new(b, r.y0), Point::new(b, r.y1), Point::new(a, r.y1)]);+ }+ }for (gi, g) in l.glyphs.iter().enumerate() {if g.visible && g.len > 0 && g.byte >= s && g.byte < e {glyphs.push((li, gi));diff --cc crates/ui-egui/src/control.rsindex d96f17773,33e7c1b97..b8cca617d--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@@ -377,40 -377,101 +392,139 @@@ pub fn save_screenshot(app: &mut Design}}+ /// Parse explicit page indices without treating invalid values as omission.+ pub(crate) fn page_index(p: &Value, default: usize, count: usize) -> Result<usize, String> {+ let page = match p.get("page") {+ None => default,+ Some(v) => v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`page` must be a nonnegative integer representable as a page index")?,+ };+ if page >= count {+ return Err(format!("no page {page} (the document has {count} pages, indices are 0-based)"));+ }+ Ok(page)+ }++ #[cfg(test)]+ mod automation_contract_tests {+ use super::*;+ fn app() -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages":2})).unwrap();+ app+ }+ fn call(app: &mut DesignApp, ctx: &egui::Context, method: &str, params: Value) -> Value {+ let (req, _) = ControlRequest::new(method, params);+ match handle(app, ctx, &req) {+ Outcome::Done(v) => v,+ Outcome::Screenshot { .. } => panic!("unexpected screenshot"),+ }+ }+ fn frame(app: &mut DesignApp, ctx: &egui::Context, events: Vec<egui::Event>) {+ let mut output = ctx.run_ui(+ egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ },+ |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ },+ );+ output.textures_delta.clear();+ }+ #[test]+ fn control_typing_uses_explicit_caret_but_retains_widget_events() {+ let mut app = app();+ let ctx = egui::Context::default();+ assert_eq!(call(&mut app, &ctx, "ui.text", json!({"text":"X"}))["ok"], false);+ let f = app.session.execute("frame.create", &json!({"rect":[36,36,300,200],"content":"text","text":"Hello"})).unwrap();+ app.session.execute("text.select", &json!({"story":f["story"],"anchor":5})).unwrap();+ assert_eq!(app.session.tool_id(), "selection");+ assert_eq!(call(&mut app, &ctx, "ui.text", json!({"text":"X"}))["ok"], true);+ assert_eq!(app.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "HelloX");+ app.session.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(app.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "Hello");+ app.select_tool("type");+ assert!(app.session.wants_text(), "the document would receive ordinary typing without widget focus");+ app.ui.palette = Some(String::new());+ for _ in 0..3 {+ frame(&mut app, &ctx, vec![]);+ }+ assert!(ctx.text_edit_focused());+ assert_eq!(call(&mut app, &ctx, "ui.text", json!({"text":"field"}))["ok"], true);+ let events = std::mem::take(&mut app.synthetic);+ frame(&mut app, &ctx, events);+ assert_eq!(app.ui.palette.as_deref(), Some("field"));+ assert_eq!(app.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "Hello");+ }+ #[test]+ fn control_pages_validate_before_writer_and_preserve_omission() {+ let mut app = app();+ let ctx = egui::Context::default();+ let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let sink = writes.clone();+ app.services.write = Some(Box::new(move |_, bytes| {+ sink.lock().unwrap().push(bytes.to_vec());+ Ok(())+ }));+ app.session.execute("frame.create", &json!({"rect":[36,36,300,200]})).unwrap();+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)));+ crate::canvas::go_to_page(&mut app, 1);+ assert_eq!(crate::canvas::current_page(&app), Some(1));+ for method in ["ui.render", "app.export"] {+ for page in+ [json!(-1), json!(-2), json!(1.5), Value::Null, json!("0"), json!(true), json!(u64::MAX), json!(18446744073709551616_f64), json!(99)]+ {+ assert_eq!(call(&mut app, &ctx, method, json!({"page":page,"path":"unchanged.png","scale":0.1}))["ok"], false, "{method}: {page}");+ assert!(writes.lock().unwrap().is_empty());+ }+ assert_eq!(call(&mut app, &ctx, method, json!({"path":"omitted.png","scale":0.1}))["ok"], true);+ assert_eq!(call(&mut app, &ctx, method, json!({"page":1,"path":"explicit.png","scale":0.1}))["ok"], true);+ let mut bytes = writes.lock().unwrap();+ assert_eq!(bytes.len(), 2);+ assert_eq!(bytes[0], bytes[1]);+ bytes.clear();+ }+ assert!(app.run("app.exportPng", json!({"page":Value::Null,"path":"unchanged.png"})).is_err());+ assert!(writes.lock().unwrap().is_empty());+ }+ }+++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::{+ Arc,+ atomic::{AtomicUsize, Ordering},+ };++ #[test]+ fn control_paste_never_reads_the_system_clipboard() {+ let calls = Arc::new(AtomicUsize::new(0));+ let seen = calls.clone();+ let services = crate::Services {+ clipboard_text: Some(Box::new(move || {+ seen.fetch_add(1, Ordering::SeqCst);+ Some("SECRET".into())+ })),+ ..Default::default()+ };+ let mut app = DesignApp::new(designcraft_engine::Session::new(), services);+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "words"})).unwrap();+ let sid = r["story"].as_u64().unwrap();+ assert!(app.session.active().unwrap().selection.text.is_some(), "the new frame is being typed in");+ let text = |app: &DesignApp| app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text.clone();+ let ctx = egui::Context::default();+ let (req, _rx) = ControlRequest::new("engine.execute", json!({"command": "edit.paste"}));+ let _ = handle(&mut app, &ctx, &req);+ assert_eq!(calls.load(Ordering::SeqCst), 0, "the control channel must not read the system clipboard");+ assert!(!text(&app).contains("SECRET"));+ assert!(!app.in_control);+ // The same command chosen by the user does paste the system clipboard.+ let _ = app.run("edit.paste", json!({}));+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert!(text(&app).contains("SECRET"));+ }+}diff --cc crates/ui-egui/src/dialogs.rsindex 8b4ed1c2a,2ab7a3bad..a3c733c1e--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -1482,9 -1855,53 +1855,53 @@@ pub fn confirm(app: &mut DesignApp) ->}Ok(r)}+ "paragraphRules" => {+ let attrs = rule_edits(&d, "");+ if attrs.is_empty() {+ return Ok(Value::Null);+ }+ app.run("type.para", json!({"attrs": attrs}))+ }+ "characterStyleOptions" => {+ let name = d.s("name");+ let mut chars = Map::new();+ for (k, v) in &d.fields {+ if let Some(a) = k.strip_prefix("c.") {+ chars.insert(a.into(), v.clone());+ }+ }+ let rename = d.s("rename").trim().to_string();+ let based = d.fields.get("basedOn").and_then(Value::as_str).map(str::to_string);+ let r = if d.b("new") {+ // A new style sets only what was filled in.+ chars.retain(|_, v| !v.is_null());+ let mut params = json!({"name": if rename.is_empty() { "Character Style 1" } else { rename.as_str() }, "chars": chars});+ if let Some(b) = based.filter(|b| b != designcraft_doc::NO_CHAR_STYLE) {+ params["basedOn"] = json!(b);+ }+ app.run("style.character.create", params)+ } else {+ let mut params = json!({"name": name, "chars": chars});+ if let Some(b) = based {+ params["basedOn"] = if b == designcraft_doc::NO_CHAR_STYLE { Value::Null } else { json!(b) };+ }+ if !rename.is_empty() && rename != name {+ params["rename"] = json!(rename);+ }+ app.run("style.character.edit", params)+ };+ if let Err(e) = &r {+ // Keep the dialog open with the reason (a taken name, a based-on loop).+ let mut d = d.clone();+ d.fields.insert("status".into(), json!(e));+ d.fields.insert("section".into(), json!("general"));+ app.ui.dialog = Some(d);+ }+ r+ }"colorPicker" => {let hex = d.s("hex");- app.run("object.color", json!({"color": hex, "target": d.s("target")}))+ app.run("object.color", json!({"color": hex, "target": d.s("target"), "text": d.b("text")}))}"layerOptions" => {let hidden: Vec<Value> = d.fields.get("layers").and_then(Value::as_array).map(|a| a.iter().filter(|l| l["visible"] == false).map(|l| l["name"].clone()).collect()).unwrap_or_default();@@@ -1853,22 -2333,19 +2368,29 @@@ fn paragraph_style_options(app: &mut De}let kind = ns["until"]["kind"].as_str().unwrap_or("words").to_string();egui::ComboBox::from_id_salt(("ns_until", i))- .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, &kind)))+ .selected_text(crate::rtl::widget(+ ui,+ if app.ui.language == "uk" {+ format!("{}:", crate::i18n::tr("uk", &kind))+ } else {+ crate::i18n::tr(&app.ui.language, &kind).to_owned()+ },+ )).width(100.0).show_ui(ui, |ui| {- for k in- ["sentences", "words", "characters", "letters", "digits", "tab", "forcedLineBreak", "emSpace", "enSpace", "chars"]- {+ for k in [+ "sentences",+ "words",+ "characters",+ "letters",+ "digits",+ "tab",+ "forcedLineBreak",+ "emSpace",+ "enSpace",+ "dropcap",+ "chars",+ ] {if ui.selectable_label(k == kind, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, k))).clicked() {ns["until"] = if k == "chars" { json!({"kind": "chars", "chars": ":"}) } else { json!({"kind": k}) };changed = true;diff --cc crates/ui-egui/src/lib.rsindex ef1d1622a,fb81e9c34..a727a489c--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -38,11 -38,21 +38,22 @@@ pub use control::{ControlRequest, Contrpub type ReadFn = Box<dyn Fn(&str) -> Result<Vec<u8>, String>>;pub type WriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;pub type PickFn = Box<dyn FnMut(&str) -> Option<String>>;- pub type OpenAsyncFn = Box<dyn FnMut(&str)>;+ /// Context captured before any host file-picker or read await.+ #[derive(Clone, Debug)]+ pub struct ImportRequest {+ pub purpose: String,+ pub target: Option<u64>,+ }+ pub struct ImportedFile {+ pub request: ImportRequest,+ pub name: String,+ pub bytes: Vec<u8>,+ }+ pub type OpenAsyncFn = Box<dyn FnMut(ImportRequest)>;pub type DownloadFn = Box<dyn FnMut(&str, &[u8])>;+pub type ClipboardFn = Box<dyn FnMut() -> Option<String>>;- /// Files `(name, bytes)` delivered asynchronously by the host (web file picker, dropped files).- pub type Inbox = std::sync::Arc<std::sync::Mutex<Vec<(String, Vec<u8>)>>>;+ /// Files delivered asynchronously with their original operation and document identity.+ pub type Inbox = std::sync::Arc<std::sync::Mutex<Vec<ImportedFile>>>;/// Platform services injected by the host (desktop or web).#[derive(Default)]@@@ -59,12 -69,8 +70,11 @@@ pub struct Services/// Hand bytes to the user as a named file (browser download). When set, Save uses it/// instead of writing to a path.pub download: Option<DownloadFn>,- /// Files delivered asynchronously, drained every frame: `.designcraft` → `file.openBytes`,- /// anything else → `file.place`.+ /// Files delivered asynchronously, drained every frame with their captured request context.pub inbox: Option<Inbox>,+ /// The system clipboard's text, for Paste chosen from a menu (egui only delivers it with the+ /// paste keys, which a native menu bar takes first).+ pub clipboard_text: Option<ClipboardFn>,}#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]@@@ -191,11 -243,14 +247,17 @@@ pub struct UiStatepub smart_spacing: bool,#[serde(default = "default_zone")]pub snap_zone: f64,+ /// Tools panel: Formatting Affects Text (J): with text frames selected, colour edits go to+ /// their text instead of the frames.+ pub formatting_affects_text: bool,/// Window > Contextual Task Bar.pub task_bar: bool,+ /// Where the Contextual Task Bar is pinned: its top-left, in points from the canvas's top-left+ /// (`None`: it follows the selection).+ pub task_bar_pin: Option<[f32; 2]>,+ /// Where the Contextual Task Bar was last shown, like [`Self::task_bar_pin`].+ #[serde(skip)]+ pub task_bar_at: Option<[f32; 2]>,/// Help › About DesignCraft is open.pub about: bool,/// The About window's tab: 0 About, 1 Contributors, 2 Models (`about::ABOUT_TABS`).@@@ -270,8 -326,9 +333,10 @@@ impl Default for UiStatesmart_dimensions: true,smart_spacing: true,snap_zone: 4.0,+ formatting_affects_text: false,task_bar: true,+ task_bar_pin: None,+ task_bar_at: None,about: false,about_tab: 0,pending_urls: Vec::new(),diff --cc crates/ui-egui/src/menus.rsindex bfb7625e9,94e5c0971..4a319c4e1--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -2028,31 -2253,97 +2263,122 @@@ mod tests}}+ /// Exercise the real dropdown, including clipping and wheel input, on a short viewport.+ #[test]+ fn oversized_edit_menu_scrolls_to_preferences() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ let ctx = egui::Context::default();+ let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(700.0, 260.0));+ let mut tick = 0;+ let mut frame = |app: &mut DesignApp, events: Vec<egui::Event>| {+ tick += 1;+ let mut output =+ ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(tick as f64 / 60.0), events, ..Default::default() }, |ui| {+ egui::MenuBar::new().ui(ui, |ui| menu_bar(app, ui));+ });+ output.textures_delta.clear();+ let mut labels = Vec::new();+ fn collect(shape: &egui::Shape, clip: egui::Rect, labels: &mut Vec<(String, egui::Rect, egui::Rect)>) {+ match shape {+ egui::Shape::Text(t) => labels.push((t.galley.job.text.clone(), t.visual_bounding_rect(), clip)),+ egui::Shape::Vec(shapes) => {+ for shape in shapes {+ collect(shape, clip, labels);+ }+ }+ _ => {}+ }+ }+ for shape in output.shapes {+ collect(&shape.shape, shape.clip_rect, &mut labels);+ }+ labels+ };+ frame(&mut app, vec![]);+ let labels = frame(&mut app, vec![]);+ let edit = labels.iter().find(|(text, _, _)| text == "Edit").unwrap().1.center();+ for pressed in [true, false] {+ frame(+ &mut app,+ vec![+ egui::Event::PointerMoved(edit),+ egui::Event::PointerButton { pos: edit, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ],+ );+ }+ for _ in 0..3 {+ frame(&mut app, vec![]);+ }+ let layer = ctx.layer_id_at(egui::pos2(edit.x + 80.0, 100.0)).expect("menu layer");+ let bounds = ctx.memory(|m| m.area_rect(layer.id)).expect("menu bounds");+ let track = egui::pos2(bounds.right() - 9.0, bounds.bottom() - 25.0);+ for pressed in [true, false] {+ frame(+ &mut app,+ vec![+ egui::Event::PointerMoved(track),+ egui::Event::PointerButton { pos: track, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ],+ );+ }+ assert!(egui::Popup::is_any_open(&ctx), "clicking the scroll track must not dismiss the menu");+ frame(+ &mut app,+ vec![+ egui::Event::PointerMoved(egui::pos2(edit.x + 80.0, 100.0)),+ egui::Event::MouseWheel {+ unit: egui::MouseWheelUnit::Point,+ delta: egui::vec2(0.0, -3000.0),+ phase: egui::TouchPhase::Move,+ modifiers: egui::Modifiers::NONE,+ },+ ],+ );+ let mut labels = Vec::new();+ for _ in 0..60 {+ labels = frame(&mut app, vec![]);+ }+ let (_, rect, clip) = labels.iter().find(|(text, _, _)| text == "Preferences…").expect("Preferences is rendered");+ assert!(screen.contains_rect(*rect) && clip.contains_rect(*rect), "Preferences must be visible after scrolling: {rect:?}, {clip:?}");+ let pos = rect.center();+ for pressed in [true, false] {+ frame(+ &mut app,+ vec![+ egui::Event::PointerMoved(pos),+ egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE },+ ],+ );+ }+ assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("preferences"));+ assert!(!egui::Popup::is_any_open(&ctx), "choosing a command dismisses the menu");+ }++ #[test]+ fn formatting_affects_text_sends_swatches_to_the_text() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "words", "caret": false})).unwrap();+ let (fid, sid) = (r["id"].as_u64().unwrap(), r["story"].as_u64().unwrap());+ app.run("selection.set", json!({"ids": [fid]})).unwrap();+ let text_fill = |app: &crate::DesignApp| {+ let st = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().clone();+ st.char_format_at(2).over.fill.clone()+ };+ let frame_fill = |app: &crate::DesignApp| app.session.active().unwrap().doc.item(designcraft_doc::ItemId(fid)).unwrap().fill.swatch.clone();+ assert!(!crate::panels::colors_affect_text(&app));+ crate::panels::apply_swatch(&mut app, false, "Cyan", None).unwrap();+ assert_eq!(frame_fill(&app), "Cyan");+ assert_eq!(text_fill(&app), None);+ let r = run_ui(&mut app, "app.formattingAffectsText", &json!({})).unwrap().unwrap();+ assert_eq!(r["on"], true, "toggles on");+ assert!(crate::panels::colors_affect_text(&app));+ crate::panels::apply_swatch(&mut app, false, "Magenta", Some(0.5)).unwrap();+ assert_eq!(frame_fill(&app), "Cyan", "the frame is left alone");+ assert_eq!(text_fill(&app).as_deref(), Some("Magenta"));+ assert_eq!(crate::panels::color_target(&mut app).map(|t| (t.0, t.1)), Some(("Magenta".to_string(), 0.5)));+ }+#[test]fn transform_menu_items_open_their_dialogs() {for id in ["transform.move", "transform.scale", "transform.rotate", "transform.shear"] {