DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge feat/paragraph-settings-full: paragraph borders, shading, span space and list levels in the model, layout, IDML and dialogs
aiongg0ebe1212f02d
diff --cc ROADMAP.mdindex 5eeace4ea,a9d976c30..7a0ad5b7b--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -54,10 -26,10 +54,11 @@@ DesignCraft aims at full Adobe InDesig- EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`).- Data Merge (one linked CSV, TSV, text, or Excel file; text, image, QR, and hyperlink placeholders; preview; a new document with one record per page or records tiled on a single page), spell checking (public-domain Moby list + document dictionary, suggestions), Step and Repeat (count or grid), snippets, object styles, Numbering & Section Options.- Footnotes: Type › Insert Footnote (caret moves into the note), Document Footnote Options (numbering style incl. symbols, start/restart per page/spread/section, prefix/suffix, reference position/character style, paragraph style, separator, spacing, first baseline, rule above); notes composed at the bottom of the referencing column with the body text making room; edited in place on the canvas; rendered, exported to PDF (real text) and IDML (InDesign's structure, verified opening in InDesign 2026) and imported from IDML; `footnote.*` commands.+- IDML1: embedded text frames and groups retain forward story references in body text, footnotes and table cells; anonymous composed stories retain anchored artwork for screen/PDF rendering. Filled compound outlines retain open contours; object-only inline lines use geometric extents, preflight distinguishes unplaced stories and locates embedded overflow at its page frame, and cyclic frame references are rejected.- Tabs panel (Type › Tabs, ⇧⌘T): alignment buttons, X, Leader and Align On fields, a ruler to add, move and delete stops and drag the first-line, left and right indents, Clear All, Delete Tab, Repeat Tab and Reset Indents; it opens over the selected text frame with its ruler on the text column. Paragraph Style Options › Tabs edits a style's stops. Commands: `type.tabs.get`, `type.tabs.add`, `type.tabs.move`, `type.tabs.change`, `type.tabs.remove`, `type.tabs.clear`, `type.tabs.repeat` (with `style` for a paragraph style).- Paragraph Rules: Rule Above / Rule Below (on, weight, colour, tint, column or text width, offset, left/right indent) set in Type › Paragraph Rules…, the Paragraph panel menu and Paragraph Style Options › Paragraph Rules; inherited style values shown, and `type.para` / `style.paragraph.edit` change only the rule fields named.- - Paragraph Style Options lists its sections in InDesign's order. Advanced Character Formats, OpenType Features, Underline Options and Strikethrough Options are the Character Style Options sections; Paragraph Border and Paragraph Shading (on, colour, tint, per-side offsets and border weights), Keep Options (keep with next, keep lines together, start paragraph), Span Columns (single, span, split with gutters) and Bullets and Numbering (list type, bullet and text after, list, format, number, Start At or Continue from Previous Number, label indents) edit the existing paragraph attributes.+ - Paragraph Style Options lists its sections in InDesign's order. Advanced Character Formats, OpenType Features, Underline Options and Strikethrough Options are the Character Style Options sections; Paragraph Border and Paragraph Shading (on, colour, tint, per-side offsets and border weights), Keep Options (keep with next, keep lines together, start paragraph), Span Columns (single, span, split with gutters, least space before and after the span or split) and Bullets and Numbering (list type and level, bullet with a glyph grid to pick it from, bullet font, text after, list, format, number, Start At or Continue from Previous Number, Restart Numbers at This Level After, the label's character style, alignment, indents and tab position) edit the paragraph attributes; the same sections open for the selected paragraphs from the Paragraph panel menu (Paragraph Borders and Shading…, Span Columns…, Bullets and Numbering…).+ - Lists have levels 1–9: each level numbers on its own and restarts after a higher level (any, or a given one), `^1`…`^9` in the number text are the levels' current numbers, and named lists keep their levels across stories. A bullet or number is left-aligned at the first line's start, centred on it or ends at it; the tab position is a stop for the text after it. Span and split paragraphs keep at least their space before and after from the column text. All of these round-trip through IDML (`NumberingLevel`, `NumberingRestartPolicies`, `BulletsCharacterStyle`, `NumberingCharacterStyle`, `BulletsAlignment`, `NumberingAlignment`, `BulletsFont`, `SpanColumnMinSpaceBefore`/`After`); the tab position is not written to IDML.- Cross-references and text anchors: Insert Cross-Reference (paragraph by style, or text anchor), 11 formats with InDesign's building blocks (full/partial paragraph, paragraph text/number, page number, anchor name, chapter, file name) plus user formats; resolved live at composition — never out of date, no Update step; unresolved destinations show `??`; PDF link annotations to the destination page; IDML export/import as InDesign cross-reference sources, hyperlinks, text destinations and formats (verified in InDesign 2026); `xref.*` / `anchor.*` commands.- Index: page references (topic from the selection or up to 4 levels, sort keys; current page, to end of story, next n paragraphs, suppressed, See / See also), Generate / Update Index (section headings, nested or run-in, page ranges merged, Index Title / Section Head / Level 1–4 styles); IDML export/import as InDesign topics, page references and topic cross-references (verified in InDesign 2026); `index.*` commands.- Text clipboard keeps formatting (character/paragraph formats, footnotes, cross-references, index markers, tables) and falls back to plain text when the system clipboard changed; Paste without Formatting (⇧⌘V); Change Case (UPPERCASE, lowercase, Title Case, Sentence case — formatting kept); Type › Insert Special Character / White Space / Break Character submenus.@@@ -100,10 -71,9 +101,10 @@@- Appearance of Black complete: Printing/Exporting rich black for RGB output (PNG), Overprint [Black] Swatch at 100% (document, IDML OverprintBlack).- Hyperlinks and Bookmarks panels (Window ▸ Interactive): new from the selection, edit (`hyperlink.edit`), go to source (`hyperlink.goToSource`), rename bookmarks (`bookmark.rename`), go to page, delete.- Nested line styles (`nestedLineStyles` paragraph attribute, Paragraph Style Options › Drop Caps and Nested Styles, IDML AllNestedLineStyles): the first lines restyle until the line breaks settle.+- Drop caps (`type.para {dropCapLines, dropCapChars, dropCapStyle, dropCapAlignLeft, dropCapScaleDescenders}`, Paragraph panel, Paragraph Style Options › Drop Caps and Nested Styles; IDML DropCapLines/DropCapCharacters/DropcapDetail, the drop cap style as the leading "through 1 Dropcap" nested style): the first characters (code points, as InDesign counts them, never splitting a letter from its combining marks; up to 150) are enlarged from the first line's cap height down N − 1 leadings of the text after them (up to 25 lines; grid steps on a baseline grid), the lines beside them are indented by their advance (on the right in right-to-left paragraphs), spaces right after them are set at their size without widening the indent, baselines don't move; a one-line drop cap keeps a smaller size of its own and sets its tabs at the paragraph's tab stops; Align Left Edge (on by default) moves the drop cap left by its first letter's side bearing so its ink starts at the indent; Scale for Descenders is kept but doesn't change the layout yet; a drop cap character style, and nested styles through the drop cap (Dropcap delimiter). Drawn on screen and in PDF (text in order), with caret, hit testing and selection over the enlarged letters. Vertical text sets no drop caps.- User dictionary hyphenation exceptions (`hyphenation.addException/removeException/list`, Edit ▸ Spelling ▸ User Dictionary): `ex~am~ple` breaks only at `~`, a plain word never hyphenates.- Frame Fitting Options (`object.fittingOptions`, Object ▸ Fitting ▸ Frame Fitting Options…): Auto-Fit refits on resize, fitting, Align From reference point, crop amounts; IDML FrameFittingOption.- - Paragraph borders (per-side weights, colour, tint, offsets) and shading offsets, drawn per column part of split paragraphs (also when overset); Paragraph panel controls; IDML ParagraphBorder*/ParagraphShading*Offset.+ - Paragraph borders and shading, drawn per column part of split paragraphs (also when overset) once the lines are in place: border per-side weights, stroke type (built-in types and the document's stroke styles), cap, join, colour, tint, gap colour and tint, corner size and shape per corner, per-side offsets, column or text width, top edge (ascent, baseline, em box, leading) and bottom edge (descent, baseline, em box), a closed box in each part of a split paragraph when asked, and one box for consecutive paragraphs with the same settings; shading has the same corners, offsets, edges and width, Clip to Frame, and Do not Print or Export (shown on screen only). Paragraph Borders and Shading… dialog (Paragraph panel menu, Type menu); IDML ParagraphBorder*/ParagraphShading*/MergeConsecutiveParaBorders.- Font menu: search, favourites (stars, Show Favorites Only; `favoriteFonts` preference) and each family previewed in its own face. Western (and other-script) families come first, then Japanese, Simplified Chinese, Traditional Chinese and Korean ones, each group alphabetical and set off by a separator; the group comes from the font's own data (`meta` languages, family names in a CJK language, OS/2 code pages, else what it covers), read once (installed fonts by the font scan, without loading them). CJK families show their native names, the English name on hover; Preferences › Type › Show Font Names in English (`showFontNamesInEnglish`) shows English names throughout. Search matches either name; documents store the English name. Every family list (Character panel, Control bar, Properties, style dialogs, Find Font, Glyphs) follows this order.- Application preferences (engine `Prefs`) now persist across launches (desktop: prefs.json beside ui.json).- View ▸ Fit Selection in Window (⌥⌘=) and Find/Change ▸ Object (`find.objects`, `find.changeObjects`: by fill, stroke, weight, opacity, kind, layer, label).diff --cc crates/compose/src/lib.rsindex 8f30ec0bd,1c9a225a8..1d51b3435--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -13,11 -13,10 +13,12 @@@mod bidi;pub mod breaker;mod cache;+pub mod grep;pub mod hyphen;+mod mojikumi;mod notes;mod overlay;+ mod parabox;mod ruby;pub mod shape;pub mod table;@@@ -31,8 -30,8 +32,8 @@@ use std::rc::Rcuse std::sync::{Arc, Mutex};use designcraft_doc::{- Align, Document, FirstBaseline, GridAlign, ItemId, ParaProps, SpanColumns, StartParagraph, Story, StoryId, TabAlign, TextFrameOptions,- VerticalJustification, WrapMode, story,- Align, Composer, Document, FirstBaseline, GridAlign, ItemId, ListAlign, ListCounter, ParaProps, SpanColumns, StartParagraph, Story, StoryId,- TabAlign, TextFrameOptions, VerticalJustification, WrapMode, story,++ Align, Document, FirstBaseline, GridAlign, ItemId, ListAlign, ListCounter, ParaProps, SpanColumns, StartParagraph, Story, StoryId, TabAlign,++ TextFrameOptions, VerticalJustification, WrapMode, story,};use designcraft_fonts::{FontDb, ScopedFonts};use designcraft_geom::{Point, Rect};@@@ -40,9 -39,10 +41,10 @@@use crate::breaker::{Break, Spacing};pub use crate::cache::Cache;use crate::notes::Notes;-pub use crate::notes::{find_note, hit_note, note_caret};+pub use crate::notes::{find_note, hit_note, hit_note_with, note_caret};+ use crate::parabox::ParaBox;use crate::shape::{Glyph, StyleTable, SubstCtx};-pub use crate::table::{PlacedCell, StrokeSeg, TableFrag, cell_caret, find_cell, hit_cell};+pub use crate::table::{PlacedCell, StrokeSeg, TableFrag, cell_caret, find_cell, hit_cell, hit_cell_with};/// Character appearance shared by many glyphs (indexed from [`PlacedGlyph::style`]).#[derive(Clone, Debug, PartialEq)]@@@ -201,24 -199,11 +203,25 @@@ pub struct Linepub hj: u8,/// The paragraph's Keep Options couldn't be honoured here (Highlight Keep Violations).pub keep_violation: bool,+ /// The drop cap a paragraph's first line starts with (its first glyphs, set down to a later+ /// line's baseline).+ pub drop_cap: Option<DropCapBox>,+}++/// Where a drop cap sits (frame inner space).+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct DropCapBox {+ /// Story bytes from its line's start up to here are the drop cap's.+ pub end: usize,+ /// Its baseline.+ pub baseline: f64,+ /// The area it covers: from its line's top down to the text below its baseline.+ pub rect: Rect,}- /// A paragraph rule or shading rectangle in frame inner space.- #[derive(Clone, Debug, PartialEq)]+ /// A paragraph rule, border or shading in frame inner space: `rect` filled, or `path` (non-zero+ /// winding) when it has one, with `rect` its bounds.+ #[derive(Clone, Debug, Default, PartialEq)]pub struct Deco {pub rect: Rect,pub color: String,@@@ -805,26 -755,38 +813,47 @@@ fn compose_with_db(doc: &Document, storNone}};- if let Some(label) = list_label {- let n = prepend_label(db, &mut sp.glyphs, &label, prange.start, &base_chars, label_env, &mut table);+ // The label's glyphs at the paragraph start, and how many of them (up to its first tab)+ // the list alignment places.+ let mut label_aligned = 0usize;+ let mut label_tab = false;+ if let Some(label) = &list_label {+ let chars = label_chars(doc, &pp, &base_chars);- let before = sp.glyphs.len();- prepend_label(db, &mut sp.glyphs, label, prange.start, &chars, label_env, &mut table);- let n = sp.glyphs.len().saturating_sub(before);++ let n = prepend_label(db, &mut sp.glyphs, label, prange.start, &chars, label_env, &mut table);+ for g in sp.glyphs.iter_mut().take(n) {+ g.list_label = true;+ }+ label_aligned = sp.glyphs.get(..n).unwrap_or_default().iter().position(|g| g.ch == '\t').unwrap_or(n);+ label_tab = label_aligned < n;+ // Tab Position: a stop for the text after the label.+ if let Some(t) = pp.list_tab.filter(|t| t.is_finite() && *t >= 0.0)+ && !pp.tabs.iter().any(|s| (s.position - t).abs() < 1e-6)+ {+ pp.tabs.push(designcraft_doc::TabStop { position: t, align: TabAlign::Left, leader: String::new(), align_on: String::new() });+ pp.tabs.sort_by(|a, b| a.position.total_cmp(&b.position));+ }}if pi == 0&& let Some(label) = &opts.label{prepend_label(db, &mut sp.glyphs, label, prange.start, &base_chars, label_env, &mut table);+ label_aligned = 0;}+ let list_align = match pp.list_type {+ _ if label_aligned == 0 || pp.direction == designcraft_doc::TextDirection::RightToLeft => designcraft_doc::ListAlign::Left,+ designcraft_doc::ListType::Bullets => pp.bullet_align,+ _ => pp.number_align,+ };+ boxes[pi] = ParaBox::of(doc, &pp);let mut glyphs = sp.glyphs;+ if !pp.composer.japanese() {+ // Every IDML's root style carries a leading model and character alignment, which only+ // the Japanese composers use.+ for g in &mut glyphs {+ g.leading_model = designcraft_doc::cjk::LeadingModel::Roman;+ g.character_alignment = designcraft_doc::cjk::CharacterAlignment::Baseline;+ }+ }let bidi_text = bidi::paragraph_text(&mut glyphs, &story.text);let bidi_info = unicode_bidi::BidiInfo::new(&bidi_text,@@@ -882,8 -837,10 +911,10 @@@next_column(&mut cur);}if cur.last_baseline.is_some() {- begin_at(&mut cur, pp.start_paragraph);+ go(&mut cur, pp.start_paragraph);}+ // Text in the columns above a spanning paragraph, or a split block starting below text.+ let mut text_above = cur.split.is_none() && split_cfg.is_some();if spanning && cur.fi < frames.len() {// Close the band: the paragraph goes below the deepest of its columns, which are// balanced first.@@@ -1154,30 -1070,9 +1184,31 @@@let forced_mid = brk == Some(story::FORCED_LINE_BREAK) && !last;let (mut placed, end_x, ratio) =layout_line(&glyphs, s, e, b.hyphen, lx0, lx1, col.x0, &pp, &spacing, ends_para, forced_mid, f.left_page, &bidi_info);+ let end_x = if line_no == 0 && s == 0 { align_label(&mut placed, label_aligned, label_tab, list_align, end_x) } else { end_x };- // Warichu runs before ruby so a reading is placed over the stacked note.+ // 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);@@@ -1296,11 -1180,14 +1327,15 @@@.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));+ 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 });+ 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,++ color,++ tint,+ ..Deco::default()+ });}}- para_box_decos(&mut out, pi, &pp);if pp.rule_below.on&& let Some(ft) = out.frames.get_mut(cur.fi.min(frames.len().saturating_sub(1)))&& let Some(l) = ft.lines.iter().rev().find(|l| l.para == pi)@@@ -1308,49 -1195,12 +1343,8 @@@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,- ..Deco::default()- });+ 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;- }- }++ ft.decos.push(Deco { rect: Rect::new(x0 + r.left_indent, y, x1 - r.right_indent, y + r.weight), color, tint, ..Deco::default() });}// 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.@@@ -2973,147 -2639,43 +2926,184 @@@ fn place(g: &Glyph, x: f64) -> PlacedGl}}+/// Drop caps are at most this many lines and characters (larger values are capped).+pub const MAX_DROP_CAP_LINES: u32 = 25;+pub const MAX_DROP_CAP_CHARS: u32 = 150;++/// Byte where paragraph `prange`'s drop cap ends: after its first `drop_cap_chars` characters+/// (code points, as InDesign counts them, spaces included), extended to the end of the grapheme+/// cluster they end in so a letter keeps its combining marks; all of them in a shorter paragraph.+/// `prange.start` when it has none: no lines or characters, or vertical text (which sets no drop+/// caps).+fn drop_cap_end(text: &str, prange: Range<usize>, pp: &ParaProps, vertical: bool) -> usize {+ use unicode_segmentation::UnicodeSegmentation as _;+ if vertical || pp.drop_cap_lines == 0 || pp.drop_cap_chars == 0 {+ return prange.start;+ }+ let Some(para) = text.get(prange.clone()) else { return prange.start };+ let para = para.trim_end_matches('\n');+ let n = pp.drop_cap_chars.min(MAX_DROP_CAP_CHARS) as usize;+ let end = para.char_indices().nth(n).map_or(para.len(), |(i, _)| i);+ prange.start + para.grapheme_indices(true).map(|(i, _)| i).find(|i| *i >= end).unwrap_or(para.len())+}++/// A paragraph's drop cap: its first glyphs, enlarged to reach down `lines` lines.+struct DropCap {+ glyphs: Vec<Glyph>,+ /// Story byte it ends at.+ end: usize,+ lines: usize,+ /// Its advance.+ width: f64,+ /// How far its origin sits left of the indent: its first letter's left side bearing with+ /// Align Left Edge, else 0.+ lsb: f64,+ /// Its baseline below the first line's: `lines − 1` leadings of the text after it (grid steps+ /// on a baseline grid), wherever line `lines` is set.+ drop: f64,+}++/// Take the drop cap (the glyphs before byte `end`) off the front of a paragraph's glyphs and scale+/// it so its cap height reaches from the first line's cap height down to line `lines`' baseline,+/// measured in the leading and cap height of the text after it. A one-line drop cap keeps its own+/// size when that is smaller. On a baseline grid of increment `grid`, lines are that many grid+/// steps apart. With `align_left` its ink starts at the indent (see [`DropCap::lsb`]). Tabs inside+/// it advance to the stops of `tabs` (stops and the start-side indent; in right-to-left paragraphs+/// both measured from the column's right edge). Spaces right after it join it at its size without+/// widening it.+#[allow(clippy::too_many_arguments)]+fn split_drop_cap(+ db: &ScopedFonts<'_>,+ glyphs: &mut Vec<Glyph>,+ end: usize,+ lines: u32,+ base_leading: f64,+ base_cap: f64,+ grid: Option<f64>,+ align_left: bool,+ tabs: (&[designcraft_doc::TabStop], f64),+) -> Option<DropCap> {+ let n = glyphs.iter().take_while(|g| g.byte < end).count();+ if n == 0 {+ return None;+ }+ let lines = lines.clamp(1, MAX_DROP_CAP_LINES) as usize;+ let mut dc: Vec<Glyph> = glyphs.drain(..n).collect();+ let spaces = glyphs.iter().take_while(|g| g.is_space()).count();+ let mut after: Vec<Glyph> = glyphs.drain(..spaces).collect();+ let end = after.last().map_or(end, |g| g.byte.saturating_add(g.len).max(end));+ let body = glyphs.iter().find(|g| g.len > 0 && g.cap > 0.0);+ let (lead, cap) = body.map_or((base_leading, base_cap), |g| (g.leading, g.cap));+ let lead = match grid.map(|inc| (lead / inc - 1e-6).ceil().max(1.0) * inc) {+ Some(pitch) if pitch.is_finite() && pitch > 0.0 => pitch,+ _ => lead,+ };+ let drop = (lines - 1) as f64 * lead;+ let own = dc.iter().map(|g| g.cap).fold(0.0, f64::max);+ let k = if own > 0.0 { (drop + cap) / own } else { 1.0 };+ let k = if lines == 1 { k.min(1.0) } else { k };+ let k = if k.is_finite() && k > 0.0 { k.min(1000.0) } else { 1.0 };+ for g in dc.iter_mut().chain(after.iter_mut()) {+ g.adv *= k;+ g.dx *= k;+ g.dy *= k;+ g.sx *= k;+ g.sy *= k;+ g.ascent *= k;+ g.typo_ascent *= k;+ g.descent *= k;+ g.cap *= k;+ g.xh *= k;+ g.size *= k;+ g.space *= k;+ }+ let lsb = match dc.first() {+ Some(g) if align_left => {+ let ink = designcraft_geom::Shape::bounding_box(&*db.outline(g.face.get(), g.gid));+ let lsb = g.dx + ink.x0 * g.sx;+ if ink.width() > 0.0 && lsb.is_finite() { lsb } else { 0.0 }+ }+ _ => 0.0,+ };+ // Tabs advance to the paragraph's stops, measured from the column's start edge. Right to left,+ // its glyphs run from that (right) edge in this order (see `place_drop_cap`).+ let (stops, indent) = tabs;+ let mut x = indent - lsb;+ for i in 0..dc.len() {+ let tab = match dc.get(i) {+ Some(g) if g.ch == '\t' => Some(tab_advance(stops, indent, x, dc.get(i + 1..).unwrap_or_default()).0),+ _ => None,+ };+ if let (Some(w), Some(g)) = (tab, dc.get_mut(i)) {+ g.adv = w;+ }+ x += dc.get(i).map_or(0.0, |g| g.adv);+ }+ let width = dc.iter().map(|g| g.adv).sum();+ dc.append(&mut after);+ Some(DropCap { glyphs: dc, end, lines, width, drop, lsb })+}++impl DropCap {+ /// How far the lines beside it are indented: to the end of its advance.+ fn indent(&self) -> f64 {+ self.width - self.lsb+ }+}++/// The drop cap's glyphs set from `at` (right to left: mirrored, its first character on the right).+fn place_drop_cap(dc: &DropCap, at: f64, rtl: bool) -> Vec<PlacedGlyph> {+ let mut x = at;+ let mut out = Vec::with_capacity(dc.glyphs.len());+ for g in &dc.glyphs {+ let pen = if rtl { at + at + dc.width - x - g.adv } else { x };+ let mut p = place(g, pen);+ p.y += dc.drop;+ p.rtl = rtl;+ out.push(p);+ x += g.adv;+ }+ out+}++ /// The character attributes of a list label: the paragraph's, under the bullet's or number's+ /// character style, in the bullet font.+ fn label_chars(doc: &Document, pp: &ParaProps, base: &designcraft_doc::CharProps) -> designcraft_doc::CharProps {+ let bullets = pp.list_type == designcraft_doc::ListType::Bullets;+ let style = if bullets { &pp.bullet_char_style } else { &pp.number_char_style };+ let mut cp = if style.is_empty() || style == designcraft_doc::NO_CHAR_STYLE {+ base.clone()+ } else {+ doc.styles.resolve_char(base, &designcraft_doc::CharFormat { style: style.clone(), over: Default::default() })+ };+ if bullets && !pp.bullet_font.is_empty() {+ cp.font_family = pp.bullet_font.clone();+ if !pp.bullet_font_style.is_empty() {+ cp.font_style = pp.bullet_font_style.clone();+ }+ }+ cp+ }++ /// List alignment on a paragraph's first line: the label's first `n` glyphs (its text before the+ /// tab) are centred on or end at the line start. Text after the label's tab stays at its stop;+ /// without a tab the whole line moves with the label. Returns the line's end x.+ fn align_label(placed: &mut [PlacedGlyph], n: usize, tab: bool, align: ListAlign, end_x: f64) -> f64 {+ let Some(label) = placed.get(..n).filter(|l| l.iter().all(|g| g.len == 0)) else { return end_x };+ let w: f64 = label.iter().map(|g| g.adv).sum();+ let dx = match align {+ ListAlign::Left => return end_x,+ ListAlign::Center => -w / 2.0,+ ListAlign::Right => -w,+ };+ let moved = if tab { n } else { placed.len() };+ for g in placed.iter_mut().take(moved) {+ g.x += dx;+ }+ if tab { end_x } else { end_x + dx }+ }++/// Put generated `label` text before the paragraph's glyphs; returns how many glyphs it added.fn prepend_label(db: &ScopedFonts<'_>,glyphs: &mut Vec<Glyph>,diff --cc crates/compose/src/tests.rsindex aa40fb438,fdb76eaa6..073e0be0f--- a/crates/compose/src/tests.rs+++ b/crates/compose/src/tests.rs@@@ -4757,100 -2772,190 +4757,288 @@@ fn empty_paragraphs_get_no_bullet_or_nu}}+#[test]+fn tight_word_spacing_does_not_isolate_a_word() {+ // A narrow word-spacing range (100–105%) with some letter spacing and glyph scaling, no+ // hyphenation: lines that need more stretch must open their word spaces, not letter-space a+ // single word across the measure.+ let para = ParaAttrs {+ align: Some(Align::LeftJustified),+ hyphenate: Some(false),+ first_line_indent: Some(9.0),+ word_space_min: Some(1.0),+ word_space_desired: Some(1.03),+ word_space_max: Some(1.05),+ letter_space_min: Some(-0.05),+ letter_space_max: Some(0.05),+ glyph_scale_min: Some(0.99),+ glyph_scale_max: Some(1.01),+ ..Default::default()+ };+ // Short words: any two fit on a line together.+ let text = CORPUS[..2].join(" ");+ for w in (200..=320).step_by(5) {+ let (d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, w as f64, 20000.0), para.clone());+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ for l in &lines[..lines.len() - 1] {+ let words = text[l.range.clone()].split_whitespace().count();+ assert!(words > 1, "width {w}: a single-word line {:?}", &text[l.range.clone()]);+ }+ }+}++#[test]+fn fixed_width_spaces_do_not_stretch_on_justified_lines() {+ // Long words in a narrow column: lines stretch past the maximum word spacing. Only the word+ // spaces take that stretch; em, en and thin spaces keep their width.+ let words = ["characteristically", "misunderstanding", "unquestionably", "responsibility", "administration", "photographer"];+ let seps = [" ", "\u{2003}", " ", "\u{2002}", " ", "\u{2009}"];+ let text: String = (0..60).map(|i| format!("{}{}", words[i % words.len()], seps[i % seps.len()])).collect();+ let text = text.trim_end().to_string();+ let fixed = |c: char| matches!(c, '\u{2003}' | '\u{2002}' | '\u{2009}');+ // (character, advance) of each fixed space, per line, and whether the line ends the paragraph.+ let spaces = |align: Align, w: f64| -> Vec<(Vec<(char, f64)>, bool)> {+ let para = ParaAttrs { align: Some(align), hyphenate: Some(false), ..Default::default() };+ let (d, sid, _) = doc_with(&text, Rect::new(0.0, 0.0, w, 20000.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ all_lines(&cs)+ .iter()+ .map(|l| {+ let found = l.glyphs.iter().filter_map(|g| text[g.byte..].chars().next().filter(|&c| fixed(c)).map(|c| (c, g.adv))).collect();+ (found, l.last_in_para)+ })+ .collect()+ };+ let mut checked = 0;+ for w in [190.0, 230.0, 270.0] {+ let natural: Vec<(char, f64)> = spaces(Align::Left, w).into_iter().flat_map(|l| l.0).collect();+ for (found, last) in spaces(Align::LeftJustified, w) {+ if last {+ continue;+ }+ for (c, a) in found {+ let Some(&(_, n)) = natural.iter().find(|x| x.0 == c) else { continue };+ assert!((a - n).abs() < 1e-6, "width {w}: U+{:04X} is {a:.2} wide, not {n:.2}", c as u32);+ checked += 1;+ }+ }+ }+ assert!(checked > 5, "{checked} fixed spaces on justified lines");+}++#[test]+fn grep_style_in_the_documents_dialect_keeps_short_words_with_the_next() {+ // `\l` (lowercase letter) and `\h` (horizontal space) aren't Rust regex syntax; the style used+ // to be skipped silently.+ let text = "Мы и он в доме и в саду, а она у окна и с книгой в руках у стола.";+ let para = ParaAttrs {+ align: Some(Align::Left),+ grep_styles: Some(vec![designcraft_doc::GrepStyle { style: "nobreak".into(), pattern: r"\b\l{1,2}\h".into() }]),+ ..Default::default()+ };+ let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 70.0, 1000.0), para);+ let chars = designcraft_doc::CharAttrs { no_break: Some(true), ..Default::default() };+ std::sync::Arc::make_mut(&mut d.styles).character.push(designcraft_doc::CharacterStyle {+ name: "nobreak".into(),+ based_on: None,+ chars,+ shortcut: String::new(),+ });+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let lines = all_lines(&cs);+ assert!(lines.len() > 3);+ let short = |w: &str| w.chars().count() <= 2 && w.chars().all(char::is_lowercase);+ for l in &lines[..lines.len() - 1] {+ let last = text[l.range.clone()].split_whitespace().last().unwrap_or("");+ assert!(!short(last), "line ends with a short word: {:?}", &text[l.range.clone()]);+ }+}+++ // ---------- paragraph border and shading ----------++ fn bordered(text: &str, rect: Rect, para: ParaAttrs) -> ComposedStory {+ let para = ParaAttrs { border_on: Some(true), border_weights: Some([1.0; 4]), ..para };+ let (d, sid, _) = doc_with(text, rect, para);+ compose_story(&d, sid, &ComposeOptions::default())+ }++ fn has_curves(bp: &designcraft_geom::BezPath) -> bool {+ bp.elements().iter().any(|e| matches!(e, designcraft_geom::PathEl::CurveTo(..) | designcraft_geom::PathEl::QuadTo(..)))+ }++ #[test]+ fn rounded_border_corners_are_curves_and_dotted_borders_paint_their_gap_first() {+ use designcraft_geom::corners::{Corner, CornerShape};+ let rounded = [Corner { shape: CornerShape::Rounded, size: 6.0 }; 4];+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs { border_corners: Some(rounded), ..Default::default() });+ let paths: Vec<_> = cs.frames[0].decos.iter().filter_map(|dc| dc.path.as_ref()).collect();+ assert_eq!(paths.len(), 1, "one stroked outline");+ assert!(has_curves(paths[0]));+ // Square corners: plain edges, no curves.+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), ParaAttrs::default());+ assert!(cs.frames[0].decos.iter().all(|dc| dc.path.is_none()));+ // A dotted border with a gap colour: the gap under the dots.+ let dotted = ParaAttrs { border_type: Some(designcraft_doc::StrokeType::Dotted), border_gap_color: Some("[Paper]".into()), ..Default::default() };+ let cs = bordered("Boxed text", Rect::new(0.0, 0.0, 300.0, 200.0), dotted);+ let colors: Vec<&str> = cs.frames[0].decos.iter().filter(|dc| dc.path.is_some()).map(|dc| dc.color.as_str()).collect();+ assert_eq!(colors, ["[Paper]", "[Black]"]);+ }++ /// The width of the widest border edge (the top and bottom edges span the box).+ fn border_width(cs: &ComposedStory) -> f64 {+ cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect.width()).fold(0.0, f64::max)+ }++ #[test]+ fn a_text_width_border_is_narrower_than_a_column_width_one() {+ let rect = Rect::new(0.0, 0.0, 300.0, 200.0);+ let column = border_width(&bordered("Short", rect, ParaAttrs::default()));+ let text = border_width(&bordered("Short", rect, ParaAttrs { border_width: Some(designcraft_doc::BoxWidth::Text), ..Default::default() }));+ assert!((column - 302.0).abs() < 1e-6, "column and both side strokes: {column}");+ assert!(text > 2.0 && text < 60.0, "text: {text}");+ }++ /// Edges of a plain border by frame column: (column, count).+ fn edges_per_column(cs: &ComposedStory) -> Vec<usize> {+ let cols = &cs.frames[0].columns;+ cols.iter()+ .map(|c| {+ cs.frames[0].decos.iter().filter(|dc| dc.color == "[Black]" && dc.rect.center().x > c.x0 - 2.0 && dc.rect.center().x < c.x1 + 2.0).count()+ })+ .collect()+ }++ #[test]+ fn a_split_paragraph_closes_its_border_in_each_column_only_when_set_to() {+ let text = format!("{LOREM} {LOREM}");+ let compose = |display: bool| {+ let para = ParaAttrs { border_on: Some(true), border_weights: Some([1.0; 4]), border_display_if_splits: Some(display), ..Default::default() };+ let (mut d, sid, fid) = doc_with(&text, Rect::new(0.0, 0.0, 400.0, 90.0), para);+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.columns = 2;+ compose_story(&d, sid, &ComposeOptions::default())+ };+ let open = compose(false);+ assert!(open.frames[0].lines.iter().any(|l| l.column == 1), "the paragraph reaches the second column");+ // Open at the split: top and sides in the first column, sides and bottom in the second.+ assert_eq!(edges_per_column(&open), [3, 3]);+ assert_eq!(edges_per_column(&compose(true)), [4, 4]);+ }++ #[test]+ fn consecutive_paragraphs_with_the_same_border_share_one_box() {+ let compose = |merge: bool| {+ let para = ParaAttrs { space_after: Some(10.0), border_merge: Some(merge), ..Default::default() };+ bordered("One\nTwo\nThree", Rect::new(0.0, 0.0, 300.0, 300.0), para)+ };+ let merged = compose(true);+ let edges: Vec<Rect> = merged.frames[0].decos.iter().filter(|dc| dc.color == "[Black]").map(|dc| dc.rect).collect();+ assert_eq!(edges.len(), 4, "one box: {edges:?}");+ let lines = &merged.frames[0].lines;+ let (first, last) = (&lines[0], &lines[lines.len() - 1]);+ let left = edges.iter().find(|r| r.height() > r.width()).unwrap();+ assert!((left.y0 - (first.baseline - first.ascent)).abs() < 1e-6 && (left.y1 - (last.baseline + last.descent)).abs() < 1e-6, "{left:?}");+ assert_eq!(compose(false).frames[0].decos.iter().filter(|dc| dc.color == "[Black]").count(), 12, "a box each");+ }++ #[test]+ fn shading_clips_to_the_frame_and_can_stay_off_print() {+ let para = ParaAttrs {+ shading_on: Some(true),+ shading_offsets: Some([50.0; 4]),+ shading_clip: Some(true),+ shading_nonprinting: Some(true),+ ..Default::default()+ };+ let (d, sid, _) = doc_with("Shaded", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let area = cs.frames[0].columns[0];+ let shade = &cs.frames[0].decos[0];+ assert!(shade.nonprinting);+ assert!(shade.rect.x0 >= area.x0 - 1e-6 && shade.rect.y0 >= area.y0 - 1e-6 && shade.rect.x1 <= area.x1 + 1e-6, "{:?} in {area:?}", shade.rect);+ }++ // ---------- span space, bullets and numbering ----------++ #[test]+ fn space_before_and_after_a_span_moves_the_span_and_the_text_below() {+ let at = |before: f64, after: f64| {+ let (mut d, sid, _, h) = span_doc(1, 1, Rect::new(0.0, 0.0, 600.0, 800.0));+ let p = &mut d.story_mut(sid).unwrap().paras[h].para;+ p.span_space_before = Some(before);+ p.span_space_after = Some(after);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let first = |pi: usize| cs.frames[0].lines.iter().find(|l| l.para == pi).map(|l| l.baseline).unwrap();+ (first(h), first(h + 1))+ };+ let (span0, below0) = at(0.0, 0.0);+ let (span1, below1) = at(24.0, 0.0);+ assert!((span1 - span0 - 24.0).abs() < 0.01, "{span0} → {span1}");+ assert!((below1 - below0 - 24.0).abs() < 0.01, "the text below moves with it");+ let (span2, below2) = at(0.0, 18.0);+ assert!((span2 - span0).abs() < 0.01 && (below2 - below0 - 18.0).abs() < 0.01, "{below0} → {below2}");+ }++ /// The first line of each paragraph.+ fn first_lines(cs: &ComposedStory) -> Vec<&Line> {+ all_lines(cs).into_iter().filter(|l| l.first_in_para).collect()+ }++ #[test]+ fn a_right_aligned_number_ends_at_the_line_start() {+ use designcraft_doc::{ListAlign, ListType};+ let compose = |align: ListAlign| {+ let para = ParaAttrs {+ list_type: Some(ListType::Numbers),+ number_align: Some(align),+ left_indent: Some(36.0),+ first_line_indent: Some(-18.0),+ ..Default::default()+ };+ let (d, sid, _) = doc_with("Item", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ compose_story(&d, sid, &ComposeOptions::default())+ };+ // The label "1.\t": its first two glyphs are the number and the full stop.+ let cs = compose(ListAlign::Left);+ let col = cs.frames[0].columns[0];+ let l = first_lines(&cs)[0];+ assert!((l.glyphs[0].x - (col.x0 + 18.0)).abs() < 0.01, "left: starts at the line start");+ let text_x = l.glyphs.iter().find(|g| g.len > 0).unwrap().x;+ let cs = compose(ListAlign::Right);+ let l = first_lines(&cs)[0];+ let end = l.glyphs[1].x + l.glyphs[1].adv;+ assert!((end - (col.x0 + 18.0)).abs() < 0.01, "right: ends at the line start ({end})");+ assert!((l.glyphs.iter().find(|g| g.len > 0).unwrap().x - text_x).abs() < 0.01, "the text stays at the tab stop");+ }++ #[test]+ fn level_two_numbering_restarts_after_level_one() {+ let para = numbered(designcraft_doc::NumberStyle::Arabic, "^1.^#");+ let (mut d, sid, _) = doc_with("A\nB\nC\nD\nE", Rect::new(0.0, 0.0, 300.0, 300.0), para);+ for (p, level) in d.story_mut(sid).unwrap().paras.iter_mut().zip([1, 2, 2, 1, 2]) {+ p.para.list_level = Some(level);+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ // `^1` is level 1's number, `^#` the paragraph's own level.+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.1", "1.1", "1.2", "2.2", "2.1"]);+ // Without the restart, level 2 carries on.+ for p in &mut d.story_mut(sid).unwrap().paras {+ p.para.restart_numbers = Some(false);+ }+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ assert_eq!(list_labels(&cs, LABEL_CHARS), ["1.1", "1.1", "1.2", "2.2", "2.3"]);+ }++ #[test]+ fn the_tab_position_places_the_text_after_the_label() {+ use designcraft_doc::ListType;+ let compose = |tab: Option<f64>| {+ let para = ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(tab), ..Default::default() };+ let (d, sid, _) = doc_with("Item", Rect::new(0.0, 0.0, 300.0, 200.0), para);+ let cs = compose_story(&d, sid, &ComposeOptions::default());+ let col = cs.frames[0].columns[0];+ first_lines(&cs)[0].glyphs.iter().find(|g| g.len > 0).unwrap().x - col.x0+ };+ assert!((compose(Some(50.0)) - 50.0).abs() < 0.01);+ assert!((compose(None) - 36.0).abs() < 0.01, "the default tab stop");+ }diff --cc crates/geom/src/corners.rsindex bcbdf9005,e5d39a3d3..846010e41--- a/crates/geom/src/corners.rs+++ b/crates/geom/src/corners.rs@@@ -185,32 -243,24 +243,50 @@@ mod testsassert!((a - std::f64::consts::PI * 100.0).abs() < 1.0, "{a}");}+ /// InDesign draws a 28.35 pt radius on a 51.02 pt tall frame as 25.51 (half the shorter side),+ /// as a circular arc (handles 0.5523 × the radius).+ #[test]+ fn radius_is_clamped_to_half_the_shorter_side() {+ let r = rectangle(Rect::new(0.0, 0.0, 200.0, 51.02));+ let bp = apply(&r, &CornerOptions::uniform(CornerShape::Rounded, 28.35));+ let half = 51.02 / 2.0;+ let mut arcs = 0;+ let mut last = Point::ZERO;+ for el in bp.elements() {+ match *el {+ kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => last = p,+ kurbo::PathEl::CurveTo(c1, c2, p) => {+ assert!(((p - last).x.abs() - half).abs() < 1e-9 && ((p - last).y.abs() - half).abs() < 1e-9, "{last:?} → {p:?}");+ assert!(((c1 - last).hypot() - half * crate::shapes::KAPPA).abs() < 1e-9);+ assert!(((c2 - p).hypot() - half * crate::shapes::KAPPA).abs() < 1e-9);+ arcs += 1;+ last = p;+ }+ _ => {}+ }+ }+ assert_eq!(arcs, 4);+ assert!((crate::shapes::KAPPA - 0.5523).abs() < 1e-4);+ }++ #[test]+ fn box_outline_rounds_only_closed_corners() {+ let r = Rect::new(0.0, 0.0, 100.0, 50.0);+ let round = [Corner { shape: CornerShape::Rounded, size: 10.0 }; 4];+ let closed = box_outline(r, &round, [true; 4]);+ let curves = |bp: &BezPath| bp.elements().iter().filter(|e| matches!(e, kurbo::PathEl::CurveTo(..))).count();+ assert_eq!(curves(&closed), 4);+ assert!((closed.area().abs() - (5000.0 - (400.0 - std::f64::consts::PI * 100.0))).abs() < 1.0);+ // Open at the top: the two bottom corners are rounded, the top ends are square.+ let open = box_outline(r, &round, [false, true, true, true]);+ assert_eq!(curves(&open), 2);+ assert!(!open.elements().iter().any(|e| matches!(e, kurbo::PathEl::ClosePath)));+ // Open at both ends: two separate sides.+ let sides = box_outline(r, &round, [false, true, false, true]);+ assert_eq!(sides.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(), 2);+ assert_eq!(curves(&sides), 0);+ }+#[test]fn size_is_clamped_to_half_edge() {let r = rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));diff --cc crates/idml/src/export.rsindex 84fd9af8a,050e2bebd..054bd184d--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@@ -863,8 -859,12 +863,13 @@@ impl<'a> Ex<'a>}(ps.para.clone(), ps.chars.clone())};- let parent = match ps.based_on.as_deref() {+ let parent = (ps.name != designcraft_doc::NO_PARA_STYLE).then(|| ps.based_on.as_deref().unwrap_or(designcraft_doc::NO_PARA_STYLE));++ let parent_props = match ps.based_on.as_deref() {+ Some(b) if ps.name != designcraft_doc::NO_PARA_STYLE => styles.resolve_para_style(b).0,+ _ => designcraft_doc::ParaProps::default(),+ };- let pa = with_list_tab(pa, || (styles.resolve_para_style(&ps.name).0, parent));- self.para_attrs(&mut el, &mut props, &pa);++ let pa = with_list_tab(pa, || (styles.resolve_para_style(&ps.name).0, parent_props));+ self.para_attrs(&mut el, &mut props, &pa, parent);self.char_attrs(&mut el, &mut props, &ca);pg.insert(&ps.name, with_props(el, props));}@@@ -2467,7 -2474,9 +2546,9 @@@fn psr_el(&mut self, pf: &ParaFormat) -> El {let mut el = El::new("ParagraphStyleRange").attr("AppliedParagraphStyle", names::style_self("ParagraphStyle", PARA_BUILTINS, &pf.style));let mut props = Vec::new();- self.para_attrs(&mut el, &mut props, &pf.para, Some(&pf.style));+ let styles = &self.d.styles;+ let pa = with_list_tab(pf.para.clone(), || (styles.resolve_para(pf).0, styles.resolve_para_style(&pf.style).0));- self.para_attrs(&mut el, &mut props, &pa);++ self.para_attrs(&mut el, &mut props, &pa, Some(&pf.style));self.char_attrs(&mut el, &mut props, &pf.chars);with_props(el, props)}diff --cc crates/idml/src/import.rsindex a983992f4,851a7ce60..96ee4c111--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -228,12 -168,26 +228,29 @@@ fn parse_point(s: Option<&str>) -> Opti(v.len() >= 2).then(|| Point::new(v[0], v[1]))}-/// IDML tint (percent, `-1` = default) → 0..1.+/// InDesign's corner size where a file gives a corner shape without one.+const INDESIGN_CORNER_SIZE: f64 = 12.0;++ /// The four corners of a paragraph border or shading (`prefix` `ParagraphBorder` /+ /// `ParagraphShading`): top left, top right, bottom right, bottom left. Unset when none is given.+ fn corners(e: &El, prefix: &str) -> Option<[Corner; 4]> {+ let keys = ["TopLeft", "TopRight", "BottomRight", "BottomLeft"];+ let shapes = keys.map(|n| e.prop(&format!("{prefix}{n}CornerOption")));+ let sizes = keys.map(|n| e.num(&format!("{prefix}{n}CornerRadius")));+ if shapes.iter().all(Option::is_none) && sizes.iter().all(Option::is_none) {+ return None;+ }+ let mut out = [Corner::default(); 4];+ for (c, (shape, size)) in out.iter_mut().zip(shapes.iter().zip(sizes)) {+ c.shape = shape.as_deref().map_or(designcraft_geom::corners::CornerShape::None, |s| names::corner_in(s.trim()));+ c.size = size.filter(|v| v.is_finite()).map_or(12.0, |v| v.max(0.0));+ }+ Some(out)+ }++/// IDML tint (percent; `-1` = the colour's own tint, 100 %) → 0..1.fn tint(v: Option<f64>) -> Option<f32> {- v.map(|t| if t < 0.0 { 1.0 } else { (t / 100.0) as f32 })+ v.map(|t| if t < 0.0 || t.is_nan() { 1.0 } else { (t / 100.0).min(1.0) as f32 })}impl<'r> Importer<'r> {diff --cc crates/idml/src/tests.rsindex b980671b4,4361221e6..0e3eb993e--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -2225,40 -1461,40 +2286,78 @@@ fn list_numbering_format_expression_andcheck(&import_idml(&export_idml(&d)).unwrap());}+/// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is+/// set in that family instead of counting as a missing font drawn in the fallback.+#[test]+fn applied_font_with_an_id_prefix_names_the_family() {+ let styles = STYLES.replace(">Source Serif 4</AppliedFont>", ">$ID/Source Serif 4</AppliedFont>");+ let story = STORY.replace(+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14">"#,+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14"><Properties><AppliedFont type="string">$ID/Source Serif 4</AppliedFont></Properties>"#,+ );+ let bytes = zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", &styles),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", &story),+ ]);+ let d = import_idml_with(&bytes, &|_| None).unwrap();+ let fonts: Vec<&str> = d.styles.paragraph.iter().filter_map(|s| s.chars.font_family.as_deref()).collect();+ assert!(!fonts.is_empty() && fonts.iter().all(|f| *f == "Source Serif 4"), "{fonts:?}");+ let (sid, story) = d.stories.iter().next().unwrap();+ let bold = story.runs().find(|(r, _)| story.text[r.clone()].starts_with("bold")).unwrap().1;+ assert_eq!(bold.over.font_family.as_deref(), Some("Source Serif 4"));+ // The bundled family draws the text (an unknown family would fall back to Source Sans 3).+ let cs = designcraft_compose::compose_story(&d, *sid, &Default::default());+ let first_para = story.text.find('\n').unwrap();+ let families: Vec<&str> = cs+ .frames+ .iter()+ .flat_map(|f| &f.lines)+ .flat_map(|l| &l.glyphs)+ .filter(|g| g.visible && g.len > 0 && g.byte < first_para)+ .map(|g| g.face.get().family.as_str())+ .collect();+ assert!(!families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"), "{families:?}");+}+++ #[test]+ fn list_tab_position_round_trips_as_a_tab_stop() {+ use designcraft_doc::{ListType, ParaAttrs, ParagraphStyle, TabAlign, TabStop};+ let stop = |position, align| TabStop { position, align, leader: String::new(), align_on: String::new() };+ let mut d = Document::new(&NewDocument::default());+ std::sync::Arc::make_mut(&mut d.styles).paragraph.push(ParagraphStyle {+ name: "List".into(),+ based_on: None,+ next_style: None,+ para: ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(Some(24.0)), ..Default::default() },+ chars: CharAttrs::default(),+ shortcut: String::new(),+ });+ let local = ParaAttrs {+ list_type: Some(ListType::Bullets),+ list_tab: Some(Some(36.0)),+ tabs: Some(vec![stop(100.0, TabAlign::Right)]),+ ..Default::default()+ };+ let ended = ParaAttrs { list_type: Some(ListType::None), ..Default::default() };+ let lid = d.default_layer();+ for (i, (text, style, para)) in+ [("Local\tx", "", local), ("Styled\ty", "List", ParaAttrs::default()), ("Ended\tz", "List", ended)].into_iter().enumerate()+ {+ let pf = ParaFormat { style: if style.is_empty() { ParaFormat::default().style } else { style.into() }, para, ..Default::default() };+ let y = 40.0 + 100.0 * i as f64;+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, y, 300.0, y + 80.0), lid, text, pf).unwrap();+ }+ let back = import_idml(&export_idml(&d)).unwrap();+ let tabs = |prefix: &str| {+ let s = back.stories.values().find(|s| s.text.starts_with(prefix)).unwrap();+ back.styles.resolve_para(&s.paras[0]).0.tabs+ };+ assert_eq!(tabs("Local"), vec![stop(36.0, TabAlign::Left), stop(100.0, TabAlign::Right)]);+ assert_eq!(tabs("Styled"), vec![stop(24.0, TabAlign::Left)]);+ assert_eq!(tabs("Ended"), vec![], "a paragraph that ends the list has no list tab stop");+ }diff --cc crates/ui-egui/src/dialogs.rsindex 347013aab,e3d9df68c..74b65673a--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -1131,14 -1127,19 +1131,22 @@@ pub fn show(app: &mut DesignApp, ctx: &"insertTable" => crate::i18n::tr(&app.ui.language, "Create Table"),"textFrameOptions" => crate::i18n::tr(&app.ui.language, "Text Frame Options"),"documentSetup" => crate::i18n::tr(&app.ui.language, "Document Setup"),+ "numberingSection" => crate::i18n::tr(&app.ui.language, "Numbering & Section Options…").trim_end_matches('…'),"findChange" => crate::i18n::tr(&app.ui.language, "Find/Change"),"paragraphStyleOptions" => crate::i18n::tr(&app.ui.language, "Paragraph Style Options"),+ "deleteParagraphStyle" => crate::i18n::tr(&app.ui.language, "Delete Paragraph Style"),"characterStyleOptions" => crate::i18n::tr(&app.ui.language, "Character Style Options"),+ "deleteCharacterStyle" => crate::i18n::tr(&app.ui.language, "Delete Character Style"),"footnoteOptions" => crate::i18n::tr(&app.ui.language, "Footnote Options"),"paragraphRules" => crate::i18n::tr(&app.ui.language, "Paragraph Rules"),+ "paragraphLocal" => crate::i18n::tr(+ &app.ui.language,+ match d.s("section").as_str() {+ "span" => "Span Columns",+ "bullets" => "Bullets and Numbering",+ _ => "Paragraph Borders and Shading",+ },+ ),"insertXref" => crate::i18n::tr(&app.ui.language, "New Cross-Reference"),"findFont" => crate::i18n::tr(&app.ui.language, "Find/Replace Font"),"polygonSettings" => crate::i18n::tr(&app.ui.language, "Polygon Settings"),@@@ -1849,14 -1864,13 +1858,21 @@@ pub fn confirm(app: &mut DesignApp) ->}Ok(r)}+ "deleteParagraphStyle" => {+ let name = d.s("name");+ let replace = d.s("replaceWith");+ app.run(+ "style.paragraph.delete",+ json!({"name": name, "replaceWith": if replace.is_empty() { json!(designcraft_doc::BASIC_PARAGRAPH) } else { json!(replace) }}),+ )+ }+ "paragraphLocal" => {+ let attrs: Map<String, Value> = d.fields.iter().filter_map(|(k, v)| k.strip_prefix("p.").map(|a| (a.to_string(), v.clone()))).collect();+ if attrs.is_empty() {+ return Ok(Value::Null);+ }+ app.run("type.para", json!({"attrs": attrs}))+ }"paragraphRules" => {let attrs = rule_edits(&d, "");if attrs.is_empty() {@@@ -3206,6 -3431,38 +3541,37 @@@ fn bullets_and_numbering(lang: &str, ui});}+ /// Paragraph Borders and Shading, Span Columns, and Bullets and Numbering for the selected+ /// paragraphs: the Paragraph Style Options sections over the paragraphs' attributes (`current`);+ /// OK applies the edits (`p.<key>`) as local formatting.+ fn paragraph_local(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) {+ let Some(doc) = app.session.active().map(|s| s.doc.clone()) else { return };+ let pv = d.fields.get("current").cloned().unwrap_or_default();+ let lang = app.ui.language.clone();+ ui.set_min_width(480.0);+ match d.s("section").as_str() {+ "span" => span_columns(&lang, ui, d, &pv, &doc),+ "bullets" => {+ let (char_styles, families, fonts, scope) = ListUi::new_parts(app);+ let (family, style) = (d.s("family"), d.s("style"));+ let lu = ListUi { char_styles: &char_styles, families: &families, fonts: &fonts, scope, family: &family, style: &style };+ bullets_and_numbering(&lang, ui, d, &pv, &doc, &lu);+ }+ section => {+ let border = section != "shading";+ ui.horizontal(|ui| {+ for (tab, label) in [("border", "Border"), ("shading", "Shading")] {+ if ui.selectable_label(section == tab, crate::rtl::widget(ui, crate::i18n::tr(&lang, label))).clicked() {+ d.fields.insert("section".into(), json!(tab));+ }+ }+ });+ ui.separator();+ border_shading(&lang, ui, d, &pv, &doc, border);+ }+ }+ }+-/// The section list on the left of the style options dialogs.fn section_list(lang: &str, ui: &mut egui::Ui, d: &mut Dialog, sections: &[(&str, &str)]) {ui.vertical(|ui| {ui.set_width(170.0);diff --cc crates/ui-egui/src/i18n.rsindex 00d478e7c,acb0ec593..c1afd8610--- a/crates/ui-egui/src/i18n.rs+++ b/crates/ui-egui/src/i18n.rs@@@ -3060,7 -2892,101 +3060,100 @@@ const TABLE: &[(&str, [&str; 5])] = &("Numbers", ["Nummerierung", "Numéros", "Números", "自動番号", "编号"]),("Bullet Character:", ["Aufzählungszeichen:", "Caractère de puce:", "Carácter de viñeta:", "箇条書き記号:", "项目符号字符:"]),("Text After:", ["Text danach:", "Texte après:", "Texto después:", "後続テキスト:", "后续文本:"]),+ ("Gap Tint:", ["Lückenfarbton:", "Teinte de l'espace:", "Matiz del hueco:", "すき間の濃淡:", "间隙色调:"]),+ (+ "Corner Size and Shape",+ ["Eckengröße und -form", "Taille et forme des angles", "Tamaño y forma de esquinas", "角のサイズとシェイプ", "角大小和形状"],+ ),+ ("Top Left:", ["Oben links:", "En haut à gauche:", "Superior izquierda:", "左上:", "左上:"]),+ ("Top Right:", ["Oben rechts:", "En haut à droite:", "Superior derecha:", "右上:", "右上:"]),+ ("Bottom Right:", ["Unten rechts:", "En bas à droite:", "Inferior derecha:", "右下:", "右下:"]),+ ("Bottom Left:", ["Unten links:", "En bas à gauche:", "Inferior izquierda:", "左下:", "左下:"]),+ ("Rounded", ["Abgerundet", "Arrondi", "Redondeado", "角丸", "圆角"]),+ ("Inverse Rounded", ["Umgekehrt abgerundet", "Arrondi inversé", "Redondeado inverso", "逆角丸", "反向圆角"]),+ ("Inset", ["Eingezogen", "En retrait", "Hundido", "内側に切り欠き", "内凹"]),+ ("Fancy", ["Verziert", "Fantaisie", "Decorativo", "装飾", "花式"]),+ ("Top Edge:", ["Obere Kante:", "Bord supérieur:", "Borde superior:", "上端:", "上边缘:"]),+ ("Bottom Edge:", ["Untere Kante:", "Bord inférieur:", "Borde inferior:", "下端:", "下边缘:"]),+ ("Em Box Top", ["Geviert oben", "Haut du cadratin", "Parte superior del cuadratín", "仮想ボディの上", "全角框顶部"]),+ ("Descent", ["Unterlänge", "Jambage inférieur", "Descendente", "ディセント", "下伸部"]),+ ("Em Box Bottom", ["Geviert unten", "Bas du cadratin", "Parte inferior del cuadratín", "仮想ボディの下", "全角框底部"]),+ (+ "Display Border if Paragraph Splits Across Frames/Columns",+ [+ "Rahmen anzeigen, wenn der Absatz auf Rahmen/Spalten verteilt ist",+ "Afficher le contour si le paragraphe est réparti sur plusieurs blocs/colonnes",+ "Mostrar borde si el párrafo se divide entre marcos/columnas",+ "段落がフレームや段をまたぐときに囲み罫を表示",+ "段落跨框架/栏拆分时显示边框",+ ],+ ),+ (+ "Merge Consecutive Borders and Shading",+ [+ "Aufeinanderfolgende Rahmen und Schattierungen zusammenführen",+ "Fusionner les contours et trames consécutifs",+ "Combinar bordes y sombreados consecutivos",+ "連続する囲み罫と背景色を結合",+ "合并连续的边框和底纹",+ ],+ ),+ ("Clip to Frame", ["Auf Rahmen beschneiden", "Découper selon le bloc", "Recortar al marco", "フレームでクリップ", "剪切到框架"]),+ (+ "Do not Print or Export",+ ["Nicht drucken oder exportieren", "Ne pas imprimer ni exporter", "No imprimir ni exportar", "印刷・書き出ししない", "不打印或导出"],+ ),+ ("Space Before Span:", ["Abstand vor Überspannung:", "Espace avant l'étendue:", "Espacio antes de abarcar:", "段抜き前のアキ:", "跨栏前间距:"]),+ (+ "Space After Span:",+ ["Abstand nach Überspannung:", "Espace après l'étendue:", "Espacio después de abarcar:", "段抜き後のアキ:", "跨栏后间距:"],+ ),+ ("Space Before Split:", ["Abstand vor Teilung:", "Espace avant la division:", "Espacio antes de dividir:", "段分割前のアキ:", "拆分前间距:"]),+ ("Space After Split:", ["Abstand nach Teilung:", "Espace après la division:", "Espacio después de dividir:", "段分割後のアキ:", "拆分后间距:"]),+ ("Level:", ["Ebene:", "Niveau:", "Nivel:", "レベル:", "级别:"]),+ ("Glyphs…", ["Glyphen…", "Glyphes…", "Glifos…", "字形…", "字形…"]),+ ("(Paragraph Font)", ["(Absatzschrift)", "(Police du paragraphe)", "(Fuente del párrafo)", "(段落のフォント)", "(段落字体)"]),+ (+ "Restart Numbers at This Level After:",+ [+ "Nummerierung auf dieser Ebene neu beginnen nach:",+ "Recommencer la numérotation à ce niveau après:",+ "Reiniciar números en este nivel después de:",+ "このレベルの番号を振り直すきっかけ:",+ "在此级别后重新编号:",+ ],+ ),+ (+ "Any Previous Level",+ ["Einer beliebigen höheren Ebene", "Tout niveau précédent", "Cualquier nivel anterior", "任意の上位レベル", "任何上一级别"],+ ),+ ("Tab Position:", ["Tabulatorposition:", "Position de la tabulation:", "Posición de tabulación:", "タブ位置:", "制表符位置:"]),+ (+ "Paragraph Borders and Shading…",+ [+ "Absatzrahmen und -schattierung…",+ "Contours et trames de paragraphe…",+ "Bordes y sombreado de párrafo…",+ "段落囲み罫と段落背景色…",+ "段落边框和底纹…",+ ],+ ),+ (+ "Paragraph Borders and Shading",+ [+ "Absatzrahmen und -schattierung",+ "Contours et trames de paragraphe",+ "Bordes y sombreado de párrafo",+ "段落囲み罫と段落背景色",+ "段落边框和底纹",+ ],+ ),+ ("Span Columns…", ["Spalten überspannen…", "Étendre sur les colonnes…", "Abarcar columnas…", "段抜きと段分割…", "跨栏…"]),+ (+ "Bullets and Numbering…",+ ["Aufzählungszeichen und Nummerierung…", "Puces et numérotation…", "Viñetas y numeración…", "箇条書き記号と番号付け…", "项目符号和编号…"],+ ),("List:", ["Liste:", "Liste:", "Lista:", "リスト:", "列表:"]),- ("[Default]", ["[Standard]", "[Par défaut]", "[Predeterminado]", "[デフォルト]", "[默认]"]),("Number:", ["Zahl:", "Numéro:", "Número:", "番号:", "编号:"]),("Mode:", ["Modus:", "Mode:", "Modo:", "モード:", "模式:"]),(diff --cc crates/ui-egui/src/i18n/it.rsindex eed3a7a8e,b82b7b615..c2197c375--- a/crates/ui-egui/src/i18n/it.rs+++ b/crates/ui-egui/src/i18n/it.rs@@@ -1579,7 -1536,41 +1579,40 @@@ pub(super) const TABLE: &[(&str, &str)("Numbers", "Numeri"),("Bullet Character:", "Carattere punto elenco:"),("Text After:", "Testo dopo:"),+ ("Gap Tint:", "Tinta spazio:"),+ ("Corner Size and Shape", "Dimensione e forma angoli"),+ ("Top Left:", "In alto a sinistra:"),+ ("Top Right:", "In alto a destra:"),+ ("Bottom Right:", "In basso a destra:"),+ ("Bottom Left:", "In basso a sinistra:"),+ ("Rounded", "Arrotondato"),+ ("Inverse Rounded", "Arrotondato inverso"),+ ("Inset", "Rientrato"),+ ("Fancy", "Decorativo"),+ ("Top Edge:", "Bordo superiore:"),+ ("Bottom Edge:", "Bordo inferiore:"),+ ("Em Box Top", "Parte superiore del quadratone"),+ ("Descent", "Discendente"),+ ("Em Box Bottom", "Parte inferiore del quadratone"),+ ("Display Border if Paragraph Splits Across Frames/Columns", "Mostra bordo se il paragrafo si divide tra cornici/colonne"),+ ("Merge Consecutive Borders and Shading", "Unisci bordi e ombreggiature consecutivi"),+ ("Clip to Frame", "Ritaglia alla cornice"),+ ("Do not Print or Export", "Non stampare né esportare"),+ ("Space Before Span:", "Spazio prima dell'estensione:"),+ ("Space After Span:", "Spazio dopo l'estensione:"),+ ("Space Before Split:", "Spazio prima della divisione:"),+ ("Space After Split:", "Spazio dopo la divisione:"),+ ("Level:", "Livello:"),+ ("Glyphs…", "Glifi…"),+ ("(Paragraph Font)", "(Font del paragrafo)"),+ ("Restart Numbers at This Level After:", "Riavvia numerazione a questo livello dopo:"),+ ("Any Previous Level", "Qualsiasi livello precedente"),+ ("Tab Position:", "Posizione tabulazione:"),+ ("Paragraph Borders and Shading…", "Bordi e ombreggiatura paragrafo…"),+ ("Paragraph Borders and Shading", "Bordi e ombreggiatura paragrafo"),+ ("Span Columns…", "Estendi su colonne…"),+ ("Bullets and Numbering…", "Elenchi puntati e numerati…"),("List:", "Elenco:"),- ("[Default]", "[Predefinito]"),("Number:", "Numero:"),("Mode:", "Modalità:"),("Continue from Previous Number", "Continua dal numero precedente"),diff --cc crates/ui-egui/src/i18n/ja.rsindex 68d53b3b3,30d3b1145..f46032566--- a/crates/ui-egui/src/i18n/ja.rs+++ b/crates/ui-egui/src/i18n/ja.rs@@@ -1740,7 -1697,42 +1740,41 @@@ pub(super) const TABLE: &[(&str, &str)("Numbers", "自動番号"),("Bullet Character:", "箇条書き記号:"),("Text After:", "後続テキスト:"),+ ("Gap Tint:", "すき間の濃淡:"),+ ("Corner Size and Shape", "角のサイズとシェイプ"),+ ("Top Left:", "左上:"),+ ("Top Right:", "右上:"),+ ("Bottom Right:", "右下:"),+ ("Bottom Left:", "左下:"),+ ("Rounded", "角丸"),+ ("Inverse Rounded", "逆角丸"),+ ("Inset", "内側に切り欠き"),+ ("Fancy", "装飾"),+ ("Top Edge:", "上端:"),+ ("Bottom Edge:", "下端:"),+ ("Em Box Top", "仮想ボディの上"),+ ("Descent", "ディセント"),+ ("Em Box Bottom", "仮想ボディの下"),+ ("Display Border if Paragraph Splits Across Frames/Columns", "段落がフレームや段をまたぐときに囲み罫を表示"),+ ("Merge Consecutive Borders and Shading", "連続する囲み罫と背景色を結合"),+ ("Clip to Frame", "フレームでクリップ"),+ ("Do not Print or Export", "印刷・書き出ししない"),+ ("Space Before Span:", "段抜き前のアキ:"),+ ("Space After Span:", "段抜き後のアキ:"),+ ("Space Before Split:", "段分割前のアキ:"),+ ("Space After Split:", "段分割後のアキ:"),+ ("Level:", "レベル:"),+ ("Glyphs…", "字形…"),+ ("(Paragraph Font)", "(段落のフォント)"),+ ("Restart Numbers at This Level After:", "このレベルの番号を振り直すきっかけ:"),+ ("Any Previous Level", "任意の上位レベル"),+ ("Tab Position:", "タブ位置:"),+ ("Paragraph Borders and Shading…", "段落囲み罫と段落背景色…"),+ ("Paragraph Borders and Shading", "段落囲み罫と段落背景色"),+ ("Span Columns…", "段抜きと段分割…"),+ ("Bullets and Numbering…", "箇条書き記号と番号付け…"),+ ("Tint:", "濃淡:"),("List:", "リスト:"),- ("[Default]", "[デフォルト]"),("Number:", "番号:"),("Mode:", "モード:"),("Continue from Previous Number", "前の番号から継続"),diff --cc crates/ui-egui/src/panels/glyphs.rsindex 63f02e9ac,d72ffd2d2..d30359543--- a/crates/ui-egui/src/panels/glyphs.rs+++ b/crates/ui-egui/src/panels/glyphs.rs@@@ -71,10 -63,53 +63,56 @@@ pub fn show(app: &mut DesignApp, ui: &m}});}+ let (picked, count) = grid(ui, &db, scope, &st.family, &st.style, &q, 320.0);+ insert = insert.or(picked);+ if let Some(c) = insert {+ match app.run("text.insert", json!({"text": c.to_string(), "raw": true})) {+ Ok(_) => {+ st.recent.retain(|x| *x != c);+ st.recent.insert(0, c);+ st.recent.truncate(12);+ }+ Err(e) => app.status(format!("Glyphs: {e}")),+ }+ }+ crate::rtl::label(+ ui,+ egui::RichText::new(+ crate::i18n::tr(&app.ui.language, "{count} glyphs — click to insert at the text cursor").replace("{count}", &count.to_string()),+ )+ .size(10.5)+ .color(t.text_dim),+ );+ ui.data_mut(|d| d.insert_temp(id, st));+ }++ /// The characters of font `family` `style` in a grid (those matching `query`, a character or+ /// U+code, when it isn't empty), at most `max_height` tall and scrolling: the character clicked,+ /// and how many are shown.+ pub fn grid(+ ui: &mut egui::Ui,+ db: &designcraft_fonts::ScopedFonts<'_>,+ scope: u32,+ family: &str,+ style: &str,+ query: &str,+ max_height: f32,+ ) -> (Option<char>, usize) {+ let t = Tokens::get(ui.ctx());+ let face = db.face(family, style);+ let q = query.trim();+ let code = q.strip_prefix("U+").or_else(|| q.strip_prefix("u+")).and_then(|h| u32::from_str_radix(h, 16).ok());+ let mut chars: Vec<char> = face.chars().into_iter().map(|(c, _)| c).filter(|c| !c.is_control()).collect();+ chars.sort();+ chars.dedup();+ if !q.is_empty() {+ chars.retain(|c| Some(*c as u32) == code || q.contains(*c) || format!("{:04X}", *c as u32).contains(&q.to_ascii_uppercase()));+ }+ chars.truncate(MAX);- let cols = ((ui.available_width() / CELL).floor() as u32).max(1);+ // The scroll bar floats over the grid's right edge: leave it room.+ let scroll = &ui.spacing().scroll;+ let bar = scroll.bar_inner_margin + scroll.bar_width + scroll.bar_outer_margin;+ let cols = (((ui.available_width() - bar) / CELL).floor() as u32).max(1);let ppp = ui.ctx().pixels_per_point();let cell_px = (CELL * ppp).round() as u32;let ink = t.text_strong;@@@ -118,70 -154,8 +157,52 @@@if resp.clicked()&& let Some(c) = resp.interact_pointer_pos().and_then(cell_at){- insert = Some(c);+ picked = Some(c);}});- if let Some(c) = insert {- match app.run("text.insert", json!({"text": c.to_string(), "raw": true})) {- Ok(_) => {- st.recent.retain(|x| *x != c);- st.recent.insert(0, c);- st.recent.truncate(12);- }- Err(e) => app.status(format!("Glyphs: {e}")),- }- }- crate::rtl::label(- ui,- egui::RichText::new(- crate::i18n::tr(&app.ui.language, "{count} glyphs — click to insert at the text cursor").replace("{count}", &chars.len().to_string()),- )- .size(10.5)- .color(t.text_dim),- );- ui.data_mut(|d| d.insert_temp(id, st));+ (picked, chars.len())}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_grid_leaves_room_for_the_scroll_bar() {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({})).unwrap();+ let ctx = egui::Context::default();+ crate::theme::install_fonts(&ctx, "");+ crate::theme::apply(&ctx, &Tokens::for_brightness(crate::theme::Brightness::MediumDark));+ let scroll = ctx.global_style().spacing.scroll;+ let bar = scroll.bar_inner_margin + scroll.bar_width + scroll.bar_outer_margin;+ for width in [236.0, 256.0, 300.0, 333.0] {+ let mut panel = egui::Rect::NOTHING;+ let mut grid = None;+ for _ in 0..2 {+ // The app raises the texture limit for the grid (see `test_window`).+ let raw = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 700.0))),+ max_texture_side: Some(8192),+ ..Default::default()+ };+ let mut out = ctx.run_ui(raw, |ui| {+ ui.allocate_ui(vec2(width, 650.0), |ui| {+ ui.set_width(width);+ panel = ui.max_rect();+ show(&mut app, ui);+ });+ });+ out.textures_delta.clear();+ // The grid is the one textured mesh that isn't text.+ grid = out.shapes.iter().find_map(|s| match &s.shape {+ egui::Shape::Mesh(m) if m.texture_id != egui::TextureId::default() => Some(m.calc_bounds()),+ _ => None,+ });+ }+ let grid = grid.expect("the glyph grid is drawn");+ assert!(grid.right() <= panel.right() - bar + 0.5, "{width}: the grid {grid:?} runs under the scroll bar of {panel:?}");+ assert!(grid.right() > panel.right() - bar - CELL, "{width}: no column is left out ({grid:?})");+ }+ }+}