From d4c28a246db349c96cf3a49ecc1a9345a82a2c99 Mon Sep 17 00:00:00 2001 From: midasdf Date: Thu, 22 Oct 2026 01:50:07 +0900 Subject: [PATCH 001/322] =?UTF-8?q?feat(compose):=20apply=20=E7=A6=81?= =?UTF-8?q?=E5=89=87=20push-in/push-out=20priorities=20(JIS=20X=204051)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The four JIS X 4051 禁則処理 modes are now reached from the paragraph settings and applied to CJK text by both composers. The empty default and Push In First compose as push-in-first (InDesign's Japanese default); Push Out First, Push Out Only and adjustment-amount as their names say. A per-paragraph CJK flag keeps the default from biasing Latin paragraphs, and mode 3's compression-off is gated by it. The adjustment-amount value is an explicit mapping to the breaker's minimum-adjustment mode instead of falling through the wildcard. docs/cjk-typography.md moves the modes from Unfinished behavior to implemented and corrects the preflight claim; ROADMAP gets a progress line. New regressions pin the default = push-in-first, the push-out-only line-end behavior, the mode mapping and the Latin non-bias. --- ROADMAP.md | 4 +- crates/compose/src/breaker.rs | 53 +++++++++++------ crates/compose/src/lib.rs | 37 ++++++++++-- crates/compose/src/tests.rs | 106 ++++++++++++++++++++++++++++++++++ crates/doc/src/attrs.rs | 5 +- docs/cjk-typography.md | 15 +++-- 6 files changed, 191 insertions(+), 29 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index a7b5105d3..c79b2f7a2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -3,7 +3,7 @@ **Stage: pre-alpha** · next: alpha, ~5–7 h away; beta ~28 points and ~420–750 h beyond that (the core-workflow gate, not the percentage: ready for real work is already ~47%) - FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage. -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-22 · **Change:** minor (Compose: the JIS X 4051 禁則処理 push-in/push-out priorities are applied by both composers over CJK text — the empty default and Push In First compose as push-in-first as in InDesign's Japanese default, Push Out First, Push Out Only and adjustment-amount as their names say; Latin paragraphs are not biased; preflight reports only unknown values; previously minor: File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026 - AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it. - AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md. @@ -348,6 +348,8 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-22** · Compose: the JIS X 4051 禁則処理 push-in/push-out priorities are applied, not just preserved. Both composers bias the break candidates by the selected type over CJK text: push-in-first (the empty default and the UI's Push In First, as in InDesign's Japanese default) rates breaks that would stretch the line worse than ones it can reach by compressing, push-out-first the other way, push-out-only leaves no compression at the line end, and adjustment-amount takes the smallest adjustment. Latin paragraphs are not biased by the default. New regressions pin the default = push-in-first, the push-out-only line-end fits, the mode mapping and the Latin non-bias; `docs/cjk-typography.md` now lists the modes as implemented and preflight reports only unknown values. No readiness percentage change. + - **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change. - **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change. - **2026-10-17** · File › Package writes the document's and the IDML's links relative to the package (`Links/logo.png`, `file:Links/logo.png`), so a package holds no path from the machine that made it; opening a document resolves them to the files beside it. Links › Copy Link(s) To still links by full path. (#340). No readiness percentage change. diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs index 0dff34702..e861eb023 100644 --- a/crates/compose/src/breaker.rs +++ b/crates/compose/src/breaker.rs @@ -50,8 +50,12 @@ pub struct Spacing { pub optical: bool, /// Korean text breaks between syllables instead of at spaces. pub korean_char_breaks: bool, - /// 0: minimum adjustment; 1: push in; 2: push out first; 3: push out only. + /// JIS X 4051 禁則処理 type: 0: minimum adjustment (調整量優先); 1: push in first (追い込み + /// 優先, the default); 2: push out first (追い出し優先); 3: push out only (追い出しのみ). pub kinsoku_priority: u8, + /// The paragraph has CJK text, so the 禁則 priority biases its breaks. A Latin paragraph's + /// breaks are left alone by the (default) push-in-first policy. + pub kinsoku_cjk: bool, } impl Default for Spacing { @@ -73,19 +77,25 @@ impl Default for Spacing { hyph_zone: 0.0, optical: false, korean_char_breaks: false, - kinsoku_priority: 0, + kinsoku_priority: 1, + kinsoku_cjk: false, } } } impl Spacing { + /// Push out only: the 追い込み (compression that would pull the next character in) is + /// unavailable, so every line end is pushed out (and no line is compressed at its end). + pub(crate) fn push_out_only(&self) -> bool { + self.kinsoku_cjk && self.kinsoku_priority == 3 + } /// Per-tier (word, letter, glyph) stretch and shrink of glyph `g` as a box. fn box_elastic(&self, g: &Glyph) -> ([f64; 3], [f64; 3]) { if g.locked_advance { return ([0.0; 3], [0.0; 3]); } let moji_stretch = if self.justify { g.moji.stretch } else { 0.0 }; - let moji_shrink = if self.kinsoku_priority == 3 { 0.0 } else { g.moji.shrink }; + let moji_shrink = if self.push_out_only() { 0.0 } else { g.moji.shrink }; if !self.justify { return ([0.0; 3], [moji_shrink, 0.0, 0.0]); } @@ -386,7 +396,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S let mut p = Item::penalty(0.0, -INF, false); p.hang = prev_hang; if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) { - p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3); + p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, !sp.push_out_only()); } it.push(p); ig.push(i + 1); @@ -400,7 +410,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S let mut gl = Item::glue(w, st, sh); gl.hang = prev_hang; if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) { - gl.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3); + gl.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, !sp.push_out_only()); } gl.over = sp.space_overflow(g); last_space = it.len(); @@ -413,7 +423,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S let mut p = Item::penalty(0.0, 0.0, false); p.hang = prev_hang; if let Some(prev) = i.checked_sub(1).and_then(|j| glyphs.get(j)) { - p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, sp.kinsoku_priority != 3); + p.edge_elastic = crate::mojikumi::end_elastic(prev, sp.justify, !sp.push_out_only()); } last_space = it.len(); it.push(p); @@ -437,7 +447,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S let (st, sh) = sp.box_elastic(g); let mut bx = Item::boxed(g.adv, st, sh); bx.hang = (if sp.optical { hang_left(g) } else { 0.0 }) - g.moji.start; - bx.start_elastic = crate::mojikumi::start_elastic(g, sp.justify, sp.kinsoku_priority != 3); + bx.start_elastic = crate::mojikumi::start_elastic(g, sp.justify, !sp.push_out_only()); it.push(bx); ig.push(i); let next_is_space = glyphs.get(i + 1).is_none_or(|n| n.is_space()); @@ -445,12 +455,12 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S if matches!(g.ch, '-' | '\u{2010}') { let mut p = Item::penalty(0.0, 50.0, true); p.hang = right_hang(g, sp); - p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3); + p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only()); push_inword(&mut it, &mut ig, p, i + 1, sp); } else if matches!(g.ch, '\u{2013}' | '\u{2014}' | '/') || g.break_after.unwrap_or_else(|| cjk_break(g, &glyphs[i + 1], sp)) { let mut p = Item::penalty(0.0, 0.0, false); p.hang = right_hang(g, sp); - p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3); + p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only()); push_inword(&mut it, &mut ig, p, i + 1, sp); } else if hyph_after[i] { let hw = hyphen_width(g, &mut hy_cache); @@ -474,7 +484,7 @@ fn items(glyphs: &[Glyph], hyph_after: &[bool], emergency_after: &[bool], sp: &S let mut p = Item::penalty(0.0, -INF, false); p.hang = if n > 0 { right_hang(&glyphs[n - 1], sp) } else { 0.0 }; if let Some(g) = glyphs.last() { - p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3); + p.edge_elastic = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only()); } it.push(p); ig.push(n); @@ -693,10 +703,18 @@ fn kp_pass( } } } - let preference = match sp.kinsoku_priority { - 1 if r > 0.0 => 4.0, - 2 if r < 0.0 => 4.0, - _ => 1.0, + // 禁則 priority (JIS X 4051): push-in-first rates breaks whose line would have to be + // stretched (r > 0: the next character is pushed out) worse than ones it can reach by + // compressing (追い込み); push-out-first the other way. Adjustment-amount mode and a + // paragraph without CJK text rate every candidate by its adjustment alone. + let preference = if !sp.kinsoku_cjk { + 1.0 + } else { + match sp.kinsoku_priority { + 1 if r > 0.0 => 4.0, + 2 if r < 0.0 => 4.0, + _ => 1.0, + } }; let bad = preference * 100.0 * r.abs().powi(3); let lp = 10.0 + bad; @@ -877,7 +895,7 @@ pub fn greedy( while start < n { let w = width(line).max(1.0); let mut x = (if sp.optical { -hang_left(&glyphs[start]) } else { 0.0 }) + glyphs[start].moji.start; - let mut shrink = crate::mojikumi::start_elastic(&glyphs[start], sp.justify, sp.kinsoku_priority != 3)[1]; + let mut shrink = crate::mojikumi::start_elastic(&glyphs[start], sp.justify, !sp.push_out_only())[1]; let mut last_natural: Option<(usize, bool)> = None; let mut last_ok: Option<(usize, bool)> = None; // (break position = end glyph, hyphen) let mut last_space: Option<(usize, f64)> = None; // (break position, line width there) @@ -904,9 +922,10 @@ pub fn greedy( } let hang_r = right_hang(g, sp); let adv = if g.ch == '\t' { tab(line, x, i) } else { g.adv }; - let end_shrink = crate::mojikumi::end_elastic(g, sp.justify, sp.kinsoku_priority != 3)[1]; + let end_shrink = crate::mojikumi::end_elastic(g, sp.justify, !sp.push_out_only())[1]; let available = shrink + sp.box_elastic(g).1.iter().sum::() + end_shrink; - if sp.kinsoku_priority == 2 + if sp.kinsoku_cjk + && sp.kinsoku_priority == 2 && x + adv - hang_r > w + FIT_EPS && let Some((end, hyphen)) = last_natural { diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 4a2c66397..67b2fb7ff 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1067,7 +1067,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C let cols_here = &cols[cur.fi]; let col = span_rect(cols_here, cols_here[cur.col.min(cols_here.len() - 1)], pp.span_columns); let col = SplitCfg::of(&pp).map_or(col, |c| c.sub_rect(col, 0)); - let spacing = spacing_for(&pp, base_chars.size); + let spacing = spacing_for(&pp, base_chars.size, sp.glyphs.iter().any(|g| is_cjk_char(g.ch))); let mut lines: Vec<(std::ops::Range, String)> = Vec::new(); for _ in 0..3 { // The same drop cap, spacing, hyphenation and breaker as the layout below. @@ -1220,7 +1220,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C mojikumi::apply(&mut glyphs, &doc.styles, &pp.mojikumi); let hyph_after = hyphenation_points(&story.text, &glyphs, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars)); let base_size = base_chars.size; - let spacing = spacing_for(&pp, base_size); + let spacing = spacing_for(&pp, base_size, glyphs.iter().any(|g| is_cjk_char(g.ch))); // An empty paragraph takes its height from its paragraph mark's character format. let mark_chars = if glyphs.is_empty() { std::borrow::Cow::Owned(doc.styles.resolve_char(&base_chars, story.char_format_of(prange.start))) @@ -2147,8 +2147,9 @@ pub fn column_rule_rects(columns: &[Rect], lines: &[Line], opts: &TextFrameOptio out } -/// Breaker parameters from the paragraph's settings. -fn spacing_for(pp: &ParaProps, base_size: f64) -> Spacing { +/// Breaker parameters from the paragraph's settings; `cjk` says the paragraph has CJK text (so +/// its 禁則 priority applies). +fn spacing_for(pp: &ParaProps, base_size: f64, cjk: bool) -> Spacing { Spacing { justify: pp.align.is_justified(), word_min: pp.word_space_min, @@ -2168,15 +2169,39 @@ fn spacing_for(pp: &ParaProps, base_size: f64) -> Spacing { hyph_zone: if pp.align.is_justified() || !pp.composer.single_line() { 0.0 } else { pp.hyph_zone }, optical: pp.optical_margin, korean_char_breaks: pp.korean_char_breaks, + kinsoku_cjk: cjk, + // JIS X 4051 禁則処理: the empty value is InDesign's default and the UI's "Push In First", + // and 調整量優先 (adjustment amount) is the breaker's minimum-adjustment mode 0. kinsoku_priority: match pp.kinsoku_type.as_str() { - "KinsokuPushInFirst" => 1, + "" | "KinsokuPushInFirst" => 1, "KinsokuPushOutFirst" => 2, "KinsokuPushOutOnly" => 3, + "KinsokuPrioritizeAdjustmentAmount" => 0, _ => 0, }, } } +/// Is `c` CJK text (the scripts the 禁則 line-start/line-end rules are about): ideographs, kana, +/// CJK punctuation and full/half-width forms, bopomofo, Hangul. +fn is_cjk_char(c: char) -> bool { + matches!( + c as u32, + 0x1100..=0x11FF + | 0x2E80..=0x2FFF + | 0x3000..=0x30FF + | 0x3100..=0x318F + | 0x3190..=0x33FF + | 0x3400..=0x4DBF + | 0x4E00..=0x9FFF + | 0xA000..=0xA4CF + | 0xAC00..=0xD7AF + | 0xF900..=0xFAFF + | 0xFE30..=0xFE4F + | 0xFF00..=0xFFEF + ) +} + /// Desired word spacing, letter spacing and glyph scaling apply to every line (any alignment). fn apply_desired_spacing(glyphs: &mut [Glyph], pp: &ParaProps) { for i in 0..glyphs.len() { @@ -3351,7 +3376,7 @@ fn layout_line( } } } - if (justify_this || squeeze_last) && (extra >= 0.0 || sp.kinsoku_priority != 3) { + if (justify_this || squeeze_last) && (extra >= 0.0 || !sp.push_out_only()) { extra = mojikumi::distribute(line.get_mut(seg..).unwrap_or_default(), extra, add.get_mut(seg..).unwrap_or_default()); } if (justify_this || squeeze_last) && !spaces.is_empty() { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index ed4c7c476..2486107e2 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5247,6 +5247,112 @@ fn mojikumi_kinsoku_push_in_and_push_out_select_different_legal_breaks() { } } +/// A paragraph that can compress: the Mojikumi table gives its ideographs shrinkable space, so +/// a line ending before a 禁則 boundary can be pulled in (追い込み) or pushed out (追い出し). +fn kinsoku_push_pull_doc(kind: Option<&str>) -> (Document, StoryId) { + use designcraft_doc::cjk::{MojikumiAki, MojikumiTable}; + let (mut d, sid, _) = doc_with( + "甲乙丙丁戊己庚辛", + Rect::new(0.0, 0.0, 45.0, 300.0), + ParaAttrs { + composer: Some(Composer::SingleLine), + mojikumi: Some("MojikumiTable/Compress".into()), + kinsoku_type: kind.map(str::to_string), + ..Default::default() + }, + ); + Arc::make_mut(&mut d.styles).mojikumi_tables.push(MojikumiTable { + name: "Compress".into(), + based_on: "SimpChineseDefault".into(), + overrides: vec![MojikumiAki { + target_class: 12, + side_class: 12, + after: true, + minimum: 0.0, + desired: 1.0, + maximum: 2.0, + priority: 1, + ..Default::default() + }], + }); + (d, sid) +} + +fn first_line_end(cs: &ComposedStory) -> (usize, f64) { + let line = all_lines(cs)[0]; + (line.range.end, line.end_x) +} + +#[test] +fn default_kinsoku_type_composes_as_push_in_first() { + // The empty value is InDesign's default (and what the UI's "Push In First" stores): it must + // behave as push-in-first, not as the minimum-adjustment mode. + let (d, sid) = kinsoku_push_pull_doc(None); + let default = compose_story(&d, sid, &ComposeOptions::default()); + let (d, sid) = kinsoku_push_pull_doc(Some("KinsokuPushInFirst")); + let push_in = compose_story(&d, sid, &ComposeOptions::default()); + let (d, sid) = kinsoku_push_pull_doc(Some("KinsokuPushOutFirst")); + let push_out = compose_story(&d, sid, &ComposeOptions::default()); + assert_eq!(first_line_end(&default).0, first_line_end(&push_in).0); + assert!(first_line_end(&default).0 > first_line_end(&push_out).0, "{:?} vs {:?}", first_line_end(&default), first_line_end(&push_out)); +} + +#[test] +fn push_out_only_leaves_the_line_end_uncompressed() { + // Push-out-only turns the 追い込み compression off: the line cannot be squeezed to reach a + // break, so it ends earlier (and never past the measure). + let (d, sid) = kinsoku_push_pull_doc(None); + let push_in = compose_story(&d, sid, &ComposeOptions::default()); + let (d, sid) = kinsoku_push_pull_doc(Some("KinsokuPushOutOnly")); + let push_out_only = compose_story(&d, sid, &ComposeOptions::default()); + assert!(first_line_end(&push_out_only).0 <= first_line_end(&push_in).0); + for cs in [&push_in, &push_out_only] { + for line in all_lines(cs) { + assert!(line.end_x <= line.x1 + 0.01, "line end {} past the measure {}", line.end_x, line.x1); + } + } + // Push-out-only's first line is not compressed to the measure: it ends short of it. + let (_, short) = first_line_end(&push_out_only); + let line = all_lines(&push_out_only)[0]; + assert!(line.x1 - short > 0.5, "no compression: end {short} vs measure {}", line.x1); +} + +#[test] +fn kinsoku_priority_modes_map_to_breaker_policies() { + let mut pp = ParaProps::default(); + for (kind, priority) in [ + ("", 1u8), + ("KinsokuPushInFirst", 1), + ("KinsokuPushOutFirst", 2), + ("KinsokuPushOutOnly", 3), + ("KinsokuPrioritizeAdjustmentAmount", 0), + ("KinsokuSomethingElse", 0), + ] { + pp.kinsoku_type = kind.to_string(); + let sp = spacing_for(&pp, 12.0, true); + assert_eq!(sp.kinsoku_priority, priority, "{kind}"); + assert!(sp.kinsoku_cjk, "{kind}"); + assert!(!spacing_for(&pp, 12.0, false).kinsoku_cjk, "{kind}: Latin text is not biased"); + } +} + +#[test] +fn latin_paragraphs_are_not_biased_by_the_kinsoku_priority() { + // A justified Latin paragraph composes the same with push-in-first, push-out-first and + // minimum adjustment: the policy is about CJK 禁則, and a Latin paragraph has none. + let compose_with = |kind: &str| { + let (mut d, sid, _) = + doc_with(LOREM, Rect::new(0.0, 0.0, 200.0, 500.0), ParaAttrs { align: Some(Align::FullyJustified), ..Default::default() }); + d.story_mut(sid).unwrap().paras[0].para.kinsoku_type = Some(kind.to_string()); + compose_story(&d, sid, &ComposeOptions::default()) + }; + let ends = |cs: &ComposedStory| all_lines(cs).iter().map(|l| l.range.end).collect::>(); + let push_in = ends(&compose_with("")); + assert_eq!(ends(&compose_with("KinsokuPushInFirst")), push_in); + assert_eq!(ends(&compose_with("KinsokuPushOutFirst")), push_in); + assert_eq!(ends(&compose_with("KinsokuPrioritizeAdjustmentAmount")), push_in); +} + #[test] fn mojikumi_priority_and_elastic_line_start_are_used_in_placement() { use designcraft_doc::cjk::{MojikumiAki, MojikumiTable}; diff --git a/crates/doc/src/attrs.rs b/crates/doc/src/attrs.rs index 077637672..f47a5fbbd 100644 --- a/crates/doc/src/attrs.rs +++ b/crates/doc/src/attrs.rs @@ -1276,7 +1276,10 @@ attr_set! { kinsoku: Option = None => "deserialize_explicit_value", /// Preserved spacing-table reference; compatibility audit reports unsupported composition. mojikumi: String = String::new(), - /// Preserved priority policy; the current breaker does not implement these priorities. + /// JIS X 4051 禁則処理 type, applied by both composers to CJK text: empty (the default) + /// and `KinsokuPushInFirst` compose as push-in-first, `KinsokuPushOutFirst`, + /// `KinsokuPushOutOnly` and `KinsokuPrioritizeAdjustmentAmount` (minimum adjustment) as + /// their names say. kinsoku_type: String = String::new(), kinsoku_hang: crate::cjk::KinsokuHang = crate::cjk::KinsokuHang::None, bunri_kinshi: bool = false, diff --git a/docs/cjk-typography.md b/docs/cjk-typography.md index 49d350b88..e46fb3c51 100644 --- a/docs/cjk-typography.md +++ b/docs/cjk-typography.md @@ -1,6 +1,6 @@ # CJK import and composition -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-07 · **Change:** trivial (status line and revision history added; content unchanged in the 2026-10-10 review) · **Target:** Adobe InDesign 2026 +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-22 · **Change:** minor (the JIS X 4051 禁則処理 push-in/push-out priority modes are applied by both composers over CJK text: the empty default and Push In First compose as push-in-first, Push Out First, Push Out Only and adjustment-amount as their names say; Latin paragraphs are not biased; preflight reports only unknown values) · **Target:** Adobe InDesign 2026 Task: CJK1. This is incremental support, not a claim of InDesign composition parity. @@ -27,6 +27,7 @@ invalidation. Font listing, replacement and preflight resolve component fonts. | Tsume | Compress nonnegative glyph sidebearings without scaling ink; full compression regression | | Jidori | Fixed group width with protected internal boundaries and justification advances; both composers tested | | Kinsoku sets | Custom character sets and independent common punctuation defaults for named sets; explicit disabling retained | +| Kinsoku priorities | The four JIS X 4051 禁則処理 types, applied by both composers to CJK text: push-in-first (the empty default, as in InDesign) and push-out-first weight the break candidates by the adjustment direction, push-out-only turns the end-of-line compression off, and adjustment-amount (調整量優先) takes the candidate with the smallest adjustment; Latin paragraphs are not biased. Regressions pin the breaks, the line-end fits and the mode mapping | | Bunri kinshi / rensuuji | Protect repeated dash/ellipsis pairs and numeric sequences | | Hanging punctuation | Regular/forced edge allowance integrated with line breaking and placement | | Ideographic spaces | Paragraph switch controls whether fullwidth spaces participate in word spacing | @@ -39,9 +40,14 @@ invalidation. Font listing, replacement and preflight resolve component fonts. - **Mojikumi**: definitions, base-set names, all override rows and paragraph references survive import/export. The numeric character-class spacing tables and their compression priorities are **not executed**. Preflight reports this explicitly. -- **Kinsoku push-in/push-out priorities**: retained, but not used in candidate - selection. Preflight reports this explicitly. Boundary prohibition alone is not - equivalent to implementing this priority policy. +- **Kinsoku priority policy** is applied as a line-cost weighting in the total-fit composer (and + as the single-line composer's early-break rule): push-in-first rates breaks that would have to + stretch the line worse than ones it can reach by compressing, push-out-first the other way, + push-out-only leaves no compression at the line end, and adjustment-amount rates every + candidate by its adjustment alone. It is a preference within the composer's other costs, not a + hard "always 追い込み before 追い出し" rule. Preflight reports only values it does not + know: the four JIS X 4051 modes are not reported as unapplied. Boundary prohibition, hanging + punctuation and the named sets are unchanged. - Named kinsoku defaults are clean-room common punctuation rules, not verified reproductions of every vendor preset. Explicit custom tables take precedence. - ICF alignment currently uses font ascender/descender metrics; exact ideographic @@ -69,5 +75,6 @@ are not committed as fixtures. | Date | Change | Summary | |---|---|---| +| 2026-10-22 | minor | 禁則処理 priority modes applied: the empty default and Push In First compose as push-in-first (as InDesign's Japanese default), Push Out First, Push Out Only and adjustment-amount (minimum adjustment) as their names say, for CJK text; Latin paragraphs are not biased; preflight reports only unknown values; breaks, line-end fits and the mode mapping regression-tested | | 2026-10-10 | trivial | Reviewed in the full re-measure; status line and this table added; summarized in [typography-parity.md](typography-parity.md) and [localization-parity.md](localization-parity.md) | | 2026-10-07 | major | Created: CJK1: IDML CJK import and composition | From d9504f09ac1b95f1c4f73b975262603ad0ada7b6 Mon Sep 17 00:00:00 2001 From: paaspaas00 <151774837+paaspaas00@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:57:04 +0200 Subject: [PATCH 002/322] Layer Options: Lock Guides, as InDesign's InDesign's Layer Options has Lock Guides beside Lock Layer: the layer's ruler guides can't be moved or deleted while its objects stay editable. Layers get `lock_guides` (serde default off), `Guide::editable_in` honours it, `layer.set` takes `lockGuides`, and IDML reads and writes the layer's `LockGuides` (it was always written as false). The options are arranged as InDesign's: Show Layer and Show Guides, Lock Layer and Lock Guides, Print Layer, then Suppress Text Wrap When Layer is Hidden. Found in the Learn Skills Daily course, chapter 32. Co-Authored-By: Claude Opus 5.5 --- ROADMAP.md | 1 + crates/doc/src/build.rs | 1 + crates/doc/src/lib.rs | 3 +++ crates/doc/src/page.rs | 4 ++-- crates/engine/src/cmd/guides.rs | 25 +++++++++++++++++++++++ crates/engine/src/cmd/layout.rs | 6 ++++-- crates/idml/src/export.rs | 2 +- crates/idml/src/import.rs | 2 ++ crates/idml/src/tests.rs | 19 ++++++++++++++++++ crates/ui-egui/src/dialogs/options.rs | 29 +++++++++++++++++++++++---- 10 files changed, 83 insertions(+), 9 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index a7b5105d3..58d784b7b 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -348,6 +348,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m Newest first. +- **2026-10-21** · Layer Options has InDesign's Lock Guides: the layer's ruler guides can't be moved or deleted while its objects stay editable (`layer.set {lockGuides}`), and IDML reads and writes the layer's `LockGuides` (it was always written as false). The options are arranged as InDesign's: Show Layer and Show Guides, Lock Layer and Lock Guides, Print Layer. Found in the Learn Skills Daily course, chapter 32. No readiness percentage change. - **2026-10-16** · Type › Reload Fonts (`font.reload`): fonts installed, edited or removed while DesignCraft runs are read again without a restart, and the open documents recompose with them (#328, #547). An edited font file is noticed by its length and modification time; bundled, added and document fonts stay as they are. InDesign does this by itself, so noticing changes automatically is still open (gap 6). No readiness percentage change. - **2026-10-16** · Parents can be deleted from their Pages-panel context menu or `layout.parents.delete {id}`. Applied-page and based-on references are cleared, local override copies survive, and Undo restores the parent. Addresses the deletion portion of #956; no readiness percentage change. - **2026-10-17** · File › Package writes the document's and the IDML's links relative to the package (`Links/logo.png`, `file:Links/logo.png`), so a package holds no path from the machine that made it; opening a document resolves them to the files beside it. Links › Copy Link(s) To still links by full path. (#340). No readiness percentage change. diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs index f8ae0ec19..4a5d4812a 100644 --- a/crates/doc/src/build.rs +++ b/crates/doc/src/build.rs @@ -173,6 +173,7 @@ impl Document { locked: false, printable: true, show_guides: true, + lock_guides: false, suppress_wrap_when_hidden: false, }); // A-Parent. diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 1bf834ae0..b527b032f 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -480,6 +480,9 @@ pub struct Layer { pub printable: bool, #[serde(default = "yes")] pub show_guides: bool, + /// Lock Guides: the layer's ruler guides can't be moved or deleted. + #[serde(default)] + pub lock_guides: bool, #[serde(default)] pub suppress_wrap_when_hidden: bool, } diff --git a/crates/doc/src/page.rs b/crates/doc/src/page.rs index 862a1cda9..6dbef3360 100644 --- a/crates/doc/src/page.rs +++ b/crates/doc/src/page.rs @@ -73,9 +73,9 @@ impl Guide { pub fn visible_in(&self, d: &crate::Document) -> bool { self.layer.is_none_or(|l| d.layer(l).is_none_or(|l| l.visible && l.show_guides)) } - /// Can be dragged: neither it nor its layer is locked. + /// Can be dragged: neither it nor its layer is locked, nor are the layer's guides. pub fn editable_in(&self, d: &crate::Document) -> bool { - !self.locked && self.layer.is_none_or(|l| d.layer(l).is_none_or(|l| !l.locked && l.visible && l.show_guides)) + !self.locked && self.layer.is_none_or(|l| d.layer(l).is_none_or(|l| !l.locked && !l.lock_guides && l.visible && l.show_guides)) } } diff --git a/crates/engine/src/cmd/guides.rs b/crates/engine/src/cmd/guides.rs index e8be163ef..9349fd4bc 100644 --- a/crates/engine/src/cmd/guides.rs +++ b/crates/engine/src/cmd/guides.rs @@ -416,6 +416,31 @@ mod layer_tests { assert_eq!(s.execute("guide.list", &json!({})).unwrap()[0]["position"], 200.0); } + /// Layer Options › Lock Guides: the layer's guides stay where they are (moving and deleting + /// them is refused) while its objects stay editable. + #[test] + fn lock_guides_locks_only_the_layers_guides() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let layer = s.execute("layer.new", &json!({"name": "Grid"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": layer})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 100})).unwrap(); + let frame = s.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.set", &json!({"id": layer, "lockGuides": true})).unwrap(); + let d = s.doc().unwrap().doc.clone(); + let g = d.spreads[0].pages[0].guides[0].clone(); + assert!(g.visible_in(&d) && !g.editable_in(&d)); + for command in ["guide.move", "guide.delete"] { + assert!(s.execute(command, &json!({"page": 0, "index": 0, "position": 200})).is_err(), "{command} moved a locked guide"); + } + assert_eq!(s.execute("guide.list", &json!({})).unwrap()[0]["position"], 100.0); + // The layer's objects aren't locked. + s.execute("transform.move", &json!({"ids": [frame], "dx": 10, "dy": 0})).unwrap(); + s.execute("layer.set", &json!({"id": layer, "lockGuides": false})).unwrap(); + s.execute("guide.move", &json!({"page": 0, "index": 0, "position": 200})).unwrap(); + assert_eq!(s.execute("guide.list", &json!({})).unwrap()[0]["position"], 200.0); + } + #[test] fn guides_follow_their_layer() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 615e7c1df..26e41f838 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -680,6 +680,7 @@ pub fn specs() -> Vec { locked: false, printable: true, show_guides: true, + lock_guides: false, suppress_wrap_when_hidden: false, }, ); @@ -693,7 +694,7 @@ pub fn specs() -> Vec { "Layer Options…", [], None, - "{id, name?, color?: [r,g,b] | layer colour name (\"Light Blue\", \"Red\", …), visible?, locked?, printable?, showGuides?, suppressWrapWhenHidden?} — names are unique and not empty", + "{id, name?, color?: [r,g,b] | layer colour name (\"Light Blue\", \"Red\", …), visible?, locked?, printable?, showGuides?, lockGuides?, suppressWrapWhenHidden?} — names are unique and not empty", has_doc, set_layer ), @@ -1202,7 +1203,7 @@ fn set_layer(s: &mut Session, p: &Value) -> Result { Some(v) => v.as_bool().map(Some).ok_or_else(|| bad(ID, format!("`{k}` is true or false"))), }; let (visible, locked, printable) = (flag("visible")?, flag("locked")?, flag("printable")?); - let (guides, wrap) = (flag("showGuides")?, flag("suppressWrapWhenHidden")?); + let (guides, lock_guides, wrap) = (flag("showGuides")?, flag("lockGuides")?, flag("suppressWrapWhenHidden")?); s.edit(|d, _| { if let Some(n) = &name && d.layers.iter().any(|l| l.id != id && l.name == *n) @@ -1221,6 +1222,7 @@ fn set_layer(s: &mut Session, p: &Value) -> Result { (&mut l.locked, locked), (&mut l.printable, printable), (&mut l.show_guides, guides), + (&mut l.lock_guides, lock_guides), (&mut l.suppress_wrap_when_hidden, wrap), ] { if let Some(v) = v { diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs index 86fef8e46..a4c80fbdc 100644 --- a/crates/idml/src/export.rs +++ b/crates/idml/src/export.rs @@ -381,7 +381,7 @@ impl<'a> Ex<'a> { .attr("Locked", bool_s(l.locked)) .attr("IgnoreWrap", bool_s(l.suppress_wrap_when_hidden)) .attr("ShowGuides", bool_s(l.show_guides)) - .attr("LockGuides", "false") + .attr("LockGuides", bool_s(l.lock_guides)) .attr("UI", "true") .attr("Expendable", "true") .attr("Printable", bool_s(l.printable)); diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs index d770aef79..c7922e280 100644 --- a/crates/idml/src/import.rs +++ b/crates/idml/src/import.rs @@ -698,6 +698,7 @@ impl<'r> Importer<'r> { locked: e.get("Locked") == Some("true"), printable: e.get("Printable") != Some("false"), show_guides: e.get("ShowGuides") != Some("false"), + lock_guides: e.get("LockGuides") == Some("true"), suppress_wrap_when_hidden: e.get("IgnoreWrap") == Some("true"), }); if let Some(s) = e.get("Self") { @@ -716,6 +717,7 @@ impl<'r> Importer<'r> { locked: false, printable: true, show_guides: true, + lock_guides: false, suppress_wrap_when_hidden: false, }); } diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 035333da4..083b7a166 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -2049,6 +2049,25 @@ fn layers_import_and_export_in_stacking_order() { assert_eq!(back.spreads[0].items[0].layer, back.layers[1].id); } +/// Layer Options › Lock Guides is IDML's `LockGuides`: read, and written back (it was always +/// written as false). +#[test] +fn layer_lock_guides_round_trips() { + let designmap = r#" + + + + "#; + let spread = r#" + + "#; + let d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread)])).unwrap(); + let lock = |d: &Document, name: &str| d.layers.iter().find(|l| l.name == name).unwrap().lock_guides; + assert!(lock(&d, "Grid") && !lock(&d, "Art")); + let back = import_idml(&export_idml(&d)).unwrap(); + assert!(lock(&back, "Grid") && !lock(&back, "Art")); +} + /// Synthetic forward references: both a body anchor and a footnote anchor own /// a group containing a text frame whose story is serialized later. #[test] diff --git a/crates/ui-egui/src/dialogs/options.rs b/crates/ui-egui/src/dialogs/options.rs index d8aba2bea..d51546bcd 100644 --- a/crates/ui-egui/src/dialogs/options.rs +++ b/crates/ui-egui/src/dialogs/options.rs @@ -258,7 +258,7 @@ pub fn open_layer_options(app: &mut DesignApp, id: Option) -> Result<(), St let id = id.map_or(st.active_layer, designcraft_doc::LayerId); let l = st.doc.layer(id).ok_or("no such layer")?; let f = json!({"id": l.id.0, "name": l.name, "rgb": l.color, "visible": l.visible, "locked": l.locked, "printable": l.printable, - "showGuides": l.show_guides, "suppressWrapWhenHidden": l.suppress_wrap_when_hidden}); + "showGuides": l.show_guides, "lockGuides": l.lock_guides, "suppressWrapWhenHidden": l.suppress_wrap_when_hidden}); app.ui.dialog = Some(Dialog::new("layerSettings", f)); Ok(()) } @@ -292,11 +292,14 @@ pub fn layer_options(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.end_row(); }); ui.add_space(6.0); + // As InDesign's: the layer's options on the left, its guides' on the right. egui::Grid::new("layer_flags").num_columns(2).spacing([16.0, 6.0]).show(ui, |ui| { check(ui, d, "visible", tr(lang, "Show Layer")); - check(ui, d, "locked", tr(lang, "Lock Layer")); - ui.end_row(); check(ui, d, "showGuides", tr(lang, "Show Guides")); + ui.end_row(); + check(ui, d, "locked", tr(lang, "Lock Layer")); + check(ui, d, "lockGuides", tr(lang, "Lock Guides")); + ui.end_row(); check(ui, d, "printable", tr(lang, "Print Layer")); ui.end_row(); }); @@ -306,7 +309,7 @@ pub fn layer_options(app: &DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { pub fn confirm_layer_options(app: &mut DesignApp, d: &Dialog) -> Result { let mut p = json!({"id": d.fields.get("id").cloned().unwrap_or(Value::Null), "name": d.s("name"), "color": d.fields.get("rgb").cloned().unwrap_or(Value::Null)}); - for k in ["visible", "locked", "printable", "showGuides", "suppressWrapWhenHidden"] { + for k in ["visible", "locked", "printable", "showGuides", "lockGuides", "suppressWrapWhenHidden"] { p[k] = json!(d.b(k)); } app.run("layer.set", p) @@ -422,4 +425,22 @@ mod tests { let l = doc.layers.iter().find(|l| l.name == "Artwork").expect("renamed"); assert!(!l.printable); } + + /// The course's chapter 32: Layer Options has InDesign's Lock Guides, beside Lock Layer. + #[test] + fn layer_options_lock_the_layers_guides() { + let mut app = app(); + app.run("layer.new", json!({"name": "Grid"})).unwrap(); + let mut h = harness(app, crate::panels::layers::show); + double_click(&mut h, "Grid"); + let (lock, guides) = (h.get_by_label("Lock Layer").rect(), h.get_by_label("Lock Guides").rect()); + assert!((lock.center().y - guides.center().y).abs() < 2.0 && guides.left() > lock.right(), "Lock Guides is beside Lock Layer"); + h.get_by_label("Lock Guides").click(); + h.run_steps(2); + h.get_by_label(" OK ").click(); + h.run_steps(3); + let doc = &h.state().session.active().unwrap().doc; + let l = doc.layers.iter().find(|l| l.name == "Grid").unwrap(); + assert!(l.lock_guides && !l.locked); + } } From 0254475238d67168dccaa33de2f87e3c6c3728af Mon Sep 17 00:00:00 2001 From: moppeeer Date: Thu, 22 Oct 2026 00:35:13 +0200 Subject: [PATCH 003/322] Guides: Delete All and Create Guides' Remove Existing keep the guides that can't be edited Both cleared every guide. They now leave a locked guide and the guides of a layer that is locked, hidden or locks its guides, as `guide.move` and `guide.delete` do (`Guide::editable_in`), and Delete All counts only the guides it deleted. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/guides.rs | 68 ++++++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/guides.rs b/crates/engine/src/cmd/guides.rs index 9349fd4bc..eb01c9dd5 100644 --- a/crates/engine/src/cmd/guides.rs +++ b/crates/engine/src/cmd/guides.rs @@ -27,18 +27,23 @@ pub fn specs() -> Vec { ), cmd!("guide.move", "Move Guide", [], None, "{spread?, page, index, position}", has_doc, move_guide), cmd!("guide.delete", "Delete Guide", [], None, "{spread?, page, index}", has_doc, delete), - cmd!("guide.deleteAll", "Delete All Guides on Spread", ["View", "Grids & Guides"], None, "{spread?}", has_doc, |s, p| { - let r = super::spread_param(p, "guide.deleteAll")?; - s.edit(|d, _| { - let sp = d.spread_mut(r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?; - let mut n = 0; - for pg in &mut sp.pages { - n += pg.guides.len(); - pg.guides.clear(); - } - Ok(json!({"deleted": n})) - }) - }), + cmd!( + "guide.deleteAll", + "Delete All Guides on Spread", + ["View", "Grids & Guides"], + None, + "{spread?} — a locked guide, and the guides of a layer that is locked, hidden or locks its guides, stay → {deleted}", + has_doc, + |s, p| { + let r = super::spread_param(p, "guide.deleteAll")?; + s.edit(|d, _| { + let keep = kept_guides(d, r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?; + let sp = d.spread_mut(r).ok_or_else(|| bad("guide.deleteAll", "no such spread"))?; + let n: usize = sp.pages.iter_mut().zip(&keep).map(|(pg, keep)| remove_guides(&mut pg.guides, keep)).sum(); + Ok(json!({"deleted": n})) + }) + } + ), cmd!(query "guide.list", "Guides", [], None, "{spread?} → [{page, index, orientation, position, spread}]", has_doc, |s, p| { let d = &s.doc()?.doc; let sp = d.spread(super::spread_param(p, "guide.list")?).ok_or_else(|| bad("guide.list", "no such spread"))?; @@ -274,6 +279,7 @@ fn create_guides(s: &mut Session, p: &Value) -> Result { .ok_or_else(|| bad("layout.createGuides", format!("a single command may create at most {MAX_GUIDES_CREATED} guides")))?; let layer = s.doc()?.active_layer; s.edit(|d, _| { + let keep = kept_guides(d, r).ok_or_else(|| bad("layout.createGuides", "no such spread"))?; let sp = d.spread_mut(r).ok_or_else(|| bad("layout.createGuides", "no such spread"))?; let mut n = 0usize; for (pi, pg) in sp.pages.iter_mut().enumerate() { @@ -281,7 +287,7 @@ fn create_guides(s: &mut Session, p: &Value) -> Result { continue; } if remove { - pg.guides.clear(); + remove_guides(&mut pg.guides, keep.get(pi).map_or(&[][..], Vec::as_slice)); } let area: Rect = if to_page { pg.bounds() } else { pg.margin_rect() }; for y in grid_positions(area.y0, area.y1, rows, rg)? { @@ -311,6 +317,20 @@ fn create_guides(s: &mut Session, p: &Value) -> Result { }) } +/// Per page of spread `r`, the guides that can't be edited (locked, or on a layer that is locked, +/// hidden or locks its guides): what removing guides leaves. `None` without the spread. +fn kept_guides(d: &designcraft_doc::Document, r: designcraft_doc::SpreadRef) -> Option>> { + Some(d.spread(r)?.pages.iter().map(|pg| pg.guides.iter().map(|g| !g.editable_in(d)).collect()).collect()) +} + +/// Remove the guides `keep` doesn't mark; returns how many went. +fn remove_guides(guides: &mut Vec, keep: &[bool]) -> usize { + let before = guides.len(); + let mut keep = keep.iter(); + guides.retain(|_| keep.next().copied().unwrap_or(false)); + before - guides.len() +} + #[cfg(test)] mod tests { use super::*; @@ -441,6 +461,28 @@ mod layer_tests { assert_eq!(s.execute("guide.list", &json!({})).unwrap()[0]["position"], 200.0); } + #[test] + fn delete_all_and_remove_existing_keep_locked_guides() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let grid = s.execute("layer.new", &json!({"name": "Grid"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": grid})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 100})).unwrap(); + let free = s.execute("layer.new", &json!({"name": "Free"})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.activate", &json!({"id": free})).unwrap(); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 200})).unwrap(); + s.execute("layer.set", &json!({"id": grid, "lockGuides": true})).unwrap(); + let positions = |s: &mut Session| { + s.execute("guide.list", &json!({})).unwrap().as_array().unwrap().iter().map(|g| g["position"].as_f64().unwrap()).collect::>() + }; + assert_eq!(s.execute("guide.deleteAll", &json!({})).unwrap()["deleted"], 1); + assert_eq!(positions(&mut s), [100.0], "the locked layer's guide stays"); + s.execute("guide.add", &json!({"orientation": "vertical", "position": 200})).unwrap(); + s.execute("layout.createGuides", &json!({"columns": 2, "removeExisting": true, "page": 0})).unwrap(); + let after = positions(&mut s); + assert!(after.contains(&100.0) && !after.contains(&200.0), "{after:?}"); + } + #[test] fn guides_follow_their_layer() { let mut s = Session::new(); From 573ccb8377700275873732908d9dfa0cd089b36e Mon Sep 17 00:00:00 2001 From: midasdf Date: Thu, 22 Oct 2026 21:34:42 +0900 Subject: [PATCH 004/322] fix(compose): treat supplementary ideographs as CJK in the kinsoku gate is_cjk_char stopped at the BMP, while the breaker already classifies U+20000..=U+3FFFF as Han (breaker.rs, korean_letter's `han`). A paragraph made only of supplementary ideographs therefore passed cjk=false to spacing_for at both call sites, which disabled the explicit push-in / push-out cost preference and the push-out-only compression guard for text the breaker treats as Han. Match the breaker's Han range and add a regression that composes an Extension B paragraph, asserting the push-in and push-out-only line ends still differ, and pin the predicate for U+20000, U+2A6DF and U+3FFFF. The regression fails without the added range. --- crates/compose/src/lib.rs | 3 +++ crates/compose/src/tests.rs | 30 +++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 67b2fb7ff..3e96d5da1 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -2199,6 +2199,9 @@ fn is_cjk_char(c: char) -> bool { | 0xF900..=0xFAFF | 0xFE30..=0xFE4F | 0xFF00..=0xFFEF + // Extension B 以降 (U+20000..)。breaker の Han の判定と同じ範囲にして、 + // 補助面だけの段落でも禁則の指定が効くようにする + | 0x20000..=0x3FFFF ) } diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 2486107e2..67200f365 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5250,9 +5250,15 @@ fn mojikumi_kinsoku_push_in_and_push_out_select_different_legal_breaks() { /// A paragraph that can compress: the Mojikumi table gives its ideographs shrinkable space, so /// a line ending before a 禁則 boundary can be pulled in (追い込み) or pushed out (追い出し). fn kinsoku_push_pull_doc(kind: Option<&str>) -> (Document, StoryId) { + kinsoku_push_pull_doc_text("甲乙丙丁戊己庚辛", kind) +} + +/// Same paragraph with a different body: used for the supplementary-plane ideographs, whose +/// CJK classification must match the breaker's Han set. +fn kinsoku_push_pull_doc_text(text: &str, kind: Option<&str>) -> (Document, StoryId) { use designcraft_doc::cjk::{MojikumiAki, MojikumiTable}; let (mut d, sid, _) = doc_with( - "甲乙丙丁戊己庚辛", + text, Rect::new(0.0, 0.0, 45.0, 300.0), ParaAttrs { composer: Some(Composer::SingleLine), @@ -5317,6 +5323,28 @@ fn push_out_only_leaves_the_line_end_uncompressed() { assert!(line.x1 - short > 0.5, "no compression: end {short} vs measure {}", line.x1); } +#[test] +fn supplementary_ideograph_paragraph_keeps_the_kinsoku_gate() { + // Extension B 以降の漢字 (U+20000..) は breaker では Han として扱われる。段落全体の CJK 判定 + // (is_cjk_char) がそこを落とすと、補助面だけの段落で禁則の指定が効かなくなる。 + // 補助面だけの本文でも、追い込みと追い出しで行末が変わる (指定が効いている) こと。 + let first_end = |text: &str, kind: Option<&str>| { + let (d, sid) = kinsoku_push_pull_doc_text(text, kind); + first_line_end(&compose_story(&d, sid, &ComposeOptions::default())).0 + }; + let bmp = "甲乙丙丁戊己庚辛"; + let sup = "\u{20000}\u{20001}\u{20002}\u{20003}\u{20004}\u{20005}\u{20006}\u{20007}"; + // 対照: BMP の漢字だけの段落では、追い込みと追い出しで行末が変わる + assert_ne!(first_end(bmp, None), first_end(bmp, Some("KinsokuPushOutOnly")), "BMP の対照で禁則の指定が効いていない"); + // 補助面だけの段落でも同じように効く (判定から漏れると、どちらも同じ行末になる) + assert_ne!(first_end(sup, None), first_end(sup, Some("KinsokuPushOutOnly")), "補助面だけの段落で禁則の指定が効いていない"); + // 判定そのもの (Extension B の最初と最後、Ext G の終わり) + assert!(is_cjk_char('\u{20000}')); + assert!(is_cjk_char('\u{2A6DF}')); + assert!(is_cjk_char('\u{3FFFF}')); + assert!(!is_cjk_char('A')); +} + #[test] fn kinsoku_priority_modes_map_to_breaker_policies() { let mut pp = ParaProps::default(); From 4e037320b380d5e40dc353e1e7ac2fbc82ff3630 Mon Sep 17 00:00:00 2001 From: midasdf Date: Fri, 23 Oct 2026 00:09:43 +0900 Subject: [PATCH 005/322] fix(compose): classify the paragraph's script before its drop cap and label MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 禁則 gate read the CJK flag from sp.glyphs after split_drop_cap had removed the drop cap and prepend_label had added the list number. A paragraph whose only CJK character was a drop cap lost the push-in / push-out policy; a Japanese list label gave it to an English paragraph. Classify the shaped paragraph once before either change and reuse the flag in the nested-line-style pass and the final breaker. Tests: shape a paragraph with a CJK drop cap (counted) and a Latin paragraph with a generated Japanese label (not counted), pinning the glyph lists the gate sees. --- crates/compose/src/lib.rs | 15 +++++++++-- crates/compose/src/tests.rs | 53 +++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 2 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index d7ad7a864..34ef24119 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -1037,6 +1037,10 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C &[], (drop_end, &pp.drop_cap_style), ); + // The paragraph's script decides whether its 禁則 priority applies. Classify the shaped + // glyphs before split_drop_cap removes the drop cap and prepend_label adds the list + // label: a CJK drop cap is part of the paragraph, a generated label is not. + let cjk = paragraph_is_cjk(&sp.glyphs); // An empty paragraph has no glyphs of its own, so its only addressable character is its // hidden paragraph mark (the `\n` just past `prange.end`). A leading/size override applied // there (e.g. selecting the pilcrow to adjust line height) still needs to set the line's @@ -1067,7 +1071,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C let cols_here = &cols[cur.fi]; let col = span_rect(cols_here, cols_here[cur.col.min(cols_here.len() - 1)], pp.span_columns); let col = SplitCfg::of(&pp).map_or(col, |c| c.sub_rect(col, 0)); - let spacing = spacing_for(&pp, base_chars.size, sp.glyphs.iter().any(|g| is_cjk_char(g.ch))); + let spacing = spacing_for(&pp, base_chars.size, cjk); let mut lines: Vec<(std::ops::Range, String)> = Vec::new(); for _ in 0..3 { // The same drop cap, spacing, hyphenation and breaker as the layout below. @@ -1220,7 +1224,7 @@ fn compose_with_db(doc: &Document, story: &Story, frames: &[FrameSpec], opts: &C mojikumi::apply(&mut glyphs, &doc.styles, &pp.mojikumi); let hyph_after = hyphenation_points(&story.text, &glyphs, &pp, &hyph_exceptions, &foreign_ranges(doc, story, prange.clone(), &base_chars)); let base_size = base_chars.size; - let spacing = spacing_for(&pp, base_size, glyphs.iter().any(|g| is_cjk_char(g.ch))); + let spacing = spacing_for(&pp, base_size, cjk); // An empty paragraph takes its height from its paragraph mark's character format. let mark_chars = if glyphs.is_empty() { std::borrow::Cow::Owned(doc.styles.resolve_char(&base_chars, story.char_format_of(prange.start))) @@ -2183,6 +2187,13 @@ fn spacing_for(pp: &ParaProps, base_size: f64, cjk: bool) -> Spacing { } } +/// Whether the paragraph's own shaped glyphs contain CJK text, the gate for its 禁則 priority. +/// Called before `split_drop_cap` and `prepend_label`, so a drop cap counts and generated list +/// and story labels do not. +fn paragraph_is_cjk(glyphs: &[Glyph]) -> bool { + glyphs.iter().any(|g| is_cjk_char(g.ch)) +} + /// Is `c` CJK text (the scripts the 禁則 line-start/line-end rules are about): ideographs, kana, /// CJK punctuation and full/half-width forms, bopomofo, Hangul. fn is_cjk_char(c: char) -> bool { diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 9408a3909..009aab73d 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5345,6 +5345,59 @@ fn supplementary_ideograph_paragraph_keeps_the_kinsoku_gate() { assert!(!is_cjk_char('A')); } +/// Shape `text` as a one-paragraph story with the default font and styles: the glyph list the +/// composition classifies before `split_drop_cap` and `prepend_label`. +fn shape_for_script_test(text: &str) -> Vec { + let db = designcraft_fonts::FontDb::global().scoped(0); + let mut styles = Vec::new(); + let mut missing = std::collections::HashMap::new(); + let mut table = shape::StyleTable { styles: &mut styles, missing: &mut missing }; + let mut story = Story::new(StoryId(0)); + story.insert(0, text); + shape::shape_para( + &db, + &designcraft_doc::Styles::default(), + &story, + 0, + 0..text.len(), + &designcraft_doc::CharProps::default(), + shape::TypeEnv { auto_leading: 1.2, adv: Default::default(), glyph_fallback: true }, + &SubstCtx::default(), + &mut table, + &[], + &[], + &[], + (0, ""), + ) + .glyphs +} + +#[test] +fn paragraph_script_counts_a_drop_cap_but_not_a_generated_label() { + // The 禁則 gate reads the paragraph's own shaped glyphs. The drop cap has not been split off + // yet, so a CJK one still makes the paragraph CJK. + assert!(paragraph_is_cjk(&shape_for_script_test("漢abc"))); + // A generated list label is prepended after the gate, so it is not part of the paragraph. + let mut glyphs = shape_for_script_test("abc"); + assert!(!paragraph_is_cjk(&glyphs)); + let db = designcraft_fonts::FontDb::global().scoped(0); + let mut styles = Vec::new(); + let mut missing = std::collections::HashMap::new(); + let mut table = shape::StyleTable { styles: &mut styles, missing: &mut missing }; + let n = prepend_label( + &db, + &mut glyphs, + "第1章", + 0, + &designcraft_doc::CharProps::default(), + shape::TypeEnv { auto_leading: 1.2, adv: Default::default(), glyph_fallback: true }, + &mut table, + ); + assert!(n > 0); + // The label's glyphs are CJK, so a gate computed after prepend_label would flip the answer. + assert!(glyphs.iter().take(n).any(|g| is_cjk_char(g.ch))); +} + #[test] fn kinsoku_priority_modes_map_to_breaker_policies() { let mut pp = ParaProps::default(); From a28917ef3c4107e360e4c7657d734c44ca3c4d0d Mon Sep 17 00:00:00 2001 From: midasdf Date: Fri, 23 Oct 2026 01:37:14 +0900 Subject: [PATCH 006/322] fix(compose): classify a text variable's replacement as CJK MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit shape_segment keeps the source marker in Glyph::ch when it shapes a text variable, page number or cross-reference replacement, so a paragraph that shows CJK only through one of them was classified as non-CJK and lost its 禁則 priority. Inspect generated_text too: the paragraph is CJK when either the source character or any character of the replacement text is. Tests: designcraft-compose 367 passed, 1 ignored; the new regression (a variable marker plus Latin text) fails without the classifier change. cargo fmt --all -- --check passed. --- crates/compose/src/lib.rs | 5 +++-- crates/compose/src/tests.rs | 20 +++++++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 34ef24119..e5e2eb208 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -2189,9 +2189,10 @@ fn spacing_for(pp: &ParaProps, base_size: f64, cjk: bool) -> Spacing { /// Whether the paragraph's own shaped glyphs contain CJK text, the gate for its 禁則 priority. /// Called before `split_drop_cap` and `prepend_label`, so a drop cap counts and generated list -/// and story labels do not. +/// and story labels do not. A text variable or page number keeps its marker in [`Glyph::ch`], so +/// its replacement text is what the paragraph shows; inspect that too. fn paragraph_is_cjk(glyphs: &[Glyph]) -> bool { - glyphs.iter().any(|g| is_cjk_char(g.ch)) + glyphs.iter().any(|g| is_cjk_char(g.ch) || g.generated_text.as_deref().is_some_and(|text| text.chars().any(is_cjk_char))) } /// Is `c` CJK text (the scripts the 禁則 line-start/line-end rules are about): ideographs, kana, diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 009aab73d..b3881ba75 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5348,6 +5348,11 @@ fn supplementary_ideograph_paragraph_keeps_the_kinsoku_gate() { /// Shape `text` as a one-paragraph story with the default font and styles: the glyph list the /// composition classifies before `split_drop_cap` and `prepend_label`. fn shape_for_script_test(text: &str) -> Vec { + shape_for_script_test_with(text, &SubstCtx::default()) +} + +/// Same, with text variables resolved through `sub`. +fn shape_for_script_test_with(text: &str, sub: &SubstCtx) -> Vec { let db = designcraft_fonts::FontDb::global().scoped(0); let mut styles = Vec::new(); let mut missing = std::collections::HashMap::new(); @@ -5362,7 +5367,7 @@ fn shape_for_script_test(text: &str) -> Vec { 0..text.len(), &designcraft_doc::CharProps::default(), shape::TypeEnv { auto_leading: 1.2, adv: Default::default(), glyph_fallback: true }, - &SubstCtx::default(), + sub, &mut table, &[], &[], @@ -5398,6 +5403,19 @@ fn paragraph_script_counts_a_drop_cap_but_not_a_generated_label() { assert!(glyphs.iter().take(n).any(|g| is_cjk_char(g.ch))); } +#[test] +fn paragraph_script_reads_a_text_variable_replacement() { + // A text variable's glyphs keep the source marker in `ch`; the paragraph shows the replacement, + // so a CJK replacement makes it CJK text even though no source character is. + let marker = designcraft_doc::vars::var_char(0).expect("variable 0"); + let text = format!("{marker}abc"); + let sub = SubstCtx { vars: Arc::new(vec!["漢字".into()]), ..Default::default() }; + let glyphs = shape_for_script_test_with(&text, &sub); + assert!(!glyphs.iter().any(|g| is_cjk_char(g.ch)), "the source is only the marker and Latin text"); + assert!(glyphs.iter().any(|g| g.generated_text.as_deref().is_some_and(|t| t.chars().any(is_cjk_char)))); + assert!(paragraph_is_cjk(&glyphs), "the CJK replacement is the paragraph's text"); +} + #[test] fn kinsoku_priority_modes_map_to_breaker_policies() { let mut pp = ParaProps::default(); From b5196b933d7b16fd4f6e87622ef5930f436dd940 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 28 Oct 2026 18:36:37 +0500 Subject: [PATCH 007/322] test(cli): pin what the argument parser does today (photocraft#7071) The argument surface had no tests of its own, so the three bugs #7071 lists could come back without anything noticing. These pin what the parser does: help in all three spellings, an unknown command, the version, ` --help` for every subcommand, the options that take a value, the repeatable flags, a flag that takes no value leaving the next token alone, and a missing value naming its option. Carries the review fix: asking for help about a command nobody has is still an unknown command. usage_for fell back to the whole usage block when it described no such subcommand, so `bogus --help` printed it on stdout and exited 0, skipping the failure the test beside it asserts. It answers None instead -- the usage block names every subcommand, so no second list can drift from the match that dispatches them. Rebased onto the post-split main, on top of the rebased #1478. The CLI's tests live under tests/it/ now, so args.rs went there and is registered in tests/it/main.rs. One case needed updating rather than porting: this pinned that an automation root given twice was an error. Upstream has since made the roots repeatable (`...` in the usage), so every use adds a folder. The test now pins that -- which is what "what the parser does today" means -- and says so, rather than holding the parser to behaviour it has deliberately left behind. --- apps/designcraft-cli/src/main.rs | 11 +- apps/designcraft-cli/tests/it/args.rs | 354 ++++++++++++++++++++++++++ apps/designcraft-cli/tests/it/main.rs | 1 + 3 files changed, 363 insertions(+), 3 deletions(-) create mode 100644 apps/designcraft-cli/tests/it/args.rs diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 98c9b32d2..ea67f89b3 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -124,7 +124,11 @@ fn can_be_value(v: &str) -> bool { /// The usage lines for one subcommand, for ` --help`. Each line of [`USAGE`] names its /// subcommand, and the indented lines after it belong to it. -fn usage_for(sub: &str) -> String { +/// The part of [`USAGE`] that describes `sub`, or `None` when it describes no such subcommand -- +/// which is how ` --help` tells a real subcommand from a typo. Falling back to the whole +/// usage made `bogus --help` print it and succeed, bypassing the unknown-command failure (noted +/// in review). +fn usage_for(sub: &str) -> Option { let mut out = Vec::new(); let mut keep = false; for line in USAGE.lines() { @@ -136,7 +140,7 @@ fn usage_for(sub: &str) -> String { out.push(line); } } - if out.is_empty() { USAGE.to_string() } else { out.join("\n") } + (!out.is_empty()).then(|| out.join("\n")) } fn main() -> ExitCode { @@ -159,8 +163,9 @@ fn main() -> ExitCode { if let Some(sub) = args.first().map(String::as_str) && !matches!(sub, "--help" | "-h" | "help" | "script") && args[1..].iter().any(|a| a == "--help" || a == "-h") + && let Some(text) = usage_for(sub) { - outln!("{}", usage_for(sub)); + outln!("{text}"); return ExitCode::SUCCESS; } match args.first().map(String::as_str) { diff --git a/apps/designcraft-cli/tests/it/args.rs b/apps/designcraft-cli/tests/it/args.rs new file mode 100644 index 000000000..bbbde4867 --- /dev/null +++ b/apps/designcraft-cli/tests/it/args.rs @@ -0,0 +1,354 @@ +//! What the command line does with its arguments, pinned. +//! +//! Every assertion here was measured, not intended: these tests say what the parser does today, +//! including where that is odd (an unknown option taken as a filter, a `--opt=value` form that +//! only the automation roots have). They exist so that moving to a derived parser — the work +//! photocraft#7071 lists, which this parser needs too — changes the surface where that is the +//! point and nowhere else. +//! +//! They assert the exit code, which stream the output went to, and that an error names the +//! argument it is about. They do not assert wording, so a message can be improved without +//! editing a test, except in the few places where the wording *is* the behaviour and the test +//! says so. +//! +//! `tests/cli.rs` holds what the subcommands then do: exports, scripts, the MCP server. + +use std::process::{Command, Stdio}; + +/// `designcraft-cli` with stdin closed, so a subcommand that reads a script does not wait. +fn cli() -> Command { + let mut c = Command::new(env!("CARGO_BIN_EXE_designcraft-cli")); + c.stdin(Stdio::null()); + c +} + +/// What one invocation did. +struct Ran { + code: Option, + out: String, + err: String, +} + +fn run(args: &[&str]) -> Ran { + let out = cli().args(args).output().unwrap_or_else(|e| panic!("{args:?}: {e}")); + Ran { code: out.status.code(), out: String::from_utf8_lossy(&out.stdout).into_owned(), err: String::from_utf8_lossy(&out.stderr).into_owned() } +} + +impl Ran { + /// Succeeded, said nothing on stderr; gives back what it printed. + fn succeeded(self, what: &str) -> String { + assert_eq!(self.code, Some(0), "{what}: {:?}", self.err); + assert_eq!(self.err, "", "{what} wrote to stderr"); + self.out + } + + /// Failed with the usage exit code, said nothing on stdout; gives back the complaint. + fn failed(self, what: &str) -> String { + assert_eq!(self.code, Some(1), "{what}: expected a usage failure, got {:?} / {:?}", self.out, self.err); + assert_eq!(self.out, "", "{what} wrote to stdout"); + self.err + } +} + +/// A port with nothing listening on it, so `--connect` and `--port` fail the same way every time. +fn closed_port() -> String { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + drop(listener); + port.to_string() +} + +/// A directory of this test's own, removed when the test ends. +fn temp_dir(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("dc-args-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Every subcommand, in the order the usage block lists them. +const SUBCOMMANDS: [&str; 10] = ["run", "commands", "describe", "script", "app", "mcp", "perf", "bench", "validate-pdf", "links"]; + +#[test] +fn with_no_arguments_it_prints_the_usage_block_and_fails() { + let err = run(&[]).failed("no arguments"); + assert!(err.starts_with("usage: designcraft-cli run"), "{err:?}"); + // The usage block names every subcommand, which is how ` --help` finds its lines. + for sub in SUBCOMMANDS { + assert!(err.contains(&format!("designcraft-cli {sub}")), "usage names {sub}: {err:?}"); + } + // An empty argument is a command nobody has, not a request for help. + run(&[""]).failed("an empty argument"); +} + +#[test] +fn help_goes_to_stdout_and_succeeds_in_all_three_spellings() { + let long = run(&["--help"]).succeeded("--help"); + assert!(long.starts_with("usage: designcraft-cli run"), "{long:?}"); + // The community links are under the usage block, for someone who has nowhere else to ask. + assert!(long.contains("Community:") && long.contains("discord"), "{long:?}"); + for spelling in ["-h", "help"] { + assert_eq!(run(&[spelling]).succeeded(spelling), long, "{spelling} prints the same help"); + } +} + +#[test] +fn an_unknown_command_fails_with_the_same_text_on_stderr() { + let usage = run(&["--help"]).succeeded("--help"); + for unknown in ["bogus", "-x", "--nope", "Run"] { + let err = run(&[unknown]).failed(unknown); + assert_eq!(err, usage, "{unknown}: the same usage, on stderr"); + // Asking for help about a command nobody has is still that command: ` --help` + // answered with the whole usage block on stdout and succeeded, which skipped the + // unknown-command failure entirely (noted in review). + for spelling in ["--help", "-h"] { + let err = run(&[unknown, spelling]).failed(&format!("{unknown} {spelling}")); + assert_eq!(err, usage, "{unknown} {spelling}: the same usage, on stderr"); + } + } + // A real subcommand still answers about itself, and only about itself. + for sub in SUBCOMMANDS.iter().filter(|s| **s != "script") { + let text = run(&[sub, "--help"]).succeeded(sub); + assert!(text.contains(&format!("designcraft-cli {sub}")), "{sub} --help describes {sub}: {text:?}"); + assert_ne!(text, usage, "{sub} --help is about {sub}, not the whole usage block"); + } +} + +#[test] +fn the_version_is_the_crate_version() { + let expected = format!("designcraft-cli {}\n", env!("CARGO_PKG_VERSION")); + for spelling in ["--version", "-V", "version"] { + assert_eq!(run(&[spelling]).succeeded(spelling), expected, "{spelling}"); + } +} + +/// ` --help` asks about that subcommand. It answers from the usage block, on stdout, and +/// nothing else happens: no export is written, no port is dialled, no measurement is taken, and a +/// file named earlier in the same line is not opened or complained about (photocraft#423). +#[test] +fn every_subcommand_answers_help_without_running_anything() { + let dir = temp_dir("help"); + let png = dir.join("ran.png"); + let dead = closed_port(); + let cases: [(&str, Vec<&str>); 10] = [ + ("run", vec!["run", "--sample", "--export", png.to_str().unwrap()]), + ("commands", vec!["commands"]), + ("describe", vec!["describe", "file.open"]), + ("script", vec!["script", "no-such-script.dcs"]), + ("app", vec!["app", "--port", &dead, "document.list"]), + ("mcp", vec!["mcp", "--connect", &dead]), + ("perf", vec!["perf", "--pages", "1", "--runs", "1"]), + ("bench", vec!["bench", "no-such-document.designcraft"]), + ("validate-pdf", vec!["validate-pdf", "no-such-file.pdf"]), + ("links", vec!["links"]), + ]; + for (sub, args) in cases { + for flag in ["--help", "-h"] { + let mut args = args.clone(); + args.push(flag); + let what = format!("{sub} {flag}"); + let out = run(&args).succeeded(&what); + assert!(out.contains(&format!("designcraft-cli {sub}")), "{what} names it: {out:?}"); + assert!(!out.contains("unknown option"), "{what}: {out:?}"); + // None of the work the rest of the line asks for was done. + assert!(!png.exists(), "{what} exported a file"); + assert!(!out.contains("cannot connect") && !out.contains("render threads"), "{what}: {out:?}"); + assert!(!out.contains("No such file"), "{what}: {out:?}"); + } + } + // `script`'s own help is longer than one usage line: it documents the script syntax, which is + // otherwise only in `describe script.run` and the docs. + let out = run(&["script", "--help"]).succeeded("script --help"); + assert!(out.contains("Script text, one step per line"), "{out:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The subcommands that have options refuse an option they do not know, and name it. +#[test] +fn an_unknown_option_is_refused_by_name() { + let cases: [Vec<&str>; 5] = [ + vec!["run", "--nope"], + vec!["script", "-", "--nope"], + vec!["mcp", "--nope"], + vec!["perf", "--nope"], + vec!["bench", "f.designcraft", "--nope"], + ]; + for args in cases { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains("--nope"), "{args:?}: {err:?}"); + assert!(err.contains("unknown"), "{args:?}: {err:?}"); + } +} + +/// The subcommands whose argument is a word, not an option, take an unknown option as that word: +/// `commands --nope` filters the command list by `--nope` and finds nothing. Each of these would +/// be an error under the rule photocraft#7071 settles on; today they are not, and a change of +/// mind shows up here. +#[test] +fn the_subcommands_that_take_a_word_read_an_unknown_option_as_that_word() { + // A filter that matches no command: an empty list, successfully. + assert_eq!(run(&["commands", "--nope"]).succeeded("commands --nope").trim(), "[]"); + // A command id nobody has. + let err = run(&["describe", "--nope"]).failed("describe --nope"); + assert!(err.contains("no command `--nope`"), "{err:?}"); + // A path nobody has. + let err = run(&["validate-pdf", "--nope"]).failed("validate-pdf --nope"); + assert!(err.contains("--nope") && err.contains("No such file"), "{err:?}"); + // A method name for the running app, so the error is about reaching the app. + let dead = closed_port(); + let err = run(&["app", "--port", &dead, "--nope"]).failed("app --nope"); + assert!(err.contains("cannot connect"), "{err:?}"); + // And `links`, which takes nothing, ignores what it is given. + let out = run(&["links", "--nope"]).succeeded("links --nope"); + assert_eq!(out, run(&["links"]).succeeded("links")); +} + +/// There is no `--opt=value` form. The two automation roots are the exception: they have one, +/// because a folder whose name starts with `-` has no other way in there. +#[test] +fn only_the_automation_roots_have_an_opt_equals_value_form() { + let cases: [(&str, Vec<&str>); 3] = [ + ("--scale=2", vec!["run", "--scale=2", "--sample"]), + ("--pages=2", vec!["perf", "--pages=2"]), + ("--save=out.designcraft", vec!["script", "-", "--save=out.designcraft"]), + ]; + for (token, args) in cases { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains("unknown"), "{args:?}: {err:?}"); + // The whole token is named, `=value` and all, so it is clear what was not understood. + assert!(err.contains(token), "{args:?}: {err:?}"); + } + // The roots read the value after `=`: an empty one is refused as a folder, which is the + // parser having taken it rather than ignoring the form. + let err = run(&["mcp", "--automation-read-root="]).failed("empty root"); + assert!(err.contains("--automation-read-root") && err.contains("folder"), "{err:?}"); + // A root given more than once adds another folder, in either spelling, rather than the last + // one winning or the repeat being refused: the roots are repeatable (`...` in the usage), and + // `mcp_automation_roots_take_several_folders` covers what the extra folder grants. This PR + // first pinned the older behaviour, where a second root was an error; upstream has made them + // repeatable since, so what is pinned here is today's. + // + // Checked by what fails rather than by letting the server start: the stray token after the + // roots is the error, which shows both roots were taken. + for second in [vec!["--automation-read-root=b"], vec!["--automation-read-root", "b"]] { + let mut args = vec!["mcp", "--automation-read-root=a"]; + args.extend(second.iter().copied()); + args.push("stray"); + let err = run(&args).failed(&format!("{second:?}")); + assert!(err.contains("stray"), "the stray token is what fails: {err:?}"); + assert!(!err.contains("twice"), "a repeated root is not refused any more: {err:?}"); + } +} + +/// An option that needs a value and has none says which option, and nothing runs. +#[test] +fn a_missing_value_names_its_option() { + let dir = temp_dir("missing"); + let png = dir.join("out.png"); + let cases: [(&str, Vec<&str>); 9] = [ + ("--export", vec!["run", "--sample", "--export"]), + ("--in", vec!["run", "--in"]), + ("--all-pages", vec!["run", "--sample", "--all-pages"]), + // Before an export, too: the order of the options is nothing to judge until this one has + // a value, so it is not reported as an export it is not in front of. + ("--scale", vec!["run", "--sample", "--scale", "--export", png.to_str().unwrap()]), + ("--page", vec!["run", "--sample", "--page"]), + ("--save", vec!["script", "-", "--save"]), + ("--connect", vec!["script", "-", "--connect"]), + ("--port", vec!["app", "--port"]), + ("--pages", vec!["perf", "--pages"]), + ]; + for (option, args) in cases { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains(option), "{args:?} names {option}: {err:?}"); + assert!(err.contains("needs"), "{args:?}: {err:?}"); + } + assert!(!png.exists(), "nothing is exported"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// An option that takes no value does not swallow the token after it: that token is read as the +/// next argument, and refused if it is not one. +#[test] +fn a_flag_that_takes_no_value_leaves_the_next_token_alone() { + let err = run(&["run", "--sample", "extra", "--export", "out.png"]).failed("run --sample extra"); + assert!(err.contains("extra"), "{err:?}"); + let err = run(&["perf", "--strict", "3"]).failed("perf --strict 3"); + assert!(err.contains('3'), "{err:?}"); +} + +/// A value flag given twice keeps the last value. (The automation roots are the exception, above.) +#[test] +fn a_repeated_value_flag_keeps_the_last_value() { + let dir = temp_dir("repeat"); + let at = |args: &[&str], name: &str| -> Vec { + let path = dir.join(name); + let mut full: Vec<&str> = vec!["run", "--sample"]; + full.extend_from_slice(args); + let out = path.to_str().unwrap(); + full.extend(["--export", out]); + let ran = run(&full); + assert_eq!(ran.code, Some(0), "{full:?}: {:?}", ran.err); + std::fs::read(&path).unwrap() + }; + // `--scale`: the size of the image says which value was used. + let one = at(&[], "1.png"); + let three = at(&["--scale", "3"], "3.png"); + assert_eq!(at(&["--scale", "2", "--scale", "3"], "23.png"), three, "the last --scale won"); + assert_ne!(three, one, "and --scale 3 is not --scale 1"); + // `--page`: which page was exported says it. + let second = at(&["--page", "1"], "p1.png"); + assert_ne!(second, one, "page 1 of the sample is not page 0"); + assert_eq!(at(&["--page", "1", "--page", "0"], "p10.png"), one, "the last --page won"); + // `--connect` and `--port`: the address the error names says it. + let (a, b) = (closed_port(), closed_port()); + for args in [vec!["mcp", "--connect", &a, "--connect", &b], vec!["app", "--port", &a, "--port", &b, "document.list"]] { + let err = run(&args).failed(&format!("{args:?}")); + assert!(err.contains(&format!("127.0.0.1:{b}")), "{args:?} dialled the last port: {err:?}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + +/// The flags that are meant to repeat each take effect, in order. +#[test] +fn the_repeatable_flags_all_take_effect() { + let dir = temp_dir("each"); + let (a, b) = (dir.join("a.png"), dir.join("b.png")); + let ran = run(&[ + "run", + "--sample", + "--cmd", + "document.list", + "--cmd", + "document.list", + "--export", + a.to_str().unwrap(), + "--export", + b.to_str().unwrap(), + ]); + assert_eq!(ran.code, Some(0), "{:?}", ran.err); + // One result line per `--cmd`, in the order given. + let results: Vec<&str> = ran.out.lines().collect(); + assert_eq!(results.len(), 2, "{results:?}"); + assert_eq!(results[0], results[1]); + // And one file per `--export`. + assert_eq!(std::fs::read(&a).unwrap(), std::fs::read(&b).unwrap()); + assert_eq!(ran.err.lines().filter(|l| l.starts_with("wrote ")).count(), 2, "{:?}", ran.err); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A subcommand given nothing to do does nothing, quietly or with its own usage line. `run` with +/// no arguments is the one that says nothing at all: there is no document to act on and nothing +/// was asked of it. +#[test] +fn a_subcommand_with_nothing_to_do_says_so_or_says_nothing() { + assert_eq!(run(&["run"]).succeeded("run"), ""); + // `script` with no file reads stdin, which is closed here: an empty script, run. + let out = run(&["script"]).succeeded("script"); + assert!(out.contains("\"completed\": 0"), "{out:?}"); + // The two that need an argument print the usage line for themselves. + for sub in ["describe", "bench", "validate-pdf"] { + let err = run(&[sub]).failed(sub); + assert!(err.contains(&format!("designcraft-cli {sub}")), "{sub}: {err:?}"); + } +} diff --git a/apps/designcraft-cli/tests/it/main.rs b/apps/designcraft-cli/tests/it/main.rs index 26710c101..e8761f4e1 100644 --- a/apps/designcraft-cli/tests/it/main.rs +++ b/apps/designcraft-cli/tests/it/main.rs @@ -1 +1,2 @@ +mod args; mod cli; From 2b0d8a4c105ce1c3eac31d574f8fd999027cde44 Mon Sep 17 00:00:00 2001 From: Hamza Date: Thu, 29 Oct 2026 13:53:11 +0500 Subject: [PATCH 008/322] test(cli): don't assert the operating system's wording for a missing file Review caught a test that cannot pass on Windows: it asserted the error for `validate-pdf --nope` contains "No such file", which is the unix phrasing. Windows says "The system cannot find the file specified", so the assertion failed there even when the command refused the path correctly -- the same mistake as the `\\?\C:\` one on #1909, and in a test whose point is to run everywhere. It asserts the error names the path; `failed()` already checks the exit code and the stream. The companion check that a ` --help` run did not open a file now looks for either operating system's wording, so it catches that on Windows too rather than only on unix. --- apps/designcraft-cli/tests/it/args.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/designcraft-cli/tests/it/args.rs b/apps/designcraft-cli/tests/it/args.rs index bbbde4867..7c27a8e8e 100644 --- a/apps/designcraft-cli/tests/it/args.rs +++ b/apps/designcraft-cli/tests/it/args.rs @@ -153,7 +153,9 @@ fn every_subcommand_answers_help_without_running_anything() { // None of the work the rest of the line asks for was done. assert!(!png.exists(), "{what} exported a file"); assert!(!out.contains("cannot connect") && !out.contains("render threads"), "{what}: {out:?}"); - assert!(!out.contains("No such file"), "{what}: {out:?}"); + // Either operating system's wording, so this catches a file the help path opened on + // Windows as well as on unix. + assert!(!out.contains("No such file") && !out.contains("cannot find the file"), "{what}: {out:?}"); } } // `script`'s own help is longer than one usage line: it documents the script syntax, which is @@ -193,7 +195,11 @@ fn the_subcommands_that_take_a_word_read_an_unknown_option_as_that_word() { assert!(err.contains("no command `--nope`"), "{err:?}"); // A path nobody has. let err = run(&["validate-pdf", "--nope"]).failed("validate-pdf --nope"); - assert!(err.contains("--nope") && err.contains("No such file"), "{err:?}"); + // The error names the path. Not the operating system's wording for a missing file: Windows + // says "The system cannot find the file specified", so asserting the Unix phrasing failed + // there even when the command refused correctly (noted in review). `failed` already checks + // the exit code and the stream. + assert!(err.contains("--nope"), "{err:?}"); // A method name for the running app, so the error is about reaching the app. let dead = closed_port(); let err = run(&["app", "--port", &dead, "--nope"]).failed("app --nope"); From 8d17aa1100a35e3283508fc6c6483c2c005086f9 Mon Sep 17 00:00:00 2001 From: Hamza Date: Mon, 2 Nov 2026 16:02:59 +0500 Subject: [PATCH 009/322] test(cli): show that `--nope` reached the file system, not the parser The assertion was that the complaint names `--nope`, which a parser rejecting unknown options would do just as well -- so it did not pin the thing the test is named for (noted in review). `validate-pdf --nope` and `validate-pdf nope.pdf` are now compared with the name taken out, so the shape of the failure has to be the one an ordinary missing path gets. That holds the behaviour without asserting the operating system's wording for a missing file, which an earlier round of review rightly took out of here. Review suggested asserting the JSON report instead. There is none to assert: `validate-pdf --nope` fails at `std::fs::read`, before any check runs, and writes nothing to stdout -- which `failed` already requires. Controlled by adding `o if o.starts_with("--") => return Err(...)` to `validate_pdf`: left: "designcraft-cli: unknown option \n" right: "designcraft-cli: : No such file or directory (os error 2)\n" The old assertion passes against that left-hand side, since it names `--nope`. --- apps/designcraft-cli/tests/it/args.rs | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/apps/designcraft-cli/tests/it/args.rs b/apps/designcraft-cli/tests/it/args.rs index 7c27a8e8e..84a98c34a 100644 --- a/apps/designcraft-cli/tests/it/args.rs +++ b/apps/designcraft-cli/tests/it/args.rs @@ -193,13 +193,23 @@ fn the_subcommands_that_take_a_word_read_an_unknown_option_as_that_word() { // A command id nobody has. let err = run(&["describe", "--nope"]).failed("describe --nope"); assert!(err.contains("no command `--nope`"), "{err:?}"); - // A path nobody has. - let err = run(&["validate-pdf", "--nope"]).failed("validate-pdf --nope"); - // The error names the path. Not the operating system's wording for a missing file: Windows - // says "The system cannot find the file specified", so asserting the Unix phrasing failed - // there even when the command refused correctly (noted in review). `failed` already checks - // the exit code and the stream. - assert!(err.contains("--nope"), "{err:?}"); + // A path nobody has. `--nope` has to fail the way an ordinary missing path fails, because + // that is what shows it reached the file system as a path instead of being read as an + // option. Asserting only that the complaint names `--nope` does not show that: a parser that + // rejected unknown options would name it too (noted in review). + // + // So the two are compared with the name taken out. That holds the shape of the failure + // without asserting the operating system's wording for a missing file -- Windows says "The + // system cannot find the file specified" -- which an earlier round of review rightly took + // out of this test. `failed` already checks the exit code and that stdout stayed empty. + let as_option = run(&["validate-pdf", "--nope"]).failed("validate-pdf --nope"); + let as_path = run(&["validate-pdf", "nope.pdf"]).failed("validate-pdf nope.pdf"); + assert!(as_option.contains("--nope"), "{as_option:?}"); + assert_eq!( + as_option.replace("--nope", ""), + as_path.replace("nope.pdf", ""), + "`--nope` must fail as a missing path does, not as an option" + ); // A method name for the running app, so the error is about reaching the app. let dead = closed_port(); let err = run(&["app", "--port", &dead, "--nope"]).failed("app --nope"); From 4536e5d4cfc4397ea557b12b313b8f3bec3bea74 Mon Sep 17 00:00:00 2001 From: midasdf Date: Wed, 4 Nov 2026 08:46:04 +0900 Subject: [PATCH 010/322] Compose: match the CJK gate's Hangul set to the breaker's; drop the ROADMAP hunk --- ROADMAP.md | 3 +-- crates/compose/src/breaker.rs | 13 ++++++++---- crates/compose/src/lib.rs | 37 ++++++++++++++++++----------------- crates/compose/src/tests.rs | 10 ++++++++++ 4 files changed, 39 insertions(+), 24 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 883ca04f6..d88e8fc36 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -4,7 +4,7 @@ - 2026-10-23: placed-artwork layer options survive IDML and native round trips per placement, independently of shared assets. Unsupported visibility overrides are explicit import/preflight/PDF warnings; format 4 prevents older native readers from silently discarding them. Rendering parity is still open; see [graphic-layer-options.md](docs/graphic-layer-options.md). - FID1: PDF export normalizes mixed emitted gradient color spaces to RGB with an explicit warning; homogeneous device-space gradients retain their components. Linear/radial, midpoint, archival and print policies have synthetic regression coverage. -> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-01 · **Change:** minor (placed graphic layer-option preservation and explicit rendering warnings; previously minor, Compose: the JIS X 4051 禁則処理 push-in/push-out priorities are applied by both composers over CJK text — the empty default and Push In First compose as push-in-first as in InDesign's Japanese default, Push Out First, Push Out Only and adjustment-amount as their names say; Latin paragraphs are not biased; preflight reports only unknown values; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026 +> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-11-01 · **Change:** minor (placed graphic layer-option preservation and explicit rendering warnings; File ▸ Open Recent; .indd and .indt open through indd-utils; text threads by hand; the alpha gate waits on Primary Text Frame page fixes; Japanese print, import and table controls localized; Live corners (#186); Optical kerning from outlines (#181); window and menu quit confirmation; failed writes preserve live save and collection state; spring-loaded Zoom navigation; orderly native exit recovery; Pages panel parents; cancelable macOS Dock Quit; text stroke behind fill; Based on Parent; object styles carry effects; table anchors keep their own paragraphs; grouped HTML/EPUB reading order; Links source paths; XLSX cached cell values retain numeric precision and text) · **Target:** Adobe InDesign 2026 - AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it. - AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md. @@ -446,7 +446,6 @@ Newest first. - **2026-10-23** · File › File Info… edits the document's Document Title, Author, Description, Keywords, Copyright Notice and Copyright Info URL (`file.info`), and the document saves them. PDF export (PDF/X-4 and Print Booklet included) writes the title, author, description and keywords into the PDF's document information and XMP. EPUB export takes the title and author from File Info, and HTML export takes the title. A title or author given to the export replaces File Info's, and an empty Document Title leaves the document's name as the title. No readiness percentage change. - **2026-10-23** · Save and export dialogs (Save As, Save a Copy, Export PDF and the other exports, Package, libraries and books) start in the active document's folder once it has been saved, and for a document never saved in the folder of the last file saved or exported, remembered across sessions (#1653). A folder deleted since falls back to the system's choice. No readiness percentage change. - **2026-10-22** · Autoflow (Shift-click with the loaded text cursor, autoflow on Place, `text.thread {autoflow}`) fills the pages that follow before it adds any, as InDesign does: one frame per column on each following page, whatever else the page holds, then new pages at the end of the document. It inserted pages right after the story's last frame, in front of the document's own pages. Frames it set past the end of the text go again; a page the document had stays, and a page autoflow added only for such a frame goes with it. Smart Text Reflow of the primary text frame is unchanged. No readiness percentage change. -- **2026-10-22** · Compose: the JIS X 4051 禁則処理 push-in/push-out priorities are applied, not just preserved. Both composers bias the break candidates by the selected type over CJK text: push-in-first (the empty default and the UI's Push In First, as in InDesign's Japanese default) rates breaks that would stretch the line worse than ones it can reach by compressing, push-out-first the other way, push-out-only leaves no compression at the line end, and adjustment-amount takes the smallest adjustment. Latin paragraphs are not biased by the default. New regressions pin the default = push-in-first, the push-out-only line-end fits, the mode mapping and the Latin non-bias; `docs/cjk-typography.md` now lists the modes as implemented and preflight reports only unknown values. No readiness percentage change. - **2026-10-18** · German text hyphenates using the MIT-licensed 2006 reform patterns (`hyph-de-1996.tex`) through `hypher`. Explicit 2006 names and plain/2006 locale codes reach both composers; traditional and unknown spelling variants stay unhyphenated. Tests cover this distinction, umlauts, ß, compounds, reformed ck/st breaks and paragraph limits. Six of InDesign's ~40 hyphenation languages. No readiness percentage change. - **2026-10-16** · Edit › Keyboard Shortcuts imports a set saved by InDesign's Show Set (.txt, Windows or Mac key names, UTF-8 or UTF-16): matched commands take its Default shortcuts or lose theirs, other commands give up keys it takes, and a report lists what it changed and the items it could not match (`window.importShortcuts`, #1180). Tool keys stay fixed. No readiness percentage change. - **2026-10-23** · Translations: a missing string shows in English and fails no test; `cargo xtask i18n-report`, run by `cargo xtask ci`, prints the missing strings per language. Tests keep duplicate-key and placeholder checks and the language mechanics (lookup, context captions, plural captions, right-to-left). No readiness percentage change. diff --git a/crates/compose/src/breaker.rs b/crates/compose/src/breaker.rs index 254b2c6b0..2196de58b 100644 --- a/crates/compose/src/breaker.rs +++ b/crates/compose/src/breaker.rs @@ -286,13 +286,18 @@ fn kinsoku_allows(a: char, b: char) -> bool { !NO_START.contains(b) && !NO_END.contains(a) } +/// Hangul: Jamo, compatibility Jamo, the syllables, and Jamo Extended-A/B. Shared with the +/// paragraph's CJK gate so the two classifications cannot drift apart. +pub(crate) fn is_hangul(c: char) -> bool { + matches!(c as u32, 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF) +} + /// Hangul, and Han ideographs (hanja) in Korean text: Korean is set word by word (KLREQ), so /// these letters break like Western ones, at spaces. fn korean_letter(g: &Glyph) -> bool { - let c = g.ch as u32; - let hangul = matches!(c, 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF); - let han = matches!(c, 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0x20000..=0x3FFFF); - hangul || (han && g.lang.is_some_and(|t| designcraft_doc::language_subtag(t) == "ko")) + let c = g.ch; + let han = matches!(c as u32, 0x3400..=0x4DBF | 0x4E00..=0x9FFF | 0xF900..=0xFAFF | 0x20000..=0x3FFFF); + is_hangul(c) || (han && g.lang.is_some_and(|t| designcraft_doc::language_subtag(t) == "ko")) } /// Is the place between glyphs `a` and `b` one where CJK text may break (next to an ideograph, kana diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index e9e82add2..3fe58a550 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -3407,24 +3407,25 @@ fn paragraph_is_cjk(glyphs: &[Glyph]) -> bool { /// Is `c` CJK text (the scripts the 禁則 line-start/line-end rules are about): ideographs, kana, /// CJK punctuation and full/half-width forms, bopomofo, Hangul. fn is_cjk_char(c: char) -> bool { - matches!( - c as u32, - 0x1100..=0x11FF - | 0x2E80..=0x2FFF - | 0x3000..=0x30FF - | 0x3100..=0x318F - | 0x3190..=0x33FF - | 0x3400..=0x4DBF - | 0x4E00..=0x9FFF - | 0xA000..=0xA4CF - | 0xAC00..=0xD7AF - | 0xF900..=0xFAFF - | 0xFE30..=0xFE4F - | 0xFF00..=0xFFEF - // Extension B 以降 (U+20000..)。breaker の Han の判定と同じ範囲にして、 - // 補助面だけの段落でも禁則の指定が効くようにする - | 0x20000..=0x3FFFF - ) + // Hangul comes from the breaker's classification (Jamo including Extended-A/B, syllables), + // so the two sets agree. Bopomofo is 0x3100..=0x312F; 0x3130..=0x318F is Hangul. + breaker::is_hangul(c) + || matches!( + c as u32, + 0x2E80..=0x2FFF + | 0x3000..=0x30FF + | 0x3100..=0x312F + | 0x3190..=0x33FF + | 0x3400..=0x4DBF + | 0x4E00..=0x9FFF + | 0xA000..=0xA4CF + | 0xF900..=0xFAFF + | 0xFE30..=0xFE4F + | 0xFF00..=0xFFEF + // Extension B and later (U+20000..): the same range as the breaker's Han check, + // so the kinsoku settings apply to a paragraph of supplementary-plane text alone. + | 0x20000..=0x3FFFF + ) } /// Desired word spacing, letter spacing and glyph scaling apply to every line (any alignment). diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 156c37a75..1e8d77887 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -5888,6 +5888,16 @@ fn supplementary_ideograph_paragraph_keeps_the_kinsoku_gate() { assert!(!is_cjk_char('A')); } +#[test] +fn hangul_jamo_extended_blocks_count_as_cjk() { + // `is_cjk_char` takes Hangul from the breaker's classification, so the syllables and the + // Jamo Extended-A/B blocks count as well: a Hangul-only paragraph keeps its 禁則 priority. + for c in ['\u{A960}', '\u{A97F}', '\u{D7B0}', '\u{D7FF}'] { + assert!(is_cjk_char(c), "U+{:04X} is Hangul", c as u32); + } + assert!(is_cjk_char('\u{3105}'), "bopomofo is still CJK"); +} + /// Shape `text` as a one-paragraph story with the default font and styles: the glyph list the /// composition classifies before `split_drop_cap` and `prepend_label`. fn shape_for_script_test(text: &str) -> Vec { From d890289a92be8cbb60a0bd20c4b20b85a74b568b Mon Sep 17 00:00:00 2001 From: texjer Date: Tue, 3 Nov 2026 21:43:44 -0500 Subject: [PATCH 011/322] Place: several images load the place cursor, with a thumbnail, count and grid MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Split out of #2073. Port of #1307, #1392 (grid) and #1432 (thumbnail and count). - File › Place takes several files; images load the place cursor in the order chosen (`place.load` `files`, `append`), after the ones it holds. A multi-page PDF or an alert stops the batch, and a file that can't be placed returns its error to `app.placeDialog`. - Each click places the next image; arrow keys while dragging lay out a grid (`place.grid`) and are handled even at a limit; Escape unloads the rest (`place.cancel`). Undo of a loaded image's asset cancels the queue. - The cursor shows how many images are loaded. - On the web, Place picks several files and the inbox loads consecutive images for the same document as one batch. --- ROADMAP.md | 1 + apps/designcraft-web/src/web.rs | 15 +- crates/engine/src/cmd/file/place.rs | 221 ++++++++++++++++-- crates/engine/src/cmd/file/registry.rs | 21 +- crates/engine/src/lib.rs | 9 + crates/engine/src/tests.rs | 117 ++++++++++ crates/engine/src/tooling.rs | 1 + crates/tools/src/nav.rs | 75 +++++- crates/tools/src/tests.rs | 17 ++ crates/ui-egui/src/app/file_dialogs.rs | 40 ++++ crates/ui-egui/src/app/files.rs | 267 ++++++++++++++++++++-- crates/ui-egui/src/canvas.rs | 2 + crates/ui-egui/src/canvas/place_cursor.rs | 34 +++ crates/ui-egui/src/i18n/ka.rs | 2 + crates/ui-egui/src/i18n/table.rs | 20 ++ crates/ui-egui/src/menus/run.rs | 15 +- crates/ui-egui/src/menus/ui_commands.rs | 7 +- docs/multi-image-placement.md | 26 +++ 18 files changed, 836 insertions(+), 54 deletions(-) create mode 100644 crates/ui-egui/src/canvas/place_cursor.rs create mode 100644 docs/multi-image-placement.md diff --git a/ROADMAP.md b/ROADMAP.md index a13912f7c..57c143340 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -405,6 +405,7 @@ Newest first. - **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change. - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. +- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). - **2026-10-29** · Inserting text with many returns no longer takes time that grows with their square (part of #1588): each return copied its paragraph's format with its own insert, moving every format after it. Splitting 20,000 returns into paragraphs took 15.8 s; placing a text file of them now takes 0.2 s, and one of a million returns 5.5 s. No readiness percentage change. diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 19bc3a122..8b23ef6b7 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -402,11 +402,18 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services { rfd::AsyncFileDialog::new().add_filter("DesignCraft, IDML or InDesign", DOC_EXTS) }; wasm_bindgen_futures::spawn_local(async move { - let Some(file) = dialog.pick_file().await else { - return; + // Place takes several files, loaded into the place cursor in the order chosen. + let handles = if request.purpose == "place" { + dialog.pick_files().await.unwrap_or_default() + } else { + dialog.pick_file().await.into_iter().collect() }; - let bytes = file.read().await; - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name: file.file_name(), bytes }); + let mut files = Vec::with_capacity(handles.len()); + for file in handles { + let bytes = file.read().await; + files.push(ImportedFile { request: request.clone(), name: file.file_name(), bytes }); + } + inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); ctx.request_repaint(); }); })), diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index a3ae11df1..ba9e0827a 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -116,7 +116,7 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { - return load_cursor(s, asset, (bw, bh)); + return load_cursor(s, asset, (bw, bh), p.get("append").and_then(Value::as_bool) == Some(true)); } s.edit(|d, sel| { let fresh = AssetId(d.alloc()); @@ -235,35 +235,96 @@ pub(crate) fn validate_placement(size: (f64, f64), frame: Rect, xf: Affine, comm Ok(()) } +/// Decode and validate the complete batch before replacing the placement cursor. pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { - let (bytes, name, link) = read_source(p)?; - let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?; - let natural = eps_size(&bytes, "place.load")?.or_else(|| designcraft_render::natural_size(&bytes, 0)).unwrap_or((pw as f64, ph as f64)); - let mime = designcraft_render::image_mime(&bytes).to_string(); - let asset = Asset { name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() }; - load_cursor(s, asset, natural) + let append = p.get("append").and_then(Value::as_bool) == Some(true); + if p.get("files").is_none() { + let (bytes, name, link) = read_source(p)?; + let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", "unsupported or corrupt image"))?; + let natural = eps_size(&bytes, "place.load")?.or_else(|| designcraft_render::natural_size(&bytes, 0)).unwrap_or((pw as f64, ph as f64)); + let mime = designcraft_render::image_mime(&bytes).to_string(); + let asset = Asset { name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() }; + return load_cursor(s, asset, natural, append); + } + let sources = p.get("files").and_then(Value::as_array).ok_or_else(|| bad("place.load", "files must be an array"))?; + if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES { + return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images"))); + } + let mut images = Vec::with_capacity(sources.len()); + for source in sources { + let (bytes, name, link) = read_source(source)?; + let (pw, ph) = designcraft_render::image_size(&bytes).ok_or_else(|| bad("place.load", format!("unsupported or corrupt image: {name}")))?; + let size = eps_size(&bytes, "place.load")?.or_else(|| designcraft_render::natural_size(&bytes, 0)).unwrap_or((pw as f64, ph as f64)); + validate_placement(size, Rect::new(0.0, 0.0, size.0, size.1), Affine::IDENTITY, "place.load")?; + let mime = designcraft_render::image_mime(&bytes).to_string(); + images.push((Asset { name, mime, link, data: Arc::new(bytes), pixels: Some((pw, ph)), ..Default::default() }, size)); + } + let queue = s.edit(|d, _| { + let mut queue = std::collections::VecDeque::with_capacity(images.len()); + for (mut asset, size) in images { + asset.id = AssetId(d.alloc()); + queue.push_back(crate::LoadedGraphic { asset: d.add_asset(asset), size }); + } + Ok(queue) + })?; + if append && s.loaded.is_some() { + s.loaded_queue.extend(queue); + } else { + s.loaded_queue = queue; + s.loaded = s.loaded_queue.pop_front(); + } + s.set_tool("placeGun"); + Ok(json!({"remaining": loaded_count(s), "loaded": true})) } -/// Adds `asset` to the document (with a fresh id) and loads it into the place cursor. -fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64)) -> Result { +/// Most images one `place.load` takes. +const MAX_LOADED_IMAGES: usize = 1000; + +/// How many images the place cursor holds: the current one and those queued after it. +fn loaded_count(s: &Session) -> usize { + s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some())) +} + +/// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with +/// `append` and an image already loaded, queued after it). +fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result { let name = asset.name.clone(); let (pw, ph) = asset.pixels.unwrap_or_default(); let aid = s.edit(|d, _| { asset.id = AssetId(d.alloc()); Ok(d.add_asset(asset)) })?; - s.loaded = Some(crate::LoadedGraphic { asset: aid, size }); + let image = crate::LoadedGraphic { asset: aid, size }; + if append && s.loaded.is_some() { + s.loaded_queue.push_back(image); + } else { + s.loaded_queue.clear(); + s.loaded = Some(image); + } s.set_tool("placeGun"); Ok(json!({"asset": aid.0, "name": name, "width": pw, "height": ph, "loaded": true})) } -pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { - let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?; - // Undo can remove the loaded graphic's asset. - if !s.doc()?.doc.assets.contains_key(&aid) { - s.loaded = None; - return Err(bad("place.drop", "the loaded graphic is no longer in the document")); +/// Cancel every pending image if Undo removed an asset used by the cursor. +fn validate_place_cursor(s: &mut Session, command: &str) -> Result<()> { + // An empty cursor is its own error, and leaves the tool as it is. + if s.loaded.is_none() { + return Err(bad(command, "nothing loaded in the place cursor")); } + let valid = s.loaded.iter().chain(s.loaded_queue.iter()).all(|image| s.doc().is_ok_and(|d| d.doc.assets.contains_key(&image.asset))); + if !valid { + s.loaded = None; + s.loaded_queue.clear(); + s.set_tool("selection"); + return Err(bad(command, "the loaded graphic is no longer in the document")); + } + Ok(()) +} + +/// Place the current image and advance the cursor only after success. +pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { + validate_place_cursor(s, "place.drop")?; + let crate::LoadedGraphic { asset: aid, size: (nw, nh) } = s.loaded.ok_or_else(|| bad("place.drop", "nothing loaded in the place cursor"))?; let sr = crate::cmd::spread_param(p, "place.drop")?; let lid = s.doc()?.active_layer; let frame = crate::cmd::id_param(p, "frame"); @@ -321,11 +382,121 @@ pub(super) fn place_drop(s: &mut Session, p: &Value) -> Result { *sel = Selection::items(vec![id]); Ok(json!({"id": id.0})) })?; - s.loaded = None; - s.set_tool("selection"); + advance_place_cursor(s); Ok(r) } +/// Advance in file order, returning to selection when the queue is exhausted. +fn advance_place_cursor(s: &mut Session) { + s.loaded = s.loaded_queue.pop_front(); + if s.loaded.is_none() { + s.set_tool("selection"); + } +} + +/// Validate bounded grid dimensions and a finite nonnegative gutter. +fn grid_dimensions(p: &Value, command: &str, default_columns: usize, default_rows: usize) -> Result<(usize, usize, f64)> { + let dimension = |key, default| -> Result { + match p.get(key) { + None => Ok(default), + Some(v) => v + .as_u64() + .filter(|n| (1..=100).contains(n)) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| bad(command, "rows and columns must be integers between 1 and 100")), + } + }; + let gutter = crate::cmd::f64_or(p, "gutter", 6.0); + if !gutter.is_finite() || gutter < 0.0 { + return Err(bad(command, "gutter must be finite and nonnegative")); + } + Ok((dimension("columns", default_columns)?, dimension("rows", default_rows)?, gutter)) +} + +/// Calculate row-major cells, rejecting gutters that leave no usable space. +fn grid_cells(rect: Rect, columns: usize, rows: usize, gutter: f64, command: &str) -> Result> { + let (columns, rows) = (columns.max(1), rows.max(1)); + let w = (rect.width() - gutter * columns.saturating_sub(1) as f64) / columns as f64; + let h = (rect.height() - gutter * rows.saturating_sub(1) as f64) / rows as f64; + if ![rect.x0, rect.y0, rect.x1, rect.y1, w, h].iter().all(|v| v.is_finite()) || w <= 0.0 || h <= 0.0 { + return Err(bad(command, "the grid area is too small for its rows, columns and gutter")); + } + Ok((0..rows) + .flat_map(|row| { + (0..columns).map(move |column| { + let x = rect.x0 + column as f64 * (w + gutter); + let y = rect.y0 + row as f64 * (h + gutter); + Rect::new(x, y, x + w, y + h) + }) + }) + .collect()) +} + +/// Insert a proportionally fitted image into one grid cell. +fn insert_grid_image( + d: &mut designcraft_doc::Document, + spread: designcraft_doc::SpreadRef, + layer: designcraft_doc::LayerId, + image: crate::LoadedGraphic, + rect: Rect, + command: &str, +) -> Result { + let crate::LoadedGraphic { asset, size: (nw, nh) } = image; + if !d.assets.contains_key(&asset) { + return Err(bad(command, "a loaded image is no longer in the document")); + } + let k = (rect.width() / nw).min(rect.height() / nh); + let xf = Affine::translate((rect.x0 + (rect.width() - nw * k) / 2.0, rect.y0 + (rect.height() - nh * k) / 2.0)) * Affine::scale(k); + validate_placement((nw, nh), rect, xf, command)?; + let id = ItemId(d.alloc()); + let mut item = Item::new(id, layer, Shape::Rectangle, shapes::rectangle(rect)); + item.object_style = d.styles.default_graphic_frame.clone(); + if let Some(effects) = d.styles.object_effects(&item.object_style) { + item.effects = effects.clone(); + } + item.content = Content::Graphic(Graphic { + layer_options: None, + asset, + size: (nw, nh), + xf, + auto_fit: designcraft_doc::Fitting::FitProportionally, + fit_align: 4, + crop: [0.0; 4], + clip: None, + wrap: Default::default(), + fill: Default::default(), + }); + d.insert_item(spread, item, None)?; + Ok(id) +} + +/// Place a row-major grid as one undoable edit. +pub(super) fn place_grid(s: &mut Session, p: &Value) -> Result { + const ID: &str = "place.grid"; + validate_place_cursor(s, ID)?; + let (columns, rows, gutter) = grid_dimensions(p, ID, 1, 1)?; + let rect = crate::cmd::rect_param(p, "rect").ok_or_else(|| bad(ID, "missing rect"))?; + let cells = grid_cells(rect, columns, rows, gutter, ID)?; + let images: Vec<_> = s.loaded.iter().chain(s.loaded_queue.iter()).copied().take(cells.len()).collect(); + if images.is_empty() { + return Err(bad(ID, "nothing loaded in the place cursor")); + } + let layer = s.doc()?.active_layer; + let spread = crate::cmd::spread_param(p, ID)?; + let ids = s.edit(|d, sel| { + let mut ids = Vec::with_capacity(images.len()); + for (image, rect) in images.iter().zip(cells) { + ids.push(insert_grid_image(d, spread, layer, *image, rect, ID)?); + } + *sel = Selection::items(ids.clone()); + Ok(ids) + })?; + for _ in &ids { + advance_place_cursor(s); + } + Ok(json!({"ids": ids.iter().map(|id| id.0).collect::>(), "remaining": loaded_count(s)})) +} + /// File › Place of an IDML or DesignCraft document: the objects of one page (`layoutPage`, /// 1-based) grouped, top-left at x/y (default: the source position on the first page). fn place_layout_page(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) -> Result { @@ -395,6 +566,20 @@ pub(super) mod image_place_tests { Ok(file) } + /// With nothing in the place cursor, placing says so and leaves the tool as it is (the + /// cursor's graphic gone from the document is another error). + #[test] + fn an_empty_place_cursor_says_so_and_keeps_the_tool() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.set_tool("rectangleFrame"); + for (cmd, p) in [("place.drop", json!({"x": 10, "y": 10})), ("place.grid", json!({"rect": [0, 0, 100, 100]}))] { + let e = s.execute(cmd, &p).unwrap_err().to_string(); + assert!(e.contains("nothing loaded"), "{cmd}: {e}"); + assert_eq!(s.tool_id(), "rectangleFrame", "{cmd}"); + } + } + #[test] fn consecutive_path_placements_create_distinct_graphics() { let images = [image_file_with_color(30).unwrap(), image_file_with_color(31).unwrap(), image_file_with_color(32).unwrap()]; diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index c1f522956..57aa1a5a6 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -3,7 +3,7 @@ use super::EngineError; use super::bytes::{base64_encode, to_bytes, to_bytes_with_preview, with_document_extension}; use super::new::{file_new, file_sample, save_preset}; use super::open::{file_open, file_open_bytes, file_open_recent, has_recent, recent_entry}; -use super::place::{file_place, place_drop, place_load, read_source}; +use super::place::{file_place, place_drop, place_grid, place_load, read_source}; use super::save::{FolderAccess, can_revert, file_revert, file_save, recovery_dir}; use super::snippets::{snippet_export, snippet_place}; use super::{CommandSpec, PRESETS, Value, always, bad, cmd, has_doc, json, ok, str_param}; @@ -123,17 +123,32 @@ pub fn specs() -> Vec { "Load Place Cursor", [], None, - "{path | base64, name?} — load a graphic into the place cursor (then click/drag with the placeGun tool)", + "{path | base64, name?, files?: [{path | base64, name?}], append? (keep the images already loaded and queue these after them)} — load up to 1000 images into the place cursor, in order (then click/drag with the placeGun tool)", has_doc, place_load ), cmd!("place.drop", "Place Loaded Graphic", [], None, "{spread?, x, y, rect?: [x0,y0,x1,y1], frame?: id}", has_doc, place_drop), + cmd!( + "place.grid", + "Place Image Grid", + [], + None, + "{spread?, rect: [x0,y0,x1,y1], columns?: 1, rows?: 1, gutter?: 6} — place queued images in row order", + has_doc, + place_grid + ), + cmd!(noundo "place.cancel", "Cancel Image Placement", [], None, "{}", has_doc, |s, _| { + s.loaded = None; + s.loaded_queue.clear(); + s.set_tool("selection"); + ok() + }), cmd!( "file.place", "Place…", ["File"], Some("Cmd+D"), - "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), height? (video/audio), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor? (with no frame to fill and no x/y, an image loads into the place cursor, as File › Place), layoutPage?: n (IDML / .designcraft: that page's objects as a group), page?, rect?: [x0,y0,x1,y1] (text: a new frame there), autoflow? (threads one frame per page column from the first frame on, adding pages until the text fits), removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link? (keep the file linked in the Links panel; default: the linkTextFiles preference)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect`", + "{path?|base64?, name?, frame?: id (place into), spread?, x?, y?, width?: finite number > 0 (null: absent), height? (video/audio), pdfPage?: n (1-based, Image Import Options), pdfCrop?: crop|art|trim|bleed|media|contentVisible|contentAll (the box the graphic shows; `width` is the whole page's), loadCursor? (with no frame to fill and no x/y, an image loads into the place cursor, as File › Place), append? (with loadCursor: queue the image after those already loaded instead of replacing them), layoutPage?: n (IDML / .designcraft: that page's objects as a group), page?, rect?: [x0,y0,x1,y1] (text: a new frame there), autoflow? (threads one frame per page column from the first frame on, adding pages until the text fits), removeStyles?, styleMap?: {imported name: document style}, styleConflicts?: useExisting|redefine|autoRename, link? (keep the file linked in the Links panel; default: the linkTextFiles preference)} — places an image into `frame` when given; otherwise any explicit x/y/spread/width creates a new frame; otherwise uses the selected empty or graphic frame, or creates a new frame; text files (.txt, .docx, .rtf, .md) and Excel workbooks (.xlsx, as a table) go into the insertion point, the selected frame or a new frame on `page`/`rect`", has_doc, file_place ), diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 19c50b7c0..397be3203 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -411,6 +411,8 @@ pub struct Session { pub ui_requests: Vec, /// Graphic loaded in the place cursor. pub loaded: Option, + /// Remaining graphics, in source-selection order, after `loaded`. + pub loaded_queue: std::collections::VecDeque, pub(crate) untitled: u32, /// Transforms applied to the current selection, oldest first (Transform Again / Sequence /// Again), with the selection they were applied to and whether the last one came from a @@ -474,6 +476,7 @@ impl Session { image_link_checks: Default::default(), ui_requests: vec![], loaded: None, + loaded_queue: Default::default(), transforms: Default::default(), text_drag: false, text_unit: None, @@ -549,6 +552,8 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); + self.loaded = None; + self.loaded_queue.clear(); self.active = Some(i); } } @@ -558,6 +563,8 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); + self.loaded = None; + self.loaded_queue.clear(); self.docs.push(d); self.active = Some(self.docs.len() - 1); self.docs.len() - 1 @@ -580,6 +587,8 @@ impl Session { recovery::discard_document(self, i, recovery_dir.as_deref()); } if i < self.docs.len() { + self.loaded = None; + self.loaded_queue.clear(); self.reset_find_scope(); self.docs.remove(i); self.active = if self.docs.is_empty() { None } else { Some(i.min(self.docs.len() - 1)) }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 7cdcd5e02..564e42605 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2010,6 +2010,123 @@ fn direct_selection_on_a_selected_frame_deletes_only_its_image() { assert!(st.selection.content && st.selection.items == [designcraft_doc::ItemId(holder)], "the pasted-in items are selected: {:?}", st.selection); } +fn load_test_images(s: &mut Session, count: usize) { + let sources: Vec<_> = (0..count) + .map(|i| { + let png = designcraft_render::Rendered { width: 40, height: 20, pixels: vec![(i % 255) as u8; 40 * 20 * 4] }.to_png(); + json!({"base64": cmd::base64_encode(&png), "name": format!("{i}.png")}) + }) + .collect(); + s.execute("place.load", &json!({"files": sources})).unwrap(); +} + +#[test] +fn image_queue_places_in_order_and_retains_remainder() { + let mut s = session(); + load_test_images(&mut s, 5); + let first = s.loaded.unwrap().asset; + s.execute("place.drop", &json!({"x": 10, "y": 20})).unwrap(); + assert_eq!(s.tool_id(), "placeGun"); + let item = s.doc().unwrap().doc.spreads[0].items.last().unwrap(); + assert!(matches!(&item.content, designcraft_doc::Content::Graphic(g) if g.asset == first)); + let r = s.execute("place.grid", &json!({"rect": [0, 0, 206, 50], "columns": 2, "rows": 1})).unwrap(); + assert_eq!(r["remaining"], 2); + let id = designcraft_doc::ItemId(r["ids"][1].as_u64().unwrap()); + let item = s.doc().unwrap().doc.item(id).unwrap(); + assert_eq!(item.bounds(), designcraft_geom::Rect::new(106.0, 0.0, 206.0, 50.0)); + if let designcraft_doc::Content::Graphic(g) = &item.content { + assert_eq!(s.doc().unwrap().doc.assets[&g.asset].name, "2.png"); + } else { + panic!("expected graphic"); + } + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.doc().unwrap().doc.item(id).is_none(), "the whole grid is one undo step"); + s.execute("place.cancel", &json!({})).unwrap(); + assert!(s.loaded.is_none() && s.loaded_queue.is_empty()); + assert_eq!(s.tool_id(), "selection"); +} + +#[test] +fn image_grid_and_load_fail_atomically() { + let mut s = session(); + load_test_images(&mut s, 3); + let before = s.doc().unwrap().doc.clone(); + let first = s.loaded.unwrap().asset; + assert!(s.execute("place.load", &json!({"files": [{"base64": "bad"}]})).is_err()); + assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + assert_eq!(s.loaded.unwrap().asset, first); + for params in [json!({"columns": 0}), json!({"columns": 101}), json!({"rows": 1.5}), json!({"gutter": -1}), json!({"columns": 3, "gutter": 1000})] + { + let mut p = params; + p["rect"] = json!([0, 0, 100, 100]); + assert!(s.execute("place.grid", &p).is_err()); + assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + assert_eq!(s.loaded_queue.len(), 2); + } +} + +#[test] +fn place_drag_arrows_make_three_by_four_grid_and_escape_cancels() { + use designcraft_tools::{Mods, PointerEvent, PointerKind, ToolKey}; + let mut s = session(); + load_test_images(&mut s, 13); + let v = ViewInfo::at_zoom(1.0); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + for key in [ToolKey::Right, ToolKey::Right, ToolKey::Up, ToolKey::Up, ToolKey::Up] { + s.tool_key(key, Mods::default(), v).unwrap(); + } + s.pointer(&PointerEvent::new(PointerKind::Drag, 500.0, 600.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 500.0, 600.0), v).unwrap(); + assert_eq!(s.doc().unwrap().doc.spreads[0].items.len(), 12); + assert!(s.loaded.is_some() && s.loaded_queue.is_empty()); + s.tool_key(ToolKey::Escape, Mods::default(), v).unwrap(); + assert!(s.loaded.is_none()); +} + +/// With several images loaded, a release under the drag threshold is still a click: arrows set +/// no grid then, and the next queued image lands at actual size where the press was. +#[test] +fn a_place_click_with_a_queue_places_the_next_image_without_a_grid() { + use designcraft_tools::{Cursor, Mods, Overlay, PointerEvent, PointerKind, ToolKey}; + let mut s = session(); + load_test_images(&mut s, 3); + let v = ViewInfo::at_zoom(1.0); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 500.0), v).unwrap(); + s.tool_key(ToolKey::Right, Mods::default(), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 101.0, 501.0), v).unwrap(); + assert!(s.overlays(v).is_empty(), "no frame or grid under the threshold"); + assert_eq!(s.cursor(designcraft_geom::Point::new(101.0, 501.0), Mods::default(), v), Cursor::LoadedGraphic); + s.pointer(&PointerEvent::new(PointerKind::Up, 101.0, 501.0), v).unwrap(); + let items = &s.doc().unwrap().doc.spreads[0].items; + assert_eq!(items.len(), 1); + assert_eq!(items[0].bounds(), designcraft_geom::Rect::new(100.0, 500.0, 140.0, 520.0), "actual size at the press"); + assert_eq!(s.loaded_queue.len(), 1, "the next image is loaded"); + // Past the threshold the arrows' grid shows, one cell per column. + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap(); + s.tool_key(ToolKey::Right, Mods::default(), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 306.0, 150.0), v).unwrap(); + assert_eq!(s.overlays(v).iter().filter(|o| matches!(o, Overlay::Marquee(_))).count(), 2); + assert_eq!(s.cursor(designcraft_geom::Point::new(306.0, 150.0), Mods::default(), v), Cursor::Crosshair); +} + +#[test] +fn undoing_loaded_assets_cancels_every_placement_cursor() { + for command in ["place.drop", "place.grid"] { + let mut s = session(); + load_test_images(&mut s, 3); + s.execute("edit.undo", &json!({})).unwrap(); + let before = s.doc().unwrap().doc.clone(); + let params = json!({"rect": [0, 0, 200, 200]}); + assert!(s.execute(command, ¶ms).is_err(), "{command}"); + assert!(s.loaded.is_none(), "{command}"); + assert!(s.loaded_queue.is_empty(), "{command}"); + assert_eq!(s.tool_id(), "selection"); + assert!(std::sync::Arc::ptr_eq(&before, &s.doc().unwrap().doc)); + load_test_images(&mut s, 2); + assert!(s.execute("place.drop", &json!({"x": 0, "y": 0})).is_ok()); + } +} + /// Issue #1637: with several objects selected, a click on one of them (no drag) makes it the key /// object, and Align to Key Object leaves it in place. A second click on it drops the key. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 2badc3a17..6dfd23703 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -74,6 +74,7 @@ impl Session { // Any other tool unloads the place cursor. if id != "placeGun" { self.loaded = None; + self.loaded_queue.clear(); } // Leaving the Type tool keeps the text frame selected. if id != "type" diff --git a/crates/tools/src/nav.rs b/crates/tools/src/nav.rs index 1748c9cfb..2b84010d1 100644 --- a/crates/tools/src/nav.rs +++ b/crates/tools/src/nav.rs @@ -112,6 +112,8 @@ impl Tool for ZoomTool { pub struct PlaceGun { start: Option, cur: Point, + columns: usize, + rows: usize, } impl Tool for PlaceGun { @@ -122,6 +124,8 @@ impl Tool for PlaceGun { match ev.kind { PointerKind::Down => { self.start = Some(ev.pos); + self.columns = 1; + self.rows = 1; self.cur = ev.pos; vec![] } @@ -140,10 +144,19 @@ impl Tool for PlaceGun { { return vec![Action::Exec("place.drop".into(), json!({"frame": id.0}))]; } - // Under the drag threshold it's a click, as the overlay shows: actual size there. + // Under the drag threshold it's a click, as the overlay shows: actual size there + // (the next queued image, with several loaded). if click { return vec![Action::Exec("place.drop".into(), json!({"spread": crate::spread_json(sr), "x": sa.x, "y": sa.y}))]; } + // Arrow keys during the drag set a grid: the queued images fill its cells. + if self.columns > 1 || self.rows > 1 { + let r = designcraft_geom::Rect::from_points(sa, b); + return vec![Action::Exec( + "place.grid".into(), + json!({"spread": crate::spread_json(sr), "rect": [r.x0, r.y0, r.x1, r.y1], "columns": self.columns, "rows": self.rows}), + )]; + } // The frame the drag drew: at the graphic's proportions from where it started. let r = cx.loaded.map_or_else(|| designcraft_geom::Rect::from_points(sa, b), |size| proportional(sa, b, size).0); vec![Action::Exec( @@ -154,14 +167,41 @@ impl Tool for PlaceGun { _ => vec![], } } + fn busy(&self) -> bool { + self.start.is_some() + } + fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec { + use crate::ToolKey; + if key == ToolKey::Escape { + self.start = None; + return vec![Action::Exec("place.cancel".into(), json!({}))]; + } + // During a drag the arrow keys change the grid, and are handled even when it is already + // at its limit, so they don't go on to nudge the selection. + if self.start.is_some() { + match key { + ToolKey::Right => self.columns = (self.columns + 1).min(100), + ToolKey::Left => self.columns = self.columns.saturating_sub(1).max(1), + ToolKey::Up => self.rows = (self.rows + 1).min(100), + ToolKey::Down => self.rows = self.rows.saturating_sub(1).max(1), + _ => return vec![], + } + return vec![Action::Handled]; + } + vec![] + } fn overlays(&self, cx: &ToolContext) -> Vec { let Some(a) = self.start else { return vec![] }; + // Under the drag threshold the release is a click (actual size where it was pressed): + // no frame is drawn yet, the loaded cursor shows what lands. + let click = (self.cur - a).hypot() < cx.tol(3.0); + if !click && (self.columns > 1 || self.rows > 1) { + return grid_overlays(designcraft_geom::Rect::from_points(a, self.cur), self.columns, self.rows); + } let Some(size) = cx.loaded else { return vec![crate::Overlay::Marquee(designcraft_geom::Rect::from_points(a, self.cur))]; }; - // Under the drag threshold the release is a click (actual size where it was pressed): - // no frame is drawn yet, the loaded cursor shows what lands. - if (self.cur - a).hypot() < cx.tol(3.0) { + if click { return vec![]; } // As InDesign: the frame the graphic will fill, and its scale beside the pointer. @@ -178,13 +218,6 @@ Y: {pct}" }, ] } - fn key(&mut self, _cx: &ToolContext, key: crate::ToolKey, _mods: Mods) -> Vec { - match key { - // Escape unloads the place cursor. - crate::ToolKey::Escape => vec![Action::SwitchTool("selection".into())], - _ => vec![], - } - } fn cursor(&self, cx: &ToolContext, _p: Point, _m: Mods) -> Cursor { // Drawing the frame: the crosshair (the loaded graphic's thumbnail would hide the frame). // Under the drag threshold no frame is drawn yet (the release is a click), so the @@ -195,6 +228,26 @@ Y: {pct}" } } +/// The cells of a `columns` × `rows` place grid drawn over `rect`, 6 pt apart, as `place.grid` +/// lays them out; the whole rect when the cells would vanish. +fn grid_overlays(rect: designcraft_geom::Rect, columns: usize, rows: usize) -> Vec { + let (columns, rows) = (columns.clamp(1, 100), rows.clamp(1, 100)); + let w = (rect.width() - 6.0 * (columns - 1) as f64) / columns as f64; + let h = (rect.height() - 6.0 * (rows - 1) as f64) / rows as f64; + if !(w > 0.0 && h > 0.0) { + return vec![crate::Overlay::Marquee(rect)]; + } + (0..rows) + .flat_map(|row| { + (0..columns).map(move |column| { + let x = rect.x0 + column as f64 * (w + 6.0); + let y = rect.y0 + row as f64 * (h + 6.0); + crate::Overlay::Marquee(designcraft_geom::Rect::new(x, y, x + w, y + h)) + }) + }) + .collect() +} + /// A dragged frame `place.drop` takes only when it is wider and taller than this, in points; /// a thinner one places the graphic at its natural size instead. pub const PLACE_DRAG_MIN: f64 = 2.0; diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 3970f1910..28cfecf01 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2352,3 +2352,20 @@ fn direct_selection_marquee_selects_points_of_several_frames_and_drags_them_toge assert!(want.x.abs() < 1e-9 && (want.y.abs() - inc).abs() < 1e-9, "a quarter turn: {want:?}"); assert!(moves(p).iter().all(|&(x, y)| (x - want.x).abs() < 1e-9 && (y - want.y).abs() < 1e-9), "{p}"); } + +/// While the place cursor drags out a grid, the arrow keys change it and are handled, even at a +/// limit, so the session doesn't try them elsewhere; other keys and keys before a drag aren't. +#[test] +fn place_gun_grid_arrow_keys_are_handled_during_a_drag() { + let d = Document::new(&NewDocument::default()); + let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false)); + let cx = ctx(&d, &s, &c, &l); + let mut t = create("placeGun"); + assert!(t.key(&cx, ToolKey::Right, Mods::default()).is_empty(), "no drag yet"); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 110.0, 60.0)); + for key in [ToolKey::Right, ToolKey::Up, ToolKey::Left, ToolKey::Left, ToolKey::Down, ToolKey::Down] { + assert_eq!(t.key(&cx, key, Mods::default()), vec![Action::Handled], "{key:?}"); + } + assert!(t.key(&cx, ToolKey::Delete, Mods::default()).is_empty()); +} diff --git a/crates/ui-egui/src/app/file_dialogs.rs b/crates/ui-egui/src/app/file_dialogs.rs index 9f1271389..42a47fe32 100644 --- a/crates/ui-egui/src/app/file_dialogs.rs +++ b/crates/ui-egui/src/app/file_dialogs.rs @@ -16,6 +16,10 @@ use super::{DesignApp, Value, json}; #[cfg(not(target_arch = "wasm32"))] pub(crate) type Then = Box Result>; +/// What runs with the files chosen in a dialog that takes several, in the order chosen. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) type ThenMany = Box) -> Result>; + /// Whether an answer still needs the document that was active when the dialog was asked for. #[derive(Clone, Copy, PartialEq, Eq)] pub(crate) enum Bound { @@ -64,6 +68,8 @@ pub(crate) struct Held { enum Step { /// Open: run `then` with the file chosen. Open(Then), + /// Open several: run `then` with the files chosen. + OpenMany(ThenMany), /// Save: `ext` is added to a name typed without it, then `then` runs, after the replace-file /// question when the added extension names a file that exists. Save { ext: Option, then: Then }, @@ -118,6 +124,31 @@ impl DesignApp { } } + /// [`Self::ask_open`] for a dialog that takes several files: `then` runs with their paths, + /// in the order chosen. + #[track_caller] + pub(crate) fn ask_open_many( + &mut self, + purpose: &str, + bound: Bound, + then: impl FnOnce(&mut DesignApp, Vec) -> Result + 'static, + ) -> Result { + #[cfg(not(target_arch = "wasm32"))] + { + let mut dialog = craft_dialogs::FileDialog::open_many(); + for filter in open_filters(purpose) { + dialog = dialog.filter(filter.name, filter.extensions); + } + self.ask_file(dialog, bound, Step::OpenMany(Box::new(then))); + Ok(Value::Null) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (purpose, bound, then); + Err(NO_PICKER.into()) + } + } + /// Ask where to save `name`: beside the active document once it has been saved, else in the /// folder of the last file saved or exported (#1653). `then` runs with the path on a later /// frame; Cancel runs nothing. In a browser the name is the download's and `then` runs now. @@ -232,6 +263,15 @@ impl DesignApp { self.continue_in(Held { doc, dialog, then, path: path.to_string_lossy().to_string() }); } } + (Step::OpenMany(then), Answer::Paths(paths)) => { + let paths: Vec = paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect(); + if let Some(first) = paths.first().cloned() { + // Held as one answer: it waits for a dialog in its way and returns to its + // document as a single file's does. + let then: Then = Box::new(move |app, _| then(app, paths)); + self.continue_in(Held { doc, dialog, then, path: first }); + } + } (Step::Save { ext, then }, Answer::Paths(paths)) => { let Some(picked) = paths.into_iter().next() else { continue }; let path = picked_save_path(picked.clone(), ext.as_deref()); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3c90d8c59..3df85b504 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -16,27 +16,82 @@ impl DesignApp { open(request); return Ok(Value::Null); } - let bound = if purpose == "place" { file_dialogs::Bound::Document } else { file_dialogs::Bound::App }; + // File › Place takes several files: they load the place cursor in the order chosen. + if purpose == "place" { + return self.ask_open_many(purpose, file_dialogs::Bound::Document, |app, paths| match paths.as_slice() { + [path] => app.open_picked("place", path.clone()), + _ => app.place_paths(paths).map(|()| Value::Null), + }); + } let purpose_owned = purpose.to_string(); - self.ask_open(purpose, bound, move |app, path| app.open_picked(&purpose_owned, path)) + self.ask_open(purpose, file_dialogs::Bound::App, move |app, path| app.open_picked(&purpose_owned, path)) } /// Open (`open`) or place (`place`) the file at `path`, chosen in a dialog or passed by a script. pub(crate) fn open_picked(&mut self, purpose: &str, path: String) -> Result { + if purpose == "place" { + return self.place_path(&path, false); + } + self.open_file("file.open", json!({"path": path})) + } + + /// File › Place of the file at `path`, asking a multi-page PDF's Image Import Options first. + /// With `append`, an image that loads the cursor queues after the ones already loaded rather + /// than replacing them. + fn place_path(&mut self, path: &str, append: bool) -> Result { // Image Import Options: a multi-page PDF asks which page. - if purpose == "place" && path.to_ascii_lowercase().ends_with(".pdf") { + if path.to_ascii_lowercase().ends_with(".pdf") { let target = self.session.active().map(|d| d.uid); - let pages = self.services.read.as_mut().and_then(|r| r(&path).ok()).and_then(|b| designcraft_render::pdf_page_count(&b)).unwrap_or(1); + let pages = self.services.read.as_mut().and_then(|r| r(path).ok()).and_then(|b| designcraft_render::pdf_page_count(&b)).unwrap_or(1); if pages > 1 { self.ui.dialog = Some(dialogs::Dialog::new("pdfImport", json!({"path": path, "page": "1", "pages": pages, "target": target}))); return Ok(Value::Null); } - return self.place_file(json!({"path": path})); } - if purpose == "place" { - return self.place_file(json!({"path": path})); + self.place_file(if append { json!({"path": path, "append": true}) } else { json!({"path": path}) }) + } + + /// Place an ordered batch of files, as File › Place with several chosen. The batch stops when + /// a file opens a dialog (a multi-page PDF's Import Options, an alert), as the inbox's does; + /// every file that loads the cursor adds to what the earlier ones loaded, in the order the + /// files were chosen (images in a row load together, before the file after them). A file that + /// can't be placed gets an alert and stops the batch; its error is returned, so automation + /// doesn't carry on as if the batch had loaded. + pub(crate) fn place_paths(&mut self, paths: Vec) -> Result<(), String> { + let mut images = Vec::new(); + // Images already in the place cursor stay: the batch queues after them. + let mut loaded = self.session.loaded.is_some(); + // `None` at the end loads the images left. + for path in paths.into_iter().map(Some).chain([None]) { + if let Some(p) = &path + && is_cursor_image(p) + { + images.push(json!({"path": p})); + continue; + } + if path.is_none() && images.is_empty() { + break; + } + if self.ui.dialog.is_some() { + self.status(crate::i18n::tr(&self.ui.language, "Place cancelled while a dialog is open")); + return Ok(()); + } + if !images.is_empty() { + let r = self.load_place_cursor(std::mem::take(&mut images), loaded)?; + loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + } + if let Some(p) = path { + let r = self.place_path(&p, loaded)?; + loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + } } - self.open_file("file.open", json!({"path": path})) + Ok(()) + } + + /// `place.load` of `files` (`{path}` or `{name, base64}` each), queued after the images + /// already loaded when `append`. An image that can't be read gets an alert, as a placed one does. + fn load_place_cursor(&mut self, files: Vec, append: bool) -> Result { + self.open_named_file("place.load", json!({"files": files, "append": append}), String::new()) } /// Load Styles: ask the host for a document whose styles to load; `kind` is `paragraph`, @@ -106,11 +161,49 @@ impl DesignApp { } let Some(inbox) = self.services.inbox.clone() else { return }; let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); - for file in files { + let cursor_image = |file: &ImportedFile| { + file.request.purpose == "place" + && !file.name.to_ascii_lowercase().ends_with(".pdf") + && (is_cursor_image(&file.name) || designcraft_render::image_size(&file.bytes).is_some()) + }; + // In the order they came: consecutive images for the same document load the place + // cursor together; after the first placement into it, the later ones are added to it. + let mut append = false; + let mut files = files.into_iter().peekable(); + while let Some(file) = files.next() { if file.request.purpose == "shortcuts" { shortcut_import::import_delivered(self, &file.bytes); continue; } + let placing = file.request.purpose == "place"; + let mut group = vec![]; + if cursor_image(&file) { + while let Some(next) = + files.next_if(|n| cursor_image(n) && n.request.target == file.request.target && n.request.purpose == file.request.purpose) + { + group.push(next); + } + } + // Several images: into the place cursor. + if !group.is_empty() { + if self.ui.dialog.is_some() { + self.status(crate::i18n::tr(&self.ui.language, "Image import cancelled while a dialog is open")); + continue; + } + if self.activate_import_target(&file.request).is_err() { + continue; + } + let sources: Vec<_> = std::iter::once(file) + .chain(group) + .map(|f| json!({"name": f.name, "base64": designcraft_engine::cmd::base64_encode(&f.bytes)})) + .collect(); + // They queue after images already in the cursor, as a native batch's do. + let queue_after = append || self.session.loaded.is_some(); + if self.load_place_cursor(sources, queue_after).is_ok() { + append = true; + } + continue; + } if self.ui.dialog.is_some() { self.status( crate::i18n::tr(&self.ui.language, "{name}: import cancelled while a dialog is open; choose the file again") @@ -119,13 +212,16 @@ impl DesignApp { continue; } let name = file.name.clone(); - if let Err(e) = self.import_file(file) { - self.status(format!("{name}: {e}")); + match self.import_file(file, append) { + Ok(_) if placing => append = true, + Ok(_) => {} + Err(e) => self.status(format!("{name}: {e}")), } } } - fn import_file(&mut self, file: ImportedFile) -> Result { + /// Imports `file`; a placed one is added to the place cursor when `append`. + fn import_file(&mut self, file: ImportedFile, append: bool) -> Result { let lower = file.name.to_ascii_lowercase(); if let Some(kind) = file.request.purpose.strip_prefix("styles") { self.activate_import_target(&file.request)?; @@ -157,7 +253,7 @@ impl DesignApp { if lower.ends_with(".ase") || file.request.purpose == "swatches" { self.run("swatch.load", json!({"base64": b64})) } else if file.request.purpose == "place" { - self.place_file(json!({"name": file.name, "base64": b64})) + self.place_file(json!({"name": file.name, "base64": b64, "append": append})) } else if place { self.open_file("file.place", json!({"name": file.name, "base64": b64})) } else { @@ -270,7 +366,7 @@ impl DesignApp { pub fn open_named_file(&mut self, cmd: &str, params: Value, file: String) -> Result { let r = self.run(cmd, params); if let Err(e) = &r { - let title = if cmd == "file.place" { "Can't Place the File" } else { "Can't Open the File" }; + let title = if cmd == "file.place" || cmd == "place.load" { "Can't Place the File" } else { "Can't Open the File" }; if self.ui.dialog.as_ref().is_some_and(|d| d.id == "findChange") { self.session.reset_find_scope(); } @@ -311,6 +407,14 @@ impl DesignApp { } } +/// Graphics that can wait in the place cursor, several at a time: raster images, SVG, PSD and +/// EPS. A PDF can't (it may ask which page), nor can text, media or documents. +pub(crate) fn is_cursor_image(name: &str) -> bool { + std::path::Path::new(name).extension().and_then(|e| e.to_str()).is_some_and(|e| { + matches!(e.to_ascii_lowercase().as_str(), "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" | "tif" | "tiff" | "svg" | "psd" | "eps") + }) +} + /// Files that open as documents (when dropped or picked) rather than being placed: DesignCraft, /// IDML, and InDesign documents and templates (converted to IDML on open). pub fn opens_as_document(name: &str) -> bool { @@ -761,6 +865,141 @@ pub(crate) mod browser_import_tests { assert!(app.pending_pdf.is_none()); assert!(app.session.doc().unwrap().doc.assets.is_empty()); } + + fn png(v: u8) -> Vec { + designcraft_render::Rendered { width: 10, height: 10, pixels: vec![v; 400] }.to_png() + } + + /// The names of the images in the place cursor, the one a click places first. + fn loaded_names(app: &DesignApp) -> Vec { + let doc = &app.session.doc().unwrap().doc; + app.session.loaded.iter().chain(app.session.loaded_queue.iter()).map(|g| doc.assets[&g.asset].name.clone()).collect() + } + + #[test] + fn multi_image_inbox_loads_one_queue_on_its_original_document() { + let mut app = app(); + let request = app.import_request("place"); + app.run("file.new", json!({"title": "B"})).unwrap(); + for i in 0..3 { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { + request: request.clone(), + name: format!("{i}.png"), + bytes: png(200), + }); + } + app.drain_inbox(); + assert_eq!(app.session.doc().unwrap().uid, request.target.unwrap()); + assert_eq!(app.session.tool_id(), "placeGun"); + assert_eq!(app.session.loaded_queue.len(), 2); + assert!(app.session.documents()[1].doc.assets.is_empty()); + } + + /// Files dropped together are placed in the order they came: images around a PDF go into the + /// place cursor before and after it, and each adds to the cursor rather than replacing it. + #[test] + fn inbox_places_images_and_a_pdf_in_their_order_into_one_cursor() { + let mut app = app(); + let request = app.import_request("place"); + for (name, bytes) in [("a.png", png(200)), ("one.pdf", pdf_pages(1)), ("b.png", png(90))] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + assert_eq!(loaded_names(&app), ["a.png", "one.pdf", "b.png"], "in the order dropped, all in the cursor"); + } + + #[test] + fn batch_cancel_status_uses_the_interface_language() { + let mut app = app(); + app.ui.language = "de".into(); + app.ui.dialog = Some(dialogs::Dialog::new("alert", json!({"title": "t", "message": "m"}))); + let request = app.import_request("place"); + for name in ["one.png", "two.png"] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes: png(200) }); + } + app.drain_inbox(); + assert_eq!(app.ui.status, "Bildimport bei geöffnetem Dialog abgebrochen"); + assert!(app.ui.dialog.is_some()); + assert!(app.session.loaded.is_none()); + } + + #[test] + fn native_batch_stops_when_a_dialog_is_open_and_appends_to_the_cursor() { + let mut app = app(); + app.ui.dialog = Some(dialogs::Dialog::new("alert", json!({"title": "t", "message": "m"}))); + let _ = app.place_paths(vec!["one.pdf".into(), "two.png".into()]); + assert_eq!(app.ui.status, "Place cancelled while a dialog is open"); + assert!(app.session.loaded.is_none()); + app.ui.dialog = None; + let b64 = designcraft_engine::cmd::base64_encode(&image()); + app.run("place.load", json!({"base64": b64, "name": "a.svg"})).unwrap(); + let first = app.session.loaded.as_ref().unwrap().asset; + let files = json!([{"base64": b64, "name": "b.svg"}, {"base64": b64, "name": "c.svg"}]); + app.run("place.load", json!({"files": files, "append": true})).unwrap(); + assert_eq!(app.session.loaded.as_ref().unwrap().asset, first); + assert_eq!(app.session.loaded_queue.len(), 2); + app.run("place.load", json!({"files": files})).unwrap(); + assert_eq!(app.session.loaded_queue.len(), 1); + } + + /// Images around a single-page PDF load into the cursor in the order they were chosen. + #[test] + fn native_batch_keeps_the_chosen_order() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("one.pdf"), pdf_pages(1)).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + app.place_paths(vec![path("a.svg"), path("one.pdf"), path("b.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg"]); + // A second batch queues after what the cursor still holds. + std::fs::write(path("c.svg"), image()).unwrap(); + app.place_paths(vec![path("c.svg"), path("a.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg", "c.svg", "a.svg"]); + } + + /// File › Place with several files chosen in the dialog loads them all into the place + /// cursor, in the order chosen; with one, it is placed as before. + #[test] + fn place_dialog_with_several_files_loads_them_all() { + let dir = tempfile::tempdir().unwrap(); + let paths: Vec = ["b.svg", "a.svg", "c.svg"].iter().map(|n| dir.path().join(n)).collect(); + for p in &paths { + std::fs::write(p, image()).unwrap(); + } + let mut app = app(); + let answer = paths.clone(); + app.answer_dialogs(move |_| craft_dialogs::Answer::Paths(answer.clone())); + app.run("app.placeDialog", json!({})).unwrap(); + app.settle_dialogs(); + assert_eq!(loaded_names(&app), ["b.svg", "a.svg", "c.svg"]); + assert_eq!(app.session.tool_id(), "placeGun"); + // The same through the command's `paths`, as the control channel gives them. + let mut scripted = self::app(); + let paths: Vec = paths.iter().map(|p| p.to_string_lossy().to_string()).collect(); + scripted.run("app.placeDialog", json!({"paths": paths})).unwrap(); + assert_eq!(loaded_names(&scripted), ["b.svg", "a.svg", "c.svg"]); + } + + #[test] + fn multi_image_inbox_cancels_when_original_document_closed() { + let mut app = app(); + let request = app.import_request("place"); + app.run("file.new", json!({"title": "B"})).unwrap(); + app.run("file.close", json!({"index": 0})).unwrap(); + for i in 0..2 { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { + request: request.clone(), + name: format!("{i}.png"), + bytes: png(200), + }); + } + app.drain_inbox(); + assert!(app.session.loaded.is_none()); + assert!(app.session.doc().unwrap().doc.assets.is_empty()); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index f544f5bf5..72132250c 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -20,6 +20,7 @@ mod guides; mod ime; mod input; mod page_decor; +mod place_cursor; mod render; mod rulers; mod scroll; @@ -413,6 +414,7 @@ fn draw_loaded_thumbnail(app: &DesignApp, painter: &egui::Painter, p: Pos2, t: & vec![pos2(inner.min.x, inner.max.y), pos2(inner.min.x + 3.5, inner.min.y + 2.5), pos2(inner.max.x, inner.max.y)], ink, )); + place_cursor::draw_loaded_count(app, painter, badge); } /// The loaded graphic's thumbnail texture, cached per image data. diff --git a/crates/ui-egui/src/canvas/place_cursor.rs b/crates/ui-egui/src/canvas/place_cursor.rs new file mode 100644 index 000000000..69b17571c --- /dev/null +++ b/crates/ui-egui/src/canvas/place_cursor.rs @@ -0,0 +1,34 @@ +//! The loaded place cursor's image count, drawn beside the thumbnail's badge. + +use super::{Color32, DesignApp, Pos2, Rect, pos2, vec2}; + +/// Several images loaded: how many, beside the thumbnail's image `badge` ("(6)"), navy with a +/// white rim so it reads over any picture. +pub(super) fn draw_loaded_count(app: &DesignApp, painter: &egui::Painter, badge: Rect) { + let loaded = app.session.loaded.is_some().then(|| app.session.loaded_queue.len().saturating_add(1)); + let Some(label) = loaded_count_label(loaded) else { return }; + let at: Pos2 = pos2(badge.max.x + 6.0, badge.center().y); + let font = crate::theme::semibold(15.0); + for d in [vec2(-1.0, 0.0), vec2(1.0, 0.0), vec2(0.0, -1.0), vec2(0.0, 1.0)] { + painter.text(at + d, egui::Align2::LEFT_CENTER, &label, font.clone(), Color32::WHITE); + } + painter.text(at, egui::Align2::LEFT_CENTER, label, font, Color32::from_rgb(25, 35, 100)); +} + +/// The count the loaded place cursor shows, as InDesign's "(6)": only when more than one image +/// is loaded. +pub(super) fn loaded_count_label(loaded: Option) -> Option { + loaded.filter(|n| *n > 1).map(|n| format!("({n})")) +} + +#[cfg(test)] +mod tests { + /// The loaded cursor counts the images as InDesign's "(6)", and shows no count for the last + /// one or with nothing loaded. + #[test] + fn the_loaded_cursor_counts_several_images() { + assert_eq!(super::loaded_count_label(Some(6)).as_deref(), Some("(6)")); + assert_eq!(super::loaded_count_label(Some(1)), None); + assert_eq!(super::loaded_count_label(None), None); + } +} diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index b89840044..87fae4392 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -25,6 +25,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "ასლის შენახვა…"), ("Revert", "წინა ვერსიაზე დაბრუნება"), ("Place…", "განთავსება…"), + ("Image import cancelled while a dialog is open", "გამოსახულებების იმპორტი გაუქმდა, რადგან დიალოგი გახსნილია"), + ("Place cancelled while a dialog is open", "განთავსება გაუქმდა, რადგან დიალოგი ღიაა"), ("Export PDF…", "PDF ექსპორტი…"), ("Print…", "დაბეჭდვა…"), ("Document Setup…", "დოკუმენტის პარამეტრები…"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index 27f5cf389..7e8ccdddc 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -146,6 +146,26 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Save a Copy…", ["Kopie speichern …", "Enregistrer une copie…", "Guardar una copia…", "コピーを保存…", "保存副本…"]), ("Revert", ["Zurück zur letzten Version", "Version précédente", "Volver a la versión guardada", "復帰", "恢复到上次保存"]), ("Place…", ["Platzieren …", "Importer…", "Colocar…", "配置…", "置入…"]), + ( + "Image import cancelled while a dialog is open", + [ + "Bildimport bei geöffnetem Dialog abgebrochen", + "Importation des images annulée car une boîte de dialogue est ouverte", + "Importación de imágenes cancelada mientras hay un diálogo abierto", + "ダイアログが開いているため画像の読み込みをキャンセルしました", + "对话框打开时已取消图像导入", + ], + ), + ( + "Place cancelled while a dialog is open", + [ + "Platzieren bei geöffnetem Dialog abgebrochen", + "Importation annulée car une boîte de dialogue est ouverte", + "Colocación cancelada mientras hay un diálogo abierto", + "ダイアログが開いているため配置をキャンセルしました", + "对话框打开时已取消置入", + ], + ), ("Export PDF…", ["PDF exportieren …", "Exporter en PDF…", "Exportar PDF…", "PDF を書き出し…", "导出PDF…"]), ("Print…", ["Drucken …", "Imprimer…", "Imprimir…", "プリント…", "打印…"]), ("Document Setup…", ["Dokument einrichten …", "Format de document…", "Ajustar documento…", "ドキュメント設定…", "文档设置…"]), diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 717e1332e..b49b8c7f4 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -135,9 +135,18 @@ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option match p.get("path").and_then(Value::as_str) { - Some(path) => app.open_picked("place", path.to_string()), - None => app.pick_and_open("place"), + "app.placeDialog" => match (p.get("path").and_then(Value::as_str), p.get("paths").and_then(Value::as_array)) { + (Some(path), _) => app.open_picked("place", path.to_string()), + // Several files, as chosen together in the dialog: in their order. One is placed as the + // dialog places one (filling the selected frame). Every entry must be a path. + (None, Some(paths)) => match paths.iter().map(|v| v.as_str().map(str::to_string)).collect::>>() { + None => Err("app.placeDialog: every entry of paths must be a string".into()), + Some(paths) => match <[String; 1]>::try_from(paths) { + Ok([path]) => app.open_picked("place", path), + Err(paths) => app.place_paths(paths).map(|()| Value::Null), + }, + }, + (None, None) => app.pick_and_open("place"), }, "app.placeWithOptions" => { // Word/RTF Import Options: style mapping and conflicts before the text lands. diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index f24d1d548..0fbdaca45 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -15,7 +15,12 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ ("app.newDocumentDialog", "New Document…", Some("Cmd+N"), "{}"), ("app.openDialog", "Open…", Some("Cmd+O"), "{path?} — without a path, choose the file in a dialog"), ("app.openRecent", "Open Recent File", None, "{index} — file.openRecent, with an alert when the file can't be opened"), - ("app.placeDialog", "Place…", Some("Cmd+D"), "{path?} — without a path, choose the file in a dialog"), + ( + "app.placeDialog", + "Place…", + Some("Cmd+D"), + "{path?, paths?: [path] (several, loaded into the place cursor in order)} — without either, choose the files in a dialog", + ), ("app.saveDialog", "Save As…", Some("Cmd+Shift+S"), "{path?} — without a path, choose where in a dialog"), ("app.save", "Save", Some("Cmd+S"), "{}"), ("app.quit", "Quit DesignCraft", Some("Cmd+Q"), "{} — close the window; each document with unsaved changes asks first"), diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md new file mode 100644 index 000000000..997414bcd --- /dev/null +++ b/docs/multi-image-placement.md @@ -0,0 +1,26 @@ +# Multiple images + +Choose **File > Place** (Cmd+D on macOS) and select several images. They load into a placement cursor in the order supplied by the file picker. The cursor shows the next image's thumbnail and, beside it, how many are loaded ("(6)"). + +- Click to place the next image at its natural size. +- Drag to draw its frame: it keeps the image's proportions, and shows the scale beside the pointer. +- Click an existing graphic frame to replace its contents. +- While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. +- Press Escape or select another tool to cancel the remaining placement. + +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. + +Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. + +## Automation + +All placement behavior is available through the engine, CLI, control channel and MCP: + +```json +{"command":"place.load","params":{"files":[{"path":"/images/one.png"},{"path":"/images/two.jpg"}]}} +{"command":"place.load","params":{"files":[{"path":"/images/three.png"}],"append":true}} +{"command":"place.grid","params":{"rect":[36,36,576,756],"columns":3,"rows":4,"gutter":6}} +{"command":"place.cancel","params":{}} +``` + +Each source can instead supply `base64` and `name`, including on the web. `append` queues the images after those already loaded instead of replacing them. `place.grid` consumes only the images that fit. Undo removes placed frames together, while the cursor remains at its current position in the queue. The UI command `app.placeDialog` takes `paths` for a File > Place of several files without the dialog. From e2d85026362a22fc4c7ec97003f93b5c93c398f5 Mon Sep 17 00:00:00 2001 From: texjer Date: Tue, 3 Nov 2026 21:54:22 -0500 Subject: [PATCH 012/322] =?UTF-8?q?Place:=20File=20=E2=80=BA=20Place=20Con?= =?UTF-8?q?tact=20Sheet=E2=80=A6=20puts=20the=20loaded=20images=20on=20new?= =?UTF-8?q?=20pages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Split out of #2073. Port of #1392's contact sheet. - `place.contactSheet` places every image in the place cursor on new pages after the last one, in a grid of equal frames (columns, rows, gutter, page margin), as one undo step; a bad grid or margin changes nothing. - The dialog reads bare numbers in the document's unit, from the menu and from `ui.dialog.open` alike; a mistake keeps it open with what was typed and why. Its fields have accessible names; strings in every language. --- ROADMAP.md | 1 + crates/engine/src/cmd/file/place.rs | 42 +++++++++++++++++++++- crates/engine/src/cmd/file/registry.rs | 11 +++++- crates/engine/src/tests.rs | 30 ++++++++++++++-- crates/ui-egui/src/app/files.rs | 38 ++++++++++++++++++++ crates/ui-egui/src/control.rs | 18 +++++++++- crates/ui-egui/src/dialogs.rs | 47 +++++++++++++++++++++++++ crates/ui-egui/src/i18n/ka.rs | 4 +++ crates/ui-egui/src/i18n/sv.rs | 4 +++ crates/ui-egui/src/i18n/table.rs | 19 ++++++++++ crates/ui-egui/src/menus/run.rs | 4 +++ crates/ui-egui/src/menus/tables.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 1 + docs/multi-image-placement.md | 9 +++-- 14 files changed, 221 insertions(+), 8 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 57c143340..40cce6b26 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -405,6 +405,7 @@ Newest first. - **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change. - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. +- **2026-10-30** · File › Place Contact Sheet… puts every image loaded in the place cursor on new pages, in a grid of equal frames (`place.contactSheet`), as one undo step. Ported from #1392; see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index ba9e0827a..819f18ef1 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -497,6 +497,44 @@ pub(super) fn place_grid(s: &mut Session, p: &Value) -> Result { Ok(json!({"ids": ids.iter().map(|id| id.0).collect::>(), "remaining": loaded_count(s)})) } +/// Place all queued images on new pages as one undoable edit. +pub(super) fn place_contact_sheet(s: &mut Session, p: &Value) -> Result { + const ID: &str = "place.contactSheet"; + validate_place_cursor(s, ID)?; + let (columns, rows, gutter) = grid_dimensions(p, ID, 3, 4)?; + let margin = crate::cmd::f64_or(p, "margin", 36.0); + if !margin.is_finite() || margin < 0.0 { + return Err(bad(ID, "invalid margin")); + } + let images: Vec<_> = s.loaded.iter().chain(s.loaded_queue.iter()).copied().collect(); + if images.is_empty() { + return Err(bad(ID, "load images first using File > Place")); + } + let layer = s.doc()?.active_layer; + let per_page = columns.saturating_mul(rows).max(1); + let count = images.len().div_ceil(per_page); + let ids = s.edit(|d, sel| { + let after = d.page_count().saturating_sub(1); + d.insert_pages(Some(after), count, None)?; + let mut ids = Vec::with_capacity(images.len()); + for (page_offset, chunk) in images.chunks(per_page).enumerate() { + let index = after.saturating_add(1).saturating_add(page_offset); + let (si, pi) = d.page_loc(index).ok_or_else(|| bad(ID, "missing page"))?; + let b = d.spreads.get(si).and_then(|sp| sp.pages.get(pi)).ok_or_else(|| bad(ID, "missing page"))?.bounds(); + let cells = grid_cells(Rect::new(b.x0 + margin, b.y0 + margin, b.x1 - margin, b.y1 - margin), columns, rows, gutter, ID)?; + for (image, rect) in chunk.iter().zip(cells) { + ids.push(insert_grid_image(d, designcraft_doc::SpreadRef::Doc(si), layer, *image, rect, ID)?); + } + } + *sel = Selection::items(ids.clone()); + Ok(ids) + })?; + for _ in &ids { + advance_place_cursor(s); + } + Ok(json!({"pages": count, "images": ids.len()})) +} + /// File › Place of an IDML or DesignCraft document: the objects of one page (`layoutPage`, /// 1-based) grouped, top-left at x/y (default: the source position on the first page). fn place_layout_page(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) -> Result { @@ -573,7 +611,9 @@ pub(super) mod image_place_tests { let mut s = Session::new(); s.execute("file.new", &json!({})).unwrap(); s.set_tool("rectangleFrame"); - for (cmd, p) in [("place.drop", json!({"x": 10, "y": 10})), ("place.grid", json!({"rect": [0, 0, 100, 100]}))] { + for (cmd, p) in + [("place.drop", json!({"x": 10, "y": 10})), ("place.grid", json!({"rect": [0, 0, 100, 100]})), ("place.contactSheet", json!({}))] + { let e = s.execute(cmd, &p).unwrap_err().to_string(); assert!(e.contains("nothing loaded"), "{cmd}: {e}"); assert_eq!(s.tool_id(), "rectangleFrame", "{cmd}"); diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index 57aa1a5a6..194cfe2ec 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -3,7 +3,7 @@ use super::EngineError; use super::bytes::{base64_encode, to_bytes, to_bytes_with_preview, with_document_extension}; use super::new::{file_new, file_sample, save_preset}; use super::open::{file_open, file_open_bytes, file_open_recent, has_recent, recent_entry}; -use super::place::{file_place, place_drop, place_grid, place_load, read_source}; +use super::place::{file_place, place_contact_sheet, place_drop, place_grid, place_load, read_source}; use super::save::{FolderAccess, can_revert, file_revert, file_save, recovery_dir}; use super::snippets::{snippet_export, snippet_place}; use super::{CommandSpec, PRESETS, Value, always, bad, cmd, has_doc, json, ok, str_param}; @@ -137,6 +137,15 @@ pub fn specs() -> Vec { has_doc, place_grid ), + cmd!( + "place.contactSheet", + "Place Contact Sheet", + ["File"], + None, + "{columns?: 3, rows?: 4, gutter?: 6, margin?: 36} — place all loaded images on new pages", + has_doc, + place_contact_sheet + ), cmd!(noundo "place.cancel", "Cancel Image Placement", [], None, "{}", has_doc, |s, _| { s.loaded = None; s.loaded_queue.clear(); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 564e42605..b8228976b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2063,6 +2063,32 @@ fn image_grid_and_load_fail_atomically() { assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); assert_eq!(s.loaded_queue.len(), 2); } + assert!(s.execute("place.contactSheet", &json!({"margin": 10000})).is_err()); + assert!(Arc::ptr_eq(&before, &s.doc().unwrap().doc)); +} + +#[test] +fn contact_sheet_adds_pages_and_undoes_as_one_edit() { + let mut s = session(); + load_test_images(&mut s, 25); + let pages = s.doc().unwrap().doc.page_count(); + let r = s.execute("place.contactSheet", &json!({"columns": 3, "rows": 4})).unwrap(); + assert_eq!(r["pages"], 3); + assert_eq!(r["images"], 25); + let doc = &s.doc().unwrap().doc; + assert_eq!(doc.page_count(), pages + 3); + for page_index in pages..pages + 3 { + let (si, pi) = doc.page_loc(page_index).unwrap(); + let bounds = doc.spreads[si].pages[pi].bounds(); + let items: Vec<_> = doc.spreads[si].items.iter().filter(|i| bounds.contains(i.bounds().center())).collect(); + assert_eq!(items.len(), if page_index == pages + 2 { 1 } else { 12 }); + for item in items { + assert!(bounds.contains(item.bounds().origin())); + } + } + assert!(s.loaded.is_none() && s.loaded_queue.is_empty()); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.page_count(), pages); } #[test] @@ -2111,12 +2137,12 @@ fn a_place_click_with_a_queue_places_the_next_image_without_a_grid() { #[test] fn undoing_loaded_assets_cancels_every_placement_cursor() { - for command in ["place.drop", "place.grid"] { + for command in ["place.drop", "place.grid", "place.contactSheet"] { let mut s = session(); load_test_images(&mut s, 3); s.execute("edit.undo", &json!({})).unwrap(); let before = s.doc().unwrap().doc.clone(); - let params = json!({"rect": [0, 0, 200, 200]}); + let params = if command == "place.contactSheet" { json!({}) } else { json!({"rect": [0, 0, 200, 200]}) }; assert!(s.execute(command, ¶ms).is_err(), "{command}"); assert!(s.loaded.is_none(), "{command}"); assert!(s.loaded_queue.is_empty(), "{command}"); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3df85b504..65097d2ef 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -893,6 +893,10 @@ pub(crate) mod browser_import_tests { assert_eq!(app.session.tool_id(), "placeGun"); assert_eq!(app.session.loaded_queue.len(), 2); assert!(app.session.documents()[1].doc.assets.is_empty()); + app.run("app.contactSheetDialog", json!({})).unwrap(); + let result = dialogs::confirm(&mut app).unwrap(); + assert_eq!(result["images"], 3); + assert_eq!(result["pages"], 1); } /// Files dropped together are placed in the order they came: images around a PDF go into the @@ -983,6 +987,40 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&scripted), ["b.svg", "a.svg", "c.svg"]); } + #[test] + fn contact_sheet_measures_use_the_document_unit() { + let mut app = app(); + app.run("document.preferences", json!({"horizontalUnits": "millimeters"})).unwrap(); + app.run("app.contactSheetDialog", json!({})).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.unit, designcraft_geom::Unit::Millimeters); + assert_eq!(d.s("gutter"), "6pt"); + } + + #[test] + fn contact_sheet_validation_preserves_fields_and_pending_images() { + let mut app = app(); + let request = app.import_request("place"); + deliver(&mut app, request, "image.png", png(200)); + app.run("app.contactSheetDialog", json!({})).unwrap(); + let before = app.session.doc().unwrap().doc.clone(); + for (field, value) in [("rows", "bad"), ("rows", "0"), ("rows", "4"), ("margin", "999999pt")] { + app.ui.dialog.as_mut().unwrap().fields.insert(field.into(), json!(value)); + if field == "rows" && value == "4" { + continue; + } + assert!(dialogs::confirm(&mut app).is_err()); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert_eq!(dialog.s(field), value); + assert!(!dialog.s("status").is_empty()); + assert!(std::sync::Arc::ptr_eq(&before, &app.session.doc().unwrap().doc)); + assert!(app.session.loaded.is_some()); + } + app.ui.dialog.as_mut().unwrap().fields.insert("margin".into(), json!("36pt")); + assert!(dialogs::confirm(&mut app).is_ok()); + assert!(app.ui.dialog.is_none()); + } + #[test] fn multi_image_inbox_cancels_when_original_document_closed() { let mut app = app(); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index d70a79695..efa2cbd8a 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -390,7 +390,11 @@ fn handle_request(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest app.session.reset_find_scope(); } let fields = p.get("fields").cloned().unwrap_or(Value::Null); - let d = if id == "frameSize" { crate::dialogs::frame_size_dialog(app, fields) } else { crate::dialogs::Dialog::new(id, fields) }; + let d = match id { + "frameSize" => crate::dialogs::frame_size_dialog(app, fields), + "contactSheet" => crate::dialogs::contact_sheet_dialog(app, fields), + _ => crate::dialogs::Dialog::new(id, fields), + }; let v = serde_json::to_value(&d).unwrap_or_default(); app.ui.dialog = Some(d); ok(v) @@ -517,6 +521,18 @@ mod automation_contract_tests { app.run("style.paragraph.edit", json!({"name":designcraft_doc::BASIC_PARAGRAPH,"chars":{"size":18}})).unwrap(); assert_eq!(app.session.doc().unwrap().history.undo.len(), history + 1); } + /// `ui.dialog.open` opens Place Contact Sheet as the menu does: bare numbers are in the + /// document's ruler unit, so `1` on an inch document is an inch, not a pica. + #[test] + fn a_contact_sheet_opened_over_the_control_channel_uses_the_document_unit() { + let mut app = app(); + let ctx = egui::Context::default(); + app.run("document.preferences", json!({"horizontalUnits": "inches"})).unwrap(); + let response = call(&mut app, &ctx, "ui.dialog.open", json!({"id": "contactSheet", "fields": {"margin": "1"}})); + assert_eq!(response["ok"], true, "{response}"); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!(d.unit, designcraft_geom::Unit::Inches); + } fn app() -> DesignApp { let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); app.session.execute("file.new", &json!({"pages":2})).unwrap(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7662c0cb0..a0a00c15c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -36,6 +36,7 @@ impl Dialog { }; let defaults = match id { "newDocument" => crate::new_document::defaults(), + "contactSheet" => json!({"columns": 3, "rows": 4, "gutter": "6pt", "margin": "36pt"}), "goToPage" => json!({"page": "1"}), "epubExport" => json!({"split": false, "mode": "style", "style": designcraft_doc::BASIC_PARAGRAPH, "coverImage": ""}), "qrCode" => json!({"type": "url", "content": "https://", "color": "[Black]"}), @@ -1526,6 +1527,20 @@ fn doc_unit(app: &DesignApp) -> Unit { app.session.active().map(|s| s.doc.settings.horizontal_units).unwrap_or(Unit::Picas) } +/// File › Place Contact Sheet…: bare numbers typed in the dialog are in the document's ruler unit +/// (the defaults keep their explicit `pt`). +pub fn open_contact_sheet(app: &mut DesignApp) { + app.ui.dialog = Some(contact_sheet_dialog(app, json!({}))); +} + +/// The Place Contact Sheet dialog with `fields`, its bare numbers in the document's ruler unit, +/// for the menu and for `ui.dialog.open` alike. +pub fn contact_sheet_dialog(app: &DesignApp, fields: Value) -> Dialog { + let mut d = Dialog::new("contactSheet", fields); + d.unit = doc_unit(app); + d +} + /// The document's vertical ruler unit: what a bare number means in a height field. fn doc_vertical_unit(app: &DesignApp) -> Unit { app.session.active().map(|s| s.doc.settings.vertical_units).unwrap_or(Unit::Picas) @@ -2948,6 +2963,7 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { "qrCode" => crate::i18n::tr(&app.ui.language, "Generate QR Code"), "preferences" => crate::i18n::tr(&app.ui.language, "Preferences"), "print" => crate::i18n::tr(&app.ui.language, "Print"), + "contactSheet" => crate::i18n::tr(&app.ui.language, "Place Contact Sheet"), "pdfImport" => crate::i18n::tr(&app.ui.language, "Place PDF"), "pdfExport" => crate::i18n::tr(&app.ui.language, "Export PDF"), "epubExport" => crate::i18n::tr(&app.ui.language, "EPUB Export Options"), @@ -3330,6 +3346,19 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { crate::package_dialog::INSTRUCTIONS => crate::package_dialog::show_instructions(app, ui, &mut d), "preferences" => preferences(app, ui, &mut d, body_height), "print" => print_dialog(app, ui, &mut d), + "contactSheet" => { + if !d.s("status").is_empty() { + ui.label(d.s("status")); + } + ui.label(crate::i18n::tr(&app.ui.language, "Place loaded images on new pages, in file order.")); + for (label, key) in [("Columns", "columns"), ("Rows", "rows"), ("Gutter", "gutter"), ("Page margin", "margin")] { + let label = crate::i18n::tr(&app.ui.language, label); + ui.horizontal(|ui| { + ui.add_sized([95.0, 20.0], egui::Label::new(label)); + text_field_named(ui, &mut d, key, 80.0, label); + }); + } + } "pdfImport" => { ui.label(egui::RichText::new(if d.b("async") { d.s("name") } else { d.s("path") }).size(11.0)); ui.horizontal(|ui| { @@ -4611,6 +4640,24 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { app.canvas.shown = None; Ok(r) } + "contactSheet" => { + let result = (|| { + let params = json!({ + "columns": d.s("columns").trim().parse::().map_err(|_| "Columns must be a whole number")?, + "rows": d.s("rows").trim().parse::().map_err(|_| "Rows must be a whole number")?, + "gutter": d.m("gutter").ok_or("Enter a valid gutter")?, + "margin": d.m("margin").ok_or("Enter a valid margin")?, + }); + app.run("place.contactSheet", params) + })(); + // A mistake keeps the dialog, with what was typed and why it can't be placed. + if let Err(error) = &result { + let mut d = d; + d.fields.insert("status".into(), json!(error)); + app.ui.dialog = Some(d); + } + result + } "pdfImport" => { let crop = d.s("crop"); // One page number, 1 or more; a blank field is page 1. A range or list ("4-5", "2,5"), a diff --git a/crates/ui-egui/src/i18n/ka.rs b/crates/ui-egui/src/i18n/ka.rs index 87fae4392..0c2ce3dc9 100644 --- a/crates/ui-egui/src/i18n/ka.rs +++ b/crates/ui-egui/src/i18n/ka.rs @@ -25,6 +25,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "ასლის შენახვა…"), ("Revert", "წინა ვერსიაზე დაბრუნება"), ("Place…", "განთავსება…"), + ("Place Contact Sheet…", "საკონტაქტო ფურცლის განთავსება…"), + ("Place Contact Sheet", "საკონტაქტო ფურცლის განთავსება"), + ("Place loaded images on new pages, in file order.", "ჩატვირთული გამოსახულებების ახალ გვერდებზე განთავსება, ფაილების თანმიმდევრობით."), + ("Page margin", "გვერდის ველი"), ("Image import cancelled while a dialog is open", "გამოსახულებების იმპორტი გაუქმდა, რადგან დიალოგი გახსნილია"), ("Place cancelled while a dialog is open", "განთავსება გაუქმდა, რადგან დიალოგი ღიაა"), ("Export PDF…", "PDF ექსპორტი…"), diff --git a/crates/ui-egui/src/i18n/sv.rs b/crates/ui-egui/src/i18n/sv.rs index 8d7c46e15..40b0b2488 100644 --- a/crates/ui-egui/src/i18n/sv.rs +++ b/crates/ui-egui/src/i18n/sv.rs @@ -21,6 +21,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Spara en kopia…"), ("Revert", "Återgå"), ("Place…", "Placera…"), + ("Place Contact Sheet…", "Placera kontaktark…"), + ("Place Contact Sheet", "Placera kontaktark"), + ("Place loaded images on new pages, in file order.", "Placera inlästa bilder på nya sidor, i filordning."), + ("Page margin", "Sidmarginal"), ("Export PDF…", "Exportera PDF…"), ("Print…", "Skriv ut…"), ("Print", "Skriv ut"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index 7e8ccdddc..60cba865d 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -146,6 +146,25 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Save a Copy…", ["Kopie speichern …", "Enregistrer une copie…", "Guardar una copia…", "コピーを保存…", "保存副本…"]), ("Revert", ["Zurück zur letzten Version", "Version précédente", "Volver a la versión guardada", "復帰", "恢复到上次保存"]), ("Place…", ["Platzieren …", "Importer…", "Colocar…", "配置…", "置入…"]), + ( + "Place Contact Sheet…", + ["Kontaktbogen platzieren…", "Importer une planche-contact…", "Colocar hoja de contactos…", "コンタクトシートを配置…", "置入联系表…"], + ), + ( + "Place Contact Sheet", + ["Kontaktbogen platzieren", "Importer une planche-contact", "Colocar hoja de contactos", "コンタクトシートを配置", "置入联系表"], + ), + ( + "Place loaded images on new pages, in file order.", + [ + "Geladene Bilder in Dateireihenfolge auf neuen Seiten platzieren.", + "Importer les images chargées sur de nouvelles pages, dans l’ordre des fichiers.", + "Colocar las imágenes cargadas en páginas nuevas, en el orden de los archivos.", + "読み込んだ画像をファイル順に新しいページに配置します。", + "按文件顺序将载入的图像置入新页面。", + ], + ), + ("Page margin", ["Seitenrand", "Marge de page", "Margen de página", "ページマージン", "页边距"]), ( "Image import cancelled while a dialog is open", [ diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b49b8c7f4..5228d3c60 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -148,6 +148,10 @@ fn run_ui_part1(app: &mut DesignApp, id: &str, p: &Value) -> Option app.pick_and_open("place"), }, + "app.contactSheetDialog" => { + crate::dialogs::open_contact_sheet(app); + Ok(Value::Null) + } "app.placeWithOptions" => { // Word/RTF Import Options: style mapping and conflicts before the text lands. let Some(path) = p.get("path").and_then(Value::as_str) else { return Some(rerun_with_path(app, "place", id, p, "path")) }; diff --git a/crates/ui-egui/src/menus/tables.rs b/crates/ui-egui/src/menus/tables.rs index e7907e7da..50904af4f 100644 --- a/crates/ui-egui/src/menus/tables.rs +++ b/crates/ui-egui/src/menus/tables.rs @@ -16,6 +16,7 @@ pub const MENUS: &[(&str, &[&str])] = &[ "cmd:file.revert", "-", "ui:app.placeDialog", + "ui:app.contactSheetDialog", "ui:app.placeWithOptions", "-", "ui:app.exportPdf", diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 0fbdaca45..db6d9eb54 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -21,6 +21,7 @@ pub const UI_COMMANDS: &[(&str, &str, Option<&str>, &str)] = &[ Some("Cmd+D"), "{path?, paths?: [path] (several, loaded into the place cursor in order)} — without either, choose the files in a dialog", ), + ("app.contactSheetDialog", "Place Contact Sheet…", None, "{} — place the images loaded in the place cursor on new pages"), ("app.saveDialog", "Save As…", Some("Cmd+Shift+S"), "{path?} — without a path, choose where in a dialog"), ("app.save", "Save", Some("Cmd+S"), "{}"), ("app.quit", "Quit DesignCraft", Some("Cmd+Q"), "{} — close the window; each document with unsaved changes asks first"), diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 997414bcd..ea5ee549b 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -1,4 +1,4 @@ -# Multiple images +# Multiple images and contact sheets Choose **File > Place** (Cmd+D on macOS) and select several images. They load into a placement cursor in the order supplied by the file picker. The cursor shows the next image's thumbnail and, beside it, how many are loaded ("(6)"). @@ -8,7 +8,9 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. - Press Escape or select another tool to cancel the remaining placement. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +For larger selections, choose **File > Place Contact Sheet…** after loading the images. Set columns, rows, gutter and page margin. All remaining images are fitted proportionally and centered in equal frames across as many new pages as needed. The default is 3 columns by 4 rows. New pages use the last document page's size and have no parent-page artwork. The entire contact sheet is one undo step. + +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid or contact-sheet area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. @@ -20,7 +22,8 @@ All placement behavior is available through the engine, CLI, control channel and {"command":"place.load","params":{"files":[{"path":"/images/one.png"},{"path":"/images/two.jpg"}]}} {"command":"place.load","params":{"files":[{"path":"/images/three.png"}],"append":true}} {"command":"place.grid","params":{"rect":[36,36,576,756],"columns":3,"rows":4,"gutter":6}} +{"command":"place.contactSheet","params":{"columns":3,"rows":4,"gutter":6,"margin":36}} {"command":"place.cancel","params":{}} ``` -Each source can instead supply `base64` and `name`, including on the web. `append` queues the images after those already loaded instead of replacing them. `place.grid` consumes only the images that fit. Undo removes placed frames together, while the cursor remains at its current position in the queue. The UI command `app.placeDialog` takes `paths` for a File > Place of several files without the dialog. +Each source can instead supply `base64` and `name`, including on the web. `append` queues the images after those already loaded instead of replacing them. `place.grid` consumes only the images that fit; `place.contactSheet` consumes the entire queue. Undo removes placed frames/pages together, while the cursor remains at its current position in the queue. The UI command `app.placeDialog` takes `paths` for a File > Place of several files without the dialog. From a10e288a581d2fda01275b0a07c2f148852f5f76 Mon Sep 17 00:00:00 2001 From: texjer Date: Tue, 3 Nov 2026 21:54:43 -0500 Subject: [PATCH 013/322] Place: dropped images load the place cursor, in the order they came Split out of #2073. Port of #1307's drops and #1666. - Several images dropped together load the place cursor in the order they came, each run of them where it comes among the other files, after the images it already holds; click to place them one by one. - One image dropped off a frame that takes it loads the place cursor instead of being placed at once; on such a frame it still fills it. - A drop is handled in its order, each file at its own pointer, and a dialog (a multi-page PDF's Import Options, an alert) cancels the rest. - On the web, files dropped together are read as one batch (none if one can't be read), and a single dropped image loads the place cursor. --- ROADMAP.md | 1 + apps/designcraft-web/src/browser_policy.rs | 39 ++++++- apps/designcraft-web/src/web.rs | 23 +++- crates/ui-egui/src/app/files.rs | 97 ++++++++++++---- crates/ui-egui/src/app/input.rs | 9 +- crates/ui-egui/src/tests.rs | 128 ++++++++++++++++++++- docs/multi-image-placement.md | 10 +- 7 files changed, 269 insertions(+), 38 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 3cef01494..8aedbe1f0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -405,6 +405,7 @@ Newest first. - **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change. - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. +- **2026-10-30** · Dropping images from the file manager works as in InDesign: images dropped together load the place cursor in the order they came, and one image dropped off a frame that takes it loads the place cursor instead of being placed at once (on a frame it still fills it). Documents and text files dropped keep opening and flowing as before. Ported from #1307 and #1666; see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). diff --git a/apps/designcraft-web/src/browser_policy.rs b/apps/designcraft-web/src/browser_policy.rs index 524df6cc5..ca82c71ca 100644 --- a/apps/designcraft-web/src/browser_policy.rs +++ b/apps/designcraft-web/src/browser_policy.rs @@ -1,4 +1,4 @@ -//! Pure browser startup and download metadata policies. +//! Browser startup, download metadata, and atomic import policies. /// Query flags are case-sensitive decoded keys. Values are ignored: `?sample=false` /// still enables sample startup, and repeated keys have the same presence semantics. @@ -65,3 +65,40 @@ mod tests { } } } + +/// Read a drop in order, publishing nothing unless every file can be read. +pub(crate) async fn read_batch(files: impl IntoIterator, mut read: F) -> Result, E> +where + F: FnMut(T) -> Fut, + Fut: std::future::Future>, +{ + let mut result = Vec::new(); + for file in files { + result.push(read(file).await?); + } + Ok(result) +} + +#[cfg(test)] +mod batch_tests { + #[test] + fn failed_read_aborts_the_whole_batch() { + use std::{ + future::Future, + task::{Context, Poll, Waker}, + }; + let mut seen = Vec::new(); + let result = { + let future = super::read_batch([1, 2, 3], |n| { + seen.push(n); + std::future::ready(if n == 2 { Err("read failed") } else { Ok(n) }) + }); + let mut future = std::pin::pin!(future); + future.as_mut().poll(&mut Context::from_waker(Waker::noop())) + }; + assert_eq!(result, Poll::Ready(Err("read failed"))); + assert_eq!(seen, [1, 2]); + let mut success = std::pin::pin!(super::read_batch([3, 1], |n| std::future::ready(Ok::<_, ()>(n)))); + assert_eq!(success.as_mut().poll(&mut Context::from_waker(Waker::noop())), Poll::Ready(Ok(vec![3, 1]))); + } +} diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 8b23ef6b7..c87581e32 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -357,18 +357,29 @@ impl eframe::App for WebShell { let _ = self.graphics.run_if_healthy(|| { // Dropped files belong to this host iteration's raw input, not to stale logic input: // read them here once, before the batch is saved as pending for a hidden pass. - for f in std::mem::take(&mut raw.dropped_files) { + // Files dropped together arrive together, in their order, so several images load the + // place cursor as one batch. + let dropped = std::mem::take(&mut raw.dropped_files); + if !dropped.is_empty() { let request = self.app.import_request("drop"); let inbox = self.inbox.clone(); let ctx = ctx.clone(); wasm_bindgen_futures::spawn_local(async move { - let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); - match f.bytes_async().await { - Ok(bytes) => { - inbox.lock().unwrap_or_else(|e| e.into_inner()).push(ImportedFile { request, name, bytes }); + let files = crate::browser_policy::read_batch(dropped, |f| { + let request = request.clone(); + async move { + let name = f.path().file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "dropped".into()); + let bytes = f.bytes_async().await.map_err(|e| format!("couldn't read dropped file {name}: {e}"))?; + Ok::<_, String>(ImportedFile { request, name, bytes }) + } + }) + .await; + match files { + Ok(files) => { + inbox.lock().unwrap_or_else(|e| e.into_inner()).extend(files); ctx.request_repaint(); } - Err(e) => log::error!("couldn't read dropped file {name}: {e}"), + Err(error) => log::error!("{error}"), } }); } diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3df85b504..bb0a20661 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -162,7 +162,7 @@ impl DesignApp { let Some(inbox) = self.services.inbox.clone() else { return }; let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); let cursor_image = |file: &ImportedFile| { - file.request.purpose == "place" + matches!(file.request.purpose.as_str(), "place" | "drop") && !file.name.to_ascii_lowercase().ends_with(".pdf") && (is_cursor_image(&file.name) || designcraft_render::image_size(&file.bytes).is_some()) }; @@ -175,7 +175,7 @@ impl DesignApp { shortcut_import::import_delivered(self, &file.bytes); continue; } - let placing = file.request.purpose == "place"; + let placing = matches!(file.request.purpose.as_str(), "place" | "drop"); let mut group = vec![]; if cursor_image(&file) { while let Some(next) = @@ -184,8 +184,9 @@ impl DesignApp { group.push(next); } } - // Several images: into the place cursor. - if !group.is_empty() { + // Several images, or one dropped (a browser drop has no position to place it at or + // frame to fill): into the place cursor. + if !group.is_empty() || (file.request.purpose == "drop" && cursor_image(&file)) { if self.ui.dialog.is_some() { self.status(crate::i18n::tr(&self.ui.language, "Image import cancelled while a dialog is open")); continue; @@ -262,9 +263,9 @@ impl DesignApp { } /// A file dropped on the window: documents open, the swatches in a swatch exchange (.ase) file - /// are loaded, and anything else is placed on the spread in view (a parent spread while parents - /// are being edited). A file without an extension opens when its content is a DesignCraft or - /// IDML document. + /// are loaded, an image loads into the place cursor, and anything else is placed on the spread + /// in view (a parent spread while parents are being edited). A file without an extension + /// opens when its content is a DesignCraft or IDML document. pub fn open_dropped(&mut self, path: &str) -> Result { self.open_dropped_at(path, None) } @@ -273,18 +274,48 @@ impl DesignApp { /// window's coordinates. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn open_dropped_files(&mut self, files: &[egui::DroppedFileHandle], pointer: Option) { + let drops = files.iter().map(|f| f.path().to_string_lossy().to_string()).filter(|p| !p.is_empty()).map(|p| (p, pointer)).collect(); + self.open_dropped_batch(drops); + } + + /// Files dropped on the window together, each with the pointer it was dropped at, handled in + /// the order they came. Each that isn't an image opens or is placed as + /// [`Self::open_dropped_at`] does at its own pointer. One image is dropped as that does too + /// (filling the frame under the pointer, else loading the place cursor); several load the place + /// cursor, each run of them where it came in the order, after any images it already holds, + /// whatever is under the pointer: click to place them one by one, drag with the arrow keys for + /// a grid. The rest of the drop is cancelled once a file opens a dialog (a multi-page PDF's + /// Import Options, an alert), as File › Place with several chosen is. + pub fn open_dropped_batch(&mut self, drops: Vec<(String, Option)>) { + let several = drops.iter().filter(|(p, _)| is_cursor_image(p)).count() > 1; + // Only the first graphic of a drop fills the frame under the pointer. let mut frame_free = true; - for f in files { - let p = f.path().to_string_lossy().to_string(); - if !p.is_empty() { - let _ = self.place_dropped(&p, pointer, &mut frame_free); + let mut images = Vec::new(); + // `None` at the end flushes the images left. + for drop in drops.into_iter().map(Some).chain([None]) { + if several + && let Some((path, _)) = &drop + && is_cursor_image(path) + { + images.push(path.clone()); + continue; } + // A file that can't be placed has its alert, which cancels the rest below. + if !images.is_empty() { + let _ = self.place_paths(std::mem::take(&mut images)); + } + let Some((path, pointer)) = drop else { break }; + if self.ui.dialog.is_some() { + self.status(crate::i18n::tr(&self.ui.language, "Place cancelled while a dialog is open")); + return; + } + let _ = self.place_dropped(&path, pointer, &mut frame_free); } } /// [`Self::open_dropped`] at the pointer: a graphic dropped on an empty or graphic frame fills - /// it, elsewhere its top left lands where the file was dropped on the canvas; text goes to a - /// new frame on the document page there. + /// it; elsewhere an image loads into the place cursor, and another graphic's top left lands + /// where the file was dropped on the canvas; text goes to a new frame on the document page there. pub fn open_dropped_at(&mut self, path: &str, pointer: Option) -> Result { self.place_dropped(path, pointer, &mut true) } @@ -303,13 +334,22 @@ impl DesignApp { if document { return self.open_file("file.open", json!({"path": path})); } - let mut params = json!({"path": path}); - // A graphic dropped on an empty or graphic frame fills it, as File > Place does. Text keeps + // A graphic dropped on a frame that takes one fills it, as File > Place does. Text keeps // getting a frame of its own, so it never replaces the image in a graphic frame. let frame = if *frame_free && !designcraft_textimport::is_text_file(path) { canvas::drop_frame(self, pointer) } else { None }; - if let (Some(frame), Some(o)) = (frame, params.as_object_mut()) { - o.insert("frame".into(), json!(frame.0)); + if let Some(frame) = frame { + let placed = self.open_file("file.place", json!({"path": path, "frame": frame.0})); + if placed.is_ok() { + *frame_free = false; + } + return placed; } + // An image dropped anywhere else waits in the place cursor, after any it already holds. + if is_cursor_image(path) { + let append = self.session.loaded.is_some(); + return self.open_file("place.load", json!({"path": path, "append": append})); + } + let mut params = json!({"path": path}); if let (Some((sr, at)), Some(o)) = (canvas::drop_point(self, pointer), params.as_object_mut()) { o.insert("spread".into(), serde_json::to_value(sr).unwrap_or(Value::Null)); o.insert("x".into(), json!(at.x)); @@ -319,11 +359,7 @@ impl DesignApp { o.insert("page".into(), json!(st.doc.first_page_of_spread(si) + pi + 1)); } } - let placed = self.open_file("file.place", params); - if frame.is_some() && placed.is_ok() { - *frame_free = false; - } - placed + self.open_file("file.place", params) } /// Queue files the operating system asked the app to open. They can arrive before the window @@ -908,6 +944,23 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "one.pdf", "b.png"], "in the order dropped, all in the cursor"); } + /// A browser drop of one image (it has no position or frame under it) loads the place + /// cursor; images dropped together load it at once, after what it holds. + #[test] + fn browser_dropped_images_load_the_place_cursor() { + let mut app = app(); + let request = app.import_request("drop"); + deliver(&mut app, request, "one.png", png(200)); + assert_eq!(app.session.tool_id(), "placeGun"); + assert!(app.session.doc().unwrap().doc.spreads[0].items.is_empty(), "nothing placed yet"); + let request = app.import_request("drop"); + for (name, v) in [("two.png", 90), ("three.png", 60)] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes: png(v) }); + } + app.drain_inbox(); + assert_eq!(loaded_names(&app), ["one.png", "two.png", "three.png"]); + } + #[test] fn batch_cancel_status_uses_the_interface_language() { let mut app = app(); diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 2682478c4..2281d3643 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -154,13 +154,10 @@ impl DesignApp { if drops.is_empty() { return; } - // Each file keeps the pointer it was dropped at; the system is asked once, for those - // that came without one. + // Dropped together, they go together: several images load the place cursor at once. Each + // file keeps the pointer it was dropped at. let system = drops.iter().any(|d| d.pointer.is_none()).then(|| self.system_pointer(ctx)).flatten(); - let mut frame_free = true; - for drop in drops { - let _ = self.place_dropped(&drop.path, drop.pointer.or(system), &mut frame_free); - } + self.open_dropped_batch(drops.into_iter().map(|d| (d.path, d.pointer.or(system))).collect()); } /// Where the pointer is in the window, asked of the system ([`crate::Services::pointer`]), diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e53e603a1..1f8cedf68 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -884,10 +884,20 @@ fn a_graphic_dropped_on_a_frame_fills_it() { let r = app.open_dropped_at(&path.to_string_lossy(), Some(inside)); let _ = std::fs::remove_file(&path); assert_eq!(r.unwrap()["id"].as_u64(), Some(frame), "the frame under the pointer is filled"); + assert!(app.session.loaded.is_none(), "nothing waits in the place cursor"); let d = &app.session.doc().unwrap().doc; assert_eq!(d.spreads[0].items.len(), 1, "no new object"); assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Graphic(_))); assert!(canvas::drop_frame(&app, Some(outside)).is_none(), "an empty spot on the page is no frame"); + // Dropped again, it replaces the image there rather than loading the place cursor. + let path = dropped_png("dropframe-again"); + app.open_dropped_at(&path.to_string_lossy(), Some(inside)).unwrap(); + let _ = std::fs::remove_file(&path); + let d = &app.session.doc().unwrap().doc; + assert_eq!(d.spreads[0].items.len(), 1, "still no new object"); + let designcraft_doc::Content::Graphic(g) = &d.item(designcraft_doc::ItemId(frame)).unwrap().content else { panic!("a graphic frame") }; + assert!(d.assets[&g.asset].name.contains("dropframe-again"), "the frame shows the new image"); + assert!(app.session.loaded.is_none(), "nothing waits in the place cursor"); // Text dropped there gets a frame of its own and leaves the image in place. let text = std::env::temp_dir().join(format!("designcraft-ui-{}-dropframe.txt", std::process::id())); std::fs::write(&text, "Dropped words").unwrap(); @@ -920,6 +930,7 @@ fn a_file_dropped_without_pointer_events_fills_the_frame_under_the_system_pointe ctx.run_ui(raw, |ui| app.take_pending_drops(ui.ctx())).textures_delta.clear(); let _ = std::fs::remove_file(&path); assert!(app.pending_drops.is_empty()); + assert!(app.session.loaded.is_none(), "nothing waits in the place cursor at {zoom}"); let d = &app.session.doc().unwrap().doc; assert_eq!(d.spreads[0].items.len(), 1, "no new object at {zoom}"); let designcraft_doc::Content::Graphic(g) = &d.item(designcraft_doc::ItemId(frame)).unwrap().content else { @@ -940,7 +951,8 @@ fn a_locked_frame_is_not_a_drop_target() { r.unwrap(); let d = &app.session.doc().unwrap().doc; assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Unassigned), "the locked frame stays empty"); - assert_eq!(d.spreads[0].items.len(), 2, "the graphic became a new object"); + assert_eq!(d.spreads[0].items.len(), 1, "no new object yet"); + assert!(app.session.loaded.is_some(), "the image waits in the place cursor"); } #[test] @@ -954,8 +966,10 @@ fn only_the_first_graphic_of_a_drop_fills_the_frame() { let _ = (std::fs::remove_file(&first), std::fs::remove_file(&second)); assert_eq!(a.unwrap()["id"].as_u64(), Some(frame)); assert_ne!(b.unwrap()["id"].as_u64(), Some(frame), "the second graphic doesn't replace the first"); + // An image dropped off a frame that takes it waits in the place cursor. + assert!(app.session.loaded.is_some(), "the second image waits in the place cursor"); let d = &app.session.doc().unwrap().doc; - assert_eq!(d.spreads[0].items.len(), 2, "the second graphic is a new object"); + assert_eq!(d.spreads[0].items.len(), 1, "no new object"); assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Graphic(_))); } @@ -971,11 +985,121 @@ fn a_file_dropped_while_a_parent_is_open_lands_on_the_parent() { let r = app.open_dropped(&path.to_string_lossy()); let _ = std::fs::remove_file(&path); r.unwrap(); + // The image waits in the place cursor; a click on the parent spread places it there. + assert!(app.session.loaded.is_some()); + let st = app.session.active().unwrap(); + let at = designcraft_tools::CanvasLayout::new(&st.doc, st.editing_parents) + .slot(designcraft_doc::SpreadRef::Parent(0)) + .unwrap() + .to_canvas(designcraft_geom::Point::new(50.0, 50.0)); + let v = designcraft_engine::ViewInfo::at_zoom(1.0); + for kind in [designcraft_tools::PointerKind::Down, designcraft_tools::PointerKind::Up] { + app.session.pointer(&designcraft_tools::PointerEvent::new(kind, at.x, at.y), v).unwrap(); + } let d = &app.session.doc().unwrap().doc; assert_eq!(d.parents[0].items.len(), 1, "the graphic is on the parent spread"); assert!(d.spreads.iter().all(|s| s.items.is_empty()), "no document page gets it"); } +/// The names of the images in the place cursor, the one a click places first. +fn loaded_names(app: &DesignApp) -> Vec { + let doc = &app.session.doc().unwrap().doc; + app.session.loaded.iter().chain(app.session.loaded_queue.iter()).map(|g| doc.assets[&g.asset].name.clone()).collect() +} + +/// One image dropped where no frame can take it loads the place cursor instead of being placed: +/// the next click places it. A frame selected doesn't take it, and another image dropped +/// meanwhile queues after it. +#[test] +fn a_single_image_dropped_off_a_frame_loads_the_place_cursor() { + let (mut app, frame, _, outside) = app_with_drop_frame(); + app.run("selection.set", json!({"ids": []})).unwrap(); + let first = dropped_png("drop-loads-a"); + let second = dropped_png("drop-loads-b"); + app.open_dropped_at(&first.to_string_lossy(), Some(outside)).unwrap(); + assert_eq!(app.session.tool_id(), "placeGun"); + assert_eq!(loaded_names(&app).len(), 1); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), 1, "nothing placed yet"); + app.run("selection.set", json!({"ids": [frame]})).unwrap(); + app.open_dropped_at(&second.to_string_lossy(), Some(outside)).unwrap(); + let _ = (std::fs::remove_file(&first), std::fs::remove_file(&second)); + let names = loaded_names(&app); + assert_eq!(names.len(), 2, "{names:?}"); + assert!(names[0].contains("drop-loads-a") && names[1].contains("drop-loads-b"), "{names:?}"); + let d = &app.session.doc().unwrap().doc; + assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Unassigned)); + app.run("place.drop", json!({"x": 300, "y": 300})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc.spreads[0].items.len(), 2, "the click placed the first"); + assert_eq!(app.session.tool_id(), "placeGun", "the second is still loaded"); +} + +/// Several images dropped together load the place cursor in the order they came, even over a +/// frame; a file that isn't an image keeps its own drop behaviour (text gets a frame). +#[test] +fn several_dropped_images_load_the_place_cursor_in_order() { + let (mut app, frame, inside, _) = app_with_drop_frame(); + app.run("selection.set", json!({"ids": []})).unwrap(); + let a = dropped_png("drop-many-a"); + let b = std::env::temp_dir().join(format!("designcraft-ui-{}-drop-many-b.svg", std::process::id())); + std::fs::write(&b, br##""##).unwrap(); + let c = dropped_png("drop-many-c"); + let text = std::env::temp_dir().join(format!("designcraft-ui-{}-drop-many.txt", std::process::id())); + std::fs::write(&text, "Dropped words").unwrap(); + let paths = [&a, &text, &b, &c].map(|p| p.to_string_lossy().to_string()); + app.open_dropped_batch(paths.iter().map(|p| (p.clone(), Some(inside))).collect()); + for p in [&a, &b, &c, &text] { + let _ = std::fs::remove_file(p); + } + let names = loaded_names(&app); + assert_eq!(names.len(), 3, "{names:?}"); + for (name, want) in names.iter().zip(["drop-many-a", "drop-many-b", "drop-many-c"]) { + assert!(name.contains(want), "{names:?}"); + } + assert_eq!(app.session.tool_id(), "placeGun"); + let d = &app.session.doc().unwrap().doc; + assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Unassigned), "the frame isn't filled"); + assert_eq!(d.spreads[0].items.len(), 2, "the text got a frame of its own"); + // Clicks place them one by one; Escape unloads the rest. + app.run("place.drop", json!({"x": 300, "y": 300})).unwrap(); + assert_eq!(app.session.loaded_queue.len(), 1); + let mods = designcraft_tools::Mods::default(); + app.session.tool_key(designcraft_tools::ToolKey::Escape, mods, designcraft_engine::ViewInfo::at_zoom(1.0)).unwrap(); + assert!(app.session.loaded.is_none() && app.session.loaded_queue.is_empty()); + assert_eq!(app.session.tool_id(), "selection"); +} + +/// A drop is handled in the order its files came, each at its own pointer: an image dropped on a +/// frame before a document fills that frame in the document that was open, not in the one the +/// drop opens after it. +#[test] +fn a_mixed_drop_keeps_its_order() { + let (mut app, frame, inside, outside) = app_with_drop_frame(); + let mut other = DesignApp::new(Session::new(), Services::default()); + other.run("file.new", json!({})).unwrap(); + let document = std::env::temp_dir().join(format!("designcraft-ui-{}-drop-mixed.designcraft", std::process::id())); + other.run("file.saveAs", json!({"path": document})).unwrap(); + let image = dropped_png("drop-mixed"); + let text = std::env::temp_dir().join(format!("designcraft-ui-{}-drop-mixed.txt", std::process::id())); + std::fs::write(&text, "Dropped words").unwrap(); + let drops = vec![ + (image.to_string_lossy().to_string(), Some(inside)), + (text.to_string_lossy().to_string(), Some(outside)), + (document.to_string_lossy().to_string(), Some(outside)), + ]; + app.open_dropped_batch(drops); + for p in [&image, &text, &document] { + let _ = std::fs::remove_file(p); + } + assert_eq!(app.session.documents().len(), 2, "the document opened last"); + let d = &app.session.documents()[0].doc; + assert!( + matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Graphic(_)), + "the image filled the frame in the document open before the drop" + ); + assert_eq!(d.spreads[0].items.len(), 2, "the text got a frame of its own"); + assert!(app.session.loaded.is_none(), "nothing waits in the place cursor"); +} + #[test] fn file_open_failures_show_an_alert() { let path = unreadable_file("open.designcraft"); diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 997414bcd..6281de637 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -1,6 +1,6 @@ # Multiple images -Choose **File > Place** (Cmd+D on macOS) and select several images. They load into a placement cursor in the order supplied by the file picker. The cursor shows the next image's thumbnail and, beside it, how many are loaded ("(6)"). +Choose **File > Place** (Cmd+D on macOS) and select several images, or drop a selection of images from your file manager onto the document. Multiple images load into a placement cursor in the order supplied by the file picker (or the drop). The cursor shows the next image's thumbnail and, beside it, how many are loaded ("(6)"). - Click to place the next image at its natural size. - Drag to draw its frame: it keeps the image's proportions, and shows the scale beside the pointer. @@ -10,6 +10,14 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +## Dropping files + +- One image dropped on an empty or graphic frame fills it, or replaces the image in it. +- One image dropped anywhere else loads into the place cursor, as File > Place does with nothing selected: the next click or drag places it. +- Several images dropped together load into the place cursor in the order they came, wherever they are dropped. +- Images dropped while the cursor already holds some queue after them. +- DesignCraft, IDML and InDesign documents open; text files (.txt, .docx, .rtf, .md) and spreadsheets go into a new frame where they are dropped; a PDF is placed where it is dropped (or fills the frame under it); swatch exchange (.ase) files load their swatches. + Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. ## Automation From ea39c914d28ca710e77c7c12ba1dc3ebc65ba0b2 Mon Sep 17 00:00:00 2001 From: Hamza Date: Wed, 4 Nov 2026 13:22:23 +0500 Subject: [PATCH 014/322] cli: a missing value stops the line before any export, help wins as a value, and every subcommand's usage lists its options --- apps/designcraft-cli/src/main.rs | 25 +++++++++++++++++-------- apps/designcraft-cli/tests/it/args.rs | 25 +++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 8 deletions(-) diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index daf91f305..c79e13f65 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -42,7 +42,7 @@ use designcraft_engine::Session; use serde_json::{Value, json}; /// The usage block. Shared by `--help` (stdout, success) and an unknown command (stderr, failure). -const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...\n the roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. Each may be given more than once; a kind\n left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli validate-pdf FILE.pdf # built-in PDF/X-4 checks (including visible unembedded fonts)\n designcraft-cli thumbnail FILE.designcraft OUT.png [SIZE] # the saved first-page preview, at most SIZE px\n designcraft-cli links\n designcraft-cli --version"; +const USAGE: &str = "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\n (--page, --scale and --pdf-options apply to the exports that follow them)\n designcraft-cli commands [FILTER]\n designcraft-cli describe COMMAND\n designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going]\n designcraft-cli app [--port PORT] COMMAND [JSON] | --method METHOD [JSON]\n designcraft-cli mcp [--connect PORT] [--sample] [--automation-read-root DIR]... [--automation-write-root DIR]...\n the roots confine every file the agent's commands read (open, placed images, data sources, libraries) and\n write (save, export, package) to those folders, links followed. Each may be given more than once; a kind\n left out grants none of its access.\n They run the in-process server, so they conflict with --connect (a running app is not confined by them).\n designcraft-cli perf [--pages N] [--frames N] [--chars N] [--images N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli validate-pdf FILE.pdf [--standard x4|x1a] # built-in PDF/X checks (including visible unembedded fonts)\n designcraft-cli thumbnail FILE.designcraft OUT.png [SIZE] # the saved first-page preview, at most SIZE px\n designcraft-cli links\n designcraft-cli --version"; /// `script --help`: the script syntax, otherwise only in `describe script.run` and docs/agents.md. const SCRIPT_HELP: &str = r#"usage: designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going] @@ -124,12 +124,10 @@ fn can_be_value(v: &str) -> bool { !(v.starts_with('-') && v.len() > 1 && v.parse::().is_err()) } -/// The usage lines for one subcommand, for ` --help`. Each line of [`USAGE`] names its -/// subcommand, and the indented lines after it belong to it. -/// The part of [`USAGE`] that describes `sub`, or `None` when it describes no such subcommand -- -/// which is how ` --help` tells a real subcommand from a typo. Falling back to the whole -/// usage made `bogus --help` print it and succeed, bypassing the unknown-command failure (noted -/// in review). +/// The usage lines for one subcommand, for ` --help`: each line of [`USAGE`] names its +/// subcommand, and the indented lines after it belong to it. `None` when no line describes `sub`, +/// which is how ` --help` tells a real subcommand from a typo; falling back to the whole usage +/// made `bogus --help` print it and succeed, bypassing the unknown-command failure. fn usage_for(sub: &str) -> Option { let mut out = Vec::new(); let mut keep = false; @@ -161,7 +159,10 @@ fn main() -> ExitCode { } } // ` --help` asks about that subcommand, which every parser but `script`'s read as an - // unknown option (photocraft#423). It goes to stdout and succeeds, as `--help` does. + // unknown option (photocraft#423). It goes to stdout and succeeds, as `--help` does. It wins + // wherever it appears after the subcommand, even where an option would take it as its value + // (`run --in -h`): no file is named `-h`, and asking for help is what that line most likely + // means. if let Some(sub) = args.first().map(String::as_str) && !matches!(sub, "--help" | "-h" | "help" | "script") && args[1..].iter().any(|a| a == "--help" || a == "-h") @@ -442,6 +443,14 @@ impl Export { } fn run(args: &[String]) -> Result<(), String> { + // Nothing runs on a line with an option missing its value: found here, before the first export + // writes anything, with the message `value()` gives. Left to `value()` alone, `--export a.png + // --scale --export b.png` wrote a.png and only then said `--scale needs a value`. + for (i, a) in args.iter().enumerate() { + if matches!(a.as_str(), "--page" | "--scale" | "--pdf-options" | "--export" | "--all-pages" | "--in" | "--cmd") { + value(a, args.get(i + 1))?; + } + } if let Some(opt) = option_after_last_export(args) { return Err(format!( "{opt} has no --export or --all-pages after it; options apply to the exports that follow them, so put it before its --export" diff --git a/apps/designcraft-cli/tests/it/args.rs b/apps/designcraft-cli/tests/it/args.rs index 84a98c34a..a854f2aba 100644 --- a/apps/designcraft-cli/tests/it/args.rs +++ b/apps/designcraft-cli/tests/it/args.rs @@ -280,9 +280,34 @@ fn a_missing_value_names_its_option() { assert!(err.contains("needs"), "{args:?}: {err:?}"); } assert!(!png.exists(), "nothing is exported"); + + // A missing value after an export is found before that export runs: the line writes nothing, + // as a malformed line always did. + let first = dir.join("first.png"); + let line = ["run", "--sample", "--export", first.to_str().unwrap(), "--scale", "--export", png.to_str().unwrap()]; + let err = run(&line).failed("a missing value after an export"); + assert!(err.contains("--scale needs a value"), "{err:?}"); + assert!(!first.exists(), "the export before it was not written"); let _ = std::fs::remove_dir_all(&dir); } +/// `--help` wins wherever it appears after the subcommand, even where an option would take it as +/// its value: `run --in -h` prints `run`'s usage and opens nothing. +#[test] +fn help_wins_even_where_an_option_would_take_it_as_a_value() { + for flag in ["-h", "--help"] { + let out = run(&["run", "--in", flag]).succeeded(&format!("run --in {flag}")); + assert!(out.contains("designcraft-cli run"), "{out:?}"); + } + // And each subcommand's usage lists every option it takes. + let perf = run(&["perf", "--help"]).succeeded("perf --help"); + for option in ["--pages", "--frames", "--chars", "--images", "--runs", "--strict"] { + assert!(perf.contains(option), "perf --help lists {option}: {perf:?}"); + } + let validate = run(&["validate-pdf", "--help"]).succeeded("validate-pdf --help"); + assert!(validate.contains("--standard"), "{validate:?}"); +} + /// An option that takes no value does not swallow the token after it: that token is read as the /// next argument, and refused if it is not one. #[test] From cb97fcb0bdcccea9a192b5eeedfc6b533bb4f667 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 10:31:22 -0500 Subject: [PATCH 015/322] Place: a grid drag too small for its cells previews and places one frame The place cursor's grid preview fell back to the raw drag rectangle when the cells had no positive size, while the release still sent `place.grid`, which rejected the area. Both now use the same cell calculation (`grid_cells`), and a grid with no room for its cells shows and places the single proportional frame of an ordinary drag. --- crates/tools/src/nav.rs | 41 +++++++++++++++++++++++------------ crates/tools/src/tests.rs | 31 ++++++++++++++++++++++++++ docs/multi-image-placement.md | 2 +- 3 files changed, 59 insertions(+), 15 deletions(-) diff --git a/crates/tools/src/nav.rs b/crates/tools/src/nav.rs index 2b84010d1..762a4f0f3 100644 --- a/crates/tools/src/nav.rs +++ b/crates/tools/src/nav.rs @@ -149,9 +149,10 @@ impl Tool for PlaceGun { if click { return vec![Action::Exec("place.drop".into(), json!({"spread": crate::spread_json(sr), "x": sa.x, "y": sa.y}))]; } - // Arrow keys during the drag set a grid: the queued images fill its cells. - if self.columns > 1 || self.rows > 1 { - let r = designcraft_geom::Rect::from_points(sa, b); + // Arrow keys during the drag set a grid: the queued images fill its cells. A drag + // too small for the grid's cells places one frame instead, as the overlay shows. + let r = designcraft_geom::Rect::from_points(sa, b); + if !grid_cells(r, self.columns, self.rows).is_empty() { return vec![Action::Exec( "place.grid".into(), json!({"spread": crate::spread_json(sr), "rect": [r.x0, r.y0, r.x1, r.y1], "columns": self.columns, "rows": self.rows}), @@ -195,8 +196,13 @@ impl Tool for PlaceGun { // Under the drag threshold the release is a click (actual size where it was pressed): // no frame is drawn yet, the loaded cursor shows what lands. let click = (self.cur - a).hypot() < cx.tol(3.0); - if !click && (self.columns > 1 || self.rows > 1) { - return grid_overlays(designcraft_geom::Rect::from_points(a, self.cur), self.columns, self.rows); + // A grid draws its cells; one too small for them falls back to the single frame, as the + // release does. + if !click { + let cells = grid_cells(designcraft_geom::Rect::from_points(a, self.cur), self.columns, self.rows); + if !cells.is_empty() { + return cells.into_iter().map(crate::Overlay::Marquee).collect(); + } } let Some(size) = cx.loaded else { return vec![crate::Overlay::Marquee(designcraft_geom::Rect::from_points(a, self.cur))]; @@ -228,21 +234,28 @@ Y: {pct}" } } -/// The cells of a `columns` × `rows` place grid drawn over `rect`, 6 pt apart, as `place.grid` -/// lays them out; the whole rect when the cells would vanish. -fn grid_overlays(rect: designcraft_geom::Rect, columns: usize, rows: usize) -> Vec { +/// The gutter between place-grid cells, in points: `place.grid`'s default. +const PLACE_GRID_GUTTER: f64 = 6.0; + +/// The cells of a `columns` × `rows` place grid drawn over `rect`, [`PLACE_GRID_GUTTER`] apart, as +/// `place.grid` lays them out. None for a 1 × 1 grid, or when `rect` is too small for the cells to +/// have a positive size: then the drag places one frame. +fn grid_cells(rect: designcraft_geom::Rect, columns: usize, rows: usize) -> Vec { let (columns, rows) = (columns.clamp(1, 100), rows.clamp(1, 100)); - let w = (rect.width() - 6.0 * (columns - 1) as f64) / columns as f64; - let h = (rect.height() - 6.0 * (rows - 1) as f64) / rows as f64; + if columns == 1 && rows == 1 { + return vec![]; + } + let w = (rect.width() - PLACE_GRID_GUTTER * (columns - 1) as f64) / columns as f64; + let h = (rect.height() - PLACE_GRID_GUTTER * (rows - 1) as f64) / rows as f64; if !(w > 0.0 && h > 0.0) { - return vec![crate::Overlay::Marquee(rect)]; + return vec![]; } (0..rows) .flat_map(|row| { (0..columns).map(move |column| { - let x = rect.x0 + column as f64 * (w + 6.0); - let y = rect.y0 + row as f64 * (h + 6.0); - crate::Overlay::Marquee(designcraft_geom::Rect::new(x, y, x + w, y + h)) + let x = rect.x0 + column as f64 * (w + PLACE_GRID_GUTTER); + let y = rect.y0 + row as f64 * (h + PLACE_GRID_GUTTER); + designcraft_geom::Rect::new(x, y, x + w, y + h) }) }) .collect() diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 28cfecf01..790b3c7f8 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2369,3 +2369,34 @@ fn place_gun_grid_arrow_keys_are_handled_during_a_drag() { } assert!(t.key(&cx, ToolKey::Delete, Mods::default()).is_empty()); } + +/// A place-cursor grid drag too thin for its cells shows and places the single frame an ordinary +/// drag would; one with room shows its cells and places the grid. +#[test] +fn place_gun_grid_too_small_for_its_cells_previews_and_places_one_frame() { + let d = Document::new(&NewDocument::default()); + let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false)); + let mut cx = ctx(&d, &s, &c, &l); + cx.loaded = Some((40.0, 20.0)); + // Drag from (10, 10) to `to`, pressing ↑ (two rows) when `grid`: the overlay before release, + // and the release. + let drag = |to: (f64, f64), grid: bool| { + let mut t = create("placeGun"); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 10.0, 10.0)); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, to.0, to.1)); + if grid { + assert_eq!(t.key(&cx, ToolKey::Up, Mods::default()), vec![Action::Handled]); + } + let shown = t.overlays(&cx); + (shown, t.pointer(&cx, &PointerEvent::new(PointerKind::Up, to.0, to.1))) + }; + // 100 × 8 pt: two rows 6 pt apart leave each a 1 pt cell; 100 × 4 pt leaves none. + let (shown, out) = drag((110.0, 18.0), true); + assert_eq!(shown.len(), 2, "{shown:?}"); + assert!(matches!(out.as_slice(), [Action::Exec(cmd, p)] if cmd == "place.grid" && p["rows"] == 2), "{out:?}"); + let (shown, out) = drag((110.0, 14.0), true); + let (single_shown, single_out) = drag((110.0, 14.0), false); + assert_eq!(shown, single_shown); + assert_eq!(out, single_out); + assert!(matches!(out.as_slice(), [Action::Exec(cmd, _)] if cmd == "place.drop"), "{out:?}"); +} diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 997414bcd..da8f180bf 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -5,7 +5,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Click to place the next image at its natural size. - Drag to draw its frame: it keeps the image's proportions, and shows the scale beside the pointer. - Click an existing graphic frame to replace its contents. -- While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. +- While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. A drag too small for the grid's cells shows and places one frame instead, as an ordinary drag does. - Press Escape or select another tool to cancel the remaining placement. A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. From a93885877568e05c40eb16d6e117b5c42ffa2de7 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 10:44:31 -0500 Subject: [PATCH 016/322] Place: contact sheet strings in every interface language; Spanish grid labels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Arabic, Czech, Hungarian, Italian, Polish, Portuguese (Brazil), Russian and Ukrainian read only their own catalogs, so File › Place Contact Sheet… and its dialog showed in English there. They now have the four new strings. - Spanish Columns, Rows and Gutter were still English in the shared table: Columnas, Filas, Medianil, as the Spanish catalog already says for "Columns:", "Rows:" and "Gutter:". --- crates/ui-egui/src/i18n/ar.rs | 4 ++++ crates/ui-egui/src/i18n/cs.rs | 4 ++++ crates/ui-egui/src/i18n/hu.rs | 4 ++++ crates/ui-egui/src/i18n/it.rs | 4 ++++ crates/ui-egui/src/i18n/pl.rs | 4 ++++ crates/ui-egui/src/i18n/pt_br.rs | 4 ++++ crates/ui-egui/src/i18n/ru.rs | 4 ++++ crates/ui-egui/src/i18n/table.rs | 6 +++--- crates/ui-egui/src/i18n/tests.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/i18n/uk.rs | 4 ++++ 10 files changed, 57 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 651b748f9..a5b8c9ce5 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -22,6 +22,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "حفظ نسخة…"), ("Revert", "استعادة"), ("Place…", "وضع…"), + ("Place Contact Sheet…", "وضع ورقة مصغّرات…"), + ("Place Contact Sheet", "وضع ورقة مصغّرات"), + ("Place loaded images on new pages, in file order.", "وضع الصور المحمّلة على صفحات جديدة، بترتيب الملفات."), + ("Page margin", "هامش الصفحة"), ("Export PDF…", "تصدير PDF…"), ("Print…", "طباعة…"), ("Print", "طباعة"), diff --git a/crates/ui-egui/src/i18n/cs.rs b/crates/ui-egui/src/i18n/cs.rs index b6459bc36..6b8caa4be 100644 --- a/crates/ui-egui/src/i18n/cs.rs +++ b/crates/ui-egui/src/i18n/cs.rs @@ -25,6 +25,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Uložit kopii…"), ("Revert", "Vrátit k uložené verzi"), ("Place…", "Umístit…"), + ("Place Contact Sheet…", "Umístit kontaktní arch…"), + ("Place Contact Sheet", "Umístit kontaktní arch"), + ("Place loaded images on new pages, in file order.", "Umístit načtené obrázky na nové stránky v pořadí souborů."), + ("Page margin", "Okraj stránky"), ("Export PDF…", "Exportovat PDF…"), ("Print…", "Tisk…"), ("Document Setup…", "Nastavení dokumentu…"), diff --git a/crates/ui-egui/src/i18n/hu.rs b/crates/ui-egui/src/i18n/hu.rs index 890959761..b3a32ca3e 100644 --- a/crates/ui-egui/src/i18n/hu.rs +++ b/crates/ui-egui/src/i18n/hu.rs @@ -1223,6 +1223,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Place with Import Options", "Elhelyezés importálási beállításokkal"), ("Place with Import Options…", "Elhelyezés importálási beállításokkal…"), ("Place…", "Elhelyezés…"), + ("Place Contact Sheet…", "Kontaktlap elhelyezése…"), + ("Place Contact Sheet", "Kontaktlap elhelyezése"), + ("Place loaded images on new pages, in file order.", "A betöltött képek elhelyezése új oldalakon, fájlsorrendben."), + ("Page margin", "Oldalmargó"), ("Plain", "Egyszerű"), ("Plain Text", "Egyszerű szöveg"), ("Play on Page Load", "Lejátszás az oldal betöltésekor"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 70d08085e..183891a57 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -25,6 +25,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Salva una copia…"), ("Revert", "Ripristina"), ("Place…", "Inserisci…"), + ("Place Contact Sheet…", "Inserisci provino…"), + ("Place Contact Sheet", "Inserisci provino"), + ("Place loaded images on new pages, in file order.", "Inserisci le immagini caricate in nuove pagine, nell'ordine dei file."), + ("Page margin", "Margine pagina"), ("Export PDF…", "Esporta PDF…"), ("Print…", "Stampa…"), ("Document Setup…", "Impostazione documento…"), diff --git a/crates/ui-egui/src/i18n/pl.rs b/crates/ui-egui/src/i18n/pl.rs index fcdb3718e..155e5f3eb 100644 --- a/crates/ui-egui/src/i18n/pl.rs +++ b/crates/ui-egui/src/i18n/pl.rs @@ -23,6 +23,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Zapisz kopię…"), ("Revert", "Przywróć"), ("Place…", "Umieść…"), + ("Place Contact Sheet…", "Umieść stykówkę…"), + ("Place Contact Sheet", "Umieść stykówkę"), + ("Place loaded images on new pages, in file order.", "Umieść wczytane obrazy na nowych stronach, w kolejności plików."), + ("Page margin", "Margines strony"), ("Export PDF…", "Eksportuj PDF…"), ("Print…", "Drukuj…"), ("Document Setup…", "Ustawienia dokumentu…"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 0ef8fa755..f104fd8de 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -26,6 +26,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Salvar uma cópia…"), ("Revert", "Reverter"), ("Place…", "Inserir…"), + ("Place Contact Sheet…", "Inserir folha de contato…"), + ("Place Contact Sheet", "Inserir folha de contato"), + ("Place loaded images on new pages, in file order.", "Inserir as imagens carregadas em novas páginas, na ordem dos arquivos."), + ("Page margin", "Margem da página"), ("Export PDF…", "Exportar PDF…"), ("Print…", "Imprimir…"), ("Print", "Imprimir"), diff --git a/crates/ui-egui/src/i18n/ru.rs b/crates/ui-egui/src/i18n/ru.rs index 8b933fe60..22533a4ff 100644 --- a/crates/ui-egui/src/i18n/ru.rs +++ b/crates/ui-egui/src/i18n/ru.rs @@ -27,6 +27,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Сохранить копию…"), ("Revert", "Восстановить сохраненную версию"), ("Place…", "Поместить…"), + ("Place Contact Sheet…", "Поместить контактный лист…"), + ("Place Contact Sheet", "Поместить контактный лист"), + ("Place loaded images on new pages, in file order.", "Поместить загруженные изображения на новые страницы в порядке файлов."), + ("Page margin", "Поле страницы"), ("Export PDF…", "Экспорт в PDF…"), ("Print…", "Печать…"), ("Document Setup…", "Настройка документа…"), diff --git a/crates/ui-egui/src/i18n/table.rs b/crates/ui-egui/src/i18n/table.rs index 60cba865d..e83665438 100644 --- a/crates/ui-egui/src/i18n/table.rs +++ b/crates/ui-egui/src/i18n/table.rs @@ -1190,7 +1190,7 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ), ("Color Settings", ["Color Settings", "Réglages des couleurs", "Color Settings", "Color Settings", "颜色设置"]), ("Color:", ["Color:", "Couleur :", "Color:", "Color:", "颜色:"]), - ("Columns", ["Columns", "Colonnes", "Columns", "Columns", "栏"]), + ("Columns", ["Columns", "Colonnes", "Columnas", "Columns", "栏"]), ("Composer:", ["Composer:", "Compositeur :", "Composer:", "Composer:", "排版器:"]), ("Copies:", ["Copies:", "Copies :", "Copies:", "Copies:", "份数:"]), ("Count", ["Count", "Compter", "Count", "Count", "数量"]), @@ -1292,7 +1292,7 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ("Generate QR Code", ["Generate QR Code", "Générer un code QR", "Generate QR Code", "Generate QR Code", "生成二维码"]), ("Go To", ["Go To", "Atteindre", "Go To", "Go To", "转到"]), ("Go to Page", ["Go to Page", "Atteindre la page", "Go to Page", "Go to Page", "转到页面"]), - ("Gutter", ["Gutter", "Gouttière", "Gutter", "Gutter", "栏间距"]), + ("Gutter", ["Gutter", "Gouttière", "Medianil", "Gutter", "栏间距"]), ("Header Rows", ["Header Rows", "Lignes d'en-tête", "Header Rows", "Header Rows", "表头行"]), ("Height", ["Height", "Hauteur", "Height", "Height", "高度"]), ("Height:", ["Height:", "Hauteur :", "Height:", "Height:", "高度:"]), @@ -3723,7 +3723,7 @@ pub(super) const TABLE: &[(&str, [&str; 5])] = &[ ), ("Rotate 180°", ["180° drehen", "Rotation à 180°", "Girar 180°", "180°回転", "旋转 180°"]), ("Rotation Angle", ["Rotation Angle", "Angle de rotation", "Rotation Angle", "Rotation Angle", "旋转角度"]), - ("Rows", ["Rows", "Lignes", "Rows", "Rows", "行数"]), + ("Rows", ["Rows", "Lignes", "Filas", "Rows", "行数"]), ("Run", ["Run", "Exécuter", "Run", "Run", "运行"]), ("Scale X Percentage", ["Scale X Percentage", "Échelle X en pourcentage", "Scale X Percentage", "Scale X Percentage", "水平缩放百分比"]), ("Scale Y Percentage", ["Scale Y Percentage", "Échelle Y en pourcentage", "Scale Y Percentage", "Scale Y Percentage", "垂直缩放百分比"]), diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b676a0c5f..a10f61438 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -249,6 +249,28 @@ fn arrangement_accessible_name_is_localized_in_every_interface_language() { } } +/// File › Place Contact Sheet… and its dialog read in every interface language, including those +/// whose own catalog is all `tr` looks in. +#[test] +fn contact_sheet_strings_are_translated_in_every_interface_language() { + let strings = [ + "Place Contact Sheet…", + "Place Contact Sheet", + "Place loaded images on new pages, in file order.", + "Columns", + "Rows", + "Gutter", + "Page margin", + ]; + for (code, name) in LANGUAGES.iter().filter(|(code, _)| !code.is_empty()) { + for s in strings { + let text = tr(code, s); + assert!(text != s && !text.trim().is_empty(), "{name}: {s:?} is still English"); + } + } + assert_eq!(["Columns", "Rows", "Gutter"].map(|s| tr("es", s)), ["Columnas", "Filas", "Medianil"]); +} + /// Checks language-specific context precedence and fallback to the plain translation. #[test] fn context_captions_come_from_their_context_or_the_plain_translation() { diff --git a/crates/ui-egui/src/i18n/uk.rs b/crates/ui-egui/src/i18n/uk.rs index 03918520f..f902cd236 100644 --- a/crates/ui-egui/src/i18n/uk.rs +++ b/crates/ui-egui/src/i18n/uk.rs @@ -26,6 +26,10 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Save a Copy…", "Зберегти копію…"), ("Revert", "Повернути збережену версію"), ("Place…", "Розмістити…"), + ("Place Contact Sheet…", "Розмістити аркуш мініатюр…"), + ("Place Contact Sheet", "Розмістити аркуш мініатюр"), + ("Place loaded images on new pages, in file order.", "Розмістити завантажені зображення на нових сторінках у порядку файлів."), + ("Page margin", "Поле сторінки"), ("Export PDF…", "Експортувати PDF…"), ("Print…", "Друк…"), ("Document Setup…", "Параметри документа…"), From 0ea2a72a091e96833783dee24669bc7ea6b3a0f4 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 11:05:45 -0500 Subject: [PATCH 017/322] Place: switching, opening or closing a document leaves the place cursor's tool Review fix for #2309: set_active, add_document and close_document emptied the place cursor but kept the placeGun tool, so the next canvas click failed with 'nothing loaded in the place cursor'. One helper, Session::unload_place_cursor, empties the cursor and its queue and goes back to the Selection tool when the place cursor's tool is active; validate_place_cursor uses it too. Test: changing_documents_unloads_the_place_cursor_and_its_tool. --- ROADMAP.md | 2 +- crates/engine/src/cmd/file/place.rs | 4 +--- crates/engine/src/lib.rs | 9 +++------ crates/engine/src/tests.rs | 27 +++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 10 ++++++++++ docs/multi-image-placement.md | 1 + 6 files changed, 43 insertions(+), 10 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 8aedbe1f0..0395fb926 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -406,7 +406,7 @@ Newest first. - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. - **2026-10-30** · Dropping images from the file manager works as in InDesign: images dropped together load the place cursor in the order they came, and one image dropped off a frame that takes it loads the place cursor instead of being placed at once (on a frame it still fills it). Documents and text files dropped keep opening and flowing as before. Ported from #1307 and #1666; see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. -- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. +- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). Switching, opening or closing a document unloads it too, back to the Selection tool. A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index ba9e0827a..dd7313776 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -313,9 +313,7 @@ fn validate_place_cursor(s: &mut Session, command: &str) -> Result<()> { } let valid = s.loaded.iter().chain(s.loaded_queue.iter()).all(|image| s.doc().is_ok_and(|d| d.doc.assets.contains_key(&image.asset))); if !valid { - s.loaded = None; - s.loaded_queue.clear(); - s.set_tool("selection"); + s.unload_place_cursor(); return Err(bad(command, "the loaded graphic is no longer in the document")); } Ok(()) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 397be3203..33af11c42 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -552,8 +552,7 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.active = Some(i); } } @@ -563,8 +562,7 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.docs.push(d); self.active = Some(self.docs.len() - 1); self.docs.len() - 1 @@ -587,8 +585,7 @@ impl Session { recovery::discard_document(self, i, recovery_dir.as_deref()); } if i < self.docs.len() { - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.reset_find_scope(); self.docs.remove(i); self.active = if self.docs.is_empty() { None } else { Some(i.min(self.docs.len() - 1)) }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 564e42605..a2751de72 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2127,6 +2127,33 @@ fn undoing_loaded_assets_cancels_every_placement_cursor() { } } +/// Switching, opening or closing a document empties the place cursor and leaves its tool: a click +/// on the canvas then selects, instead of failing with nothing loaded. Another tool stays. +#[test] +fn changing_documents_unloads_the_place_cursor_and_its_tool() { + let changes: [fn(&mut Session); 3] = [ + |s| s.set_active(0), + |s| { + s.execute("file.new", &json!({})).unwrap(); + }, + |s| s.close_document(1), + ]; + for (n, change) in changes.into_iter().enumerate() { + let mut s = session(); + s.execute("file.new", &json!({})).unwrap(); + load_test_images(&mut s, 3); + assert_eq!(s.tool_id(), "placeGun"); + change(&mut s); + assert!(s.loaded.is_none() && s.loaded_queue.is_empty(), "change {n}"); + assert_eq!(s.tool_id(), "selection", "change {n}"); + // Holding another tool, the change keeps it. + s.execute("file.new", &json!({})).unwrap(); + s.set_tool("rectangle"); + s.set_active(0); + assert_eq!(s.tool_id(), "rectangle", "change {n}"); + } +} + /// Issue #1637: with several objects selected, a click on one of them (no drag) makes it the key /// object, and Align to Key Object leaves it in place. A second click on it drops the key. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 6dfd23703..9bde0acfd 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -87,6 +87,16 @@ impl Session { } } + /// Empty the place cursor (its graphic and the ones queued after it). Holding the place + /// cursor's tool, go back to the Selection tool: with nothing loaded, a click would only fail. + pub(crate) fn unload_place_cursor(&mut self) { + self.loaded = None; + self.loaded_queue.clear(); + if self.tool_id() == "placeGun" { + self.set_tool("selection"); + } + } + pub fn layout(&self) -> CanvasLayout { match self.active() { Some(st) => CanvasLayout::new(&st.doc, st.editing_parents), diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 6281de637..13119cf64 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -7,6 +7,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images, or drop a se - Click an existing graphic frame to replace its contents. - While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. - Press Escape or select another tool to cancel the remaining placement. +- Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. From f02e13318b0c870e09f4c791047e69db7681f2b1 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 11:02:26 -0500 Subject: [PATCH 018/322] Place: a drop without pointer events keeps the system pointer of its own input Review fixes for #2304: - Each pointer-less drop asks the system where the pointer is when its raw input arrives, and converts it with that input's window rect and the UI scale, instead of one sample taken at the later UI pass for the whole batch. Drops with pointer events keep their own pointer, and the system is still only asked when a drop brought none. - system_pointer is cfg'd off on wasm with its only caller; Services::pointer's docs say a drop without a pointer lands in the middle of the view. - pointer.rs: the AppKit flip is a pure function with a test, documenting why it flips against the main display only (winit's window positions use the same origin). - Test: a filled compound path takes a dropped image through its ring, not its hole. --- apps/designcraft/src/pointer.rs | 29 +++++++++++- crates/ui-egui/src/app.rs | 2 +- crates/ui-egui/src/app/input.rs | 46 ++++++++++--------- crates/ui-egui/src/lib.rs | 4 ++ crates/ui-egui/src/services.rs | 2 +- crates/ui-egui/src/tests.rs | 78 ++++++++++++++++++++++++++++++--- 6 files changed, 132 insertions(+), 29 deletions(-) diff --git a/apps/designcraft/src/pointer.rs b/apps/designcraft/src/pointer.rs index 14bf9599a..3725cfbaa 100644 --- a/apps/designcraft/src/pointer.rs +++ b/apps/designcraft/src/pointer.rs @@ -11,6 +11,33 @@ pub fn screen_position() -> Option { // AppKit's origin is the bottom left of the first screen, the one with the menu bar. let height = NSScreen::screens(mtm).firstObject()?.frame().size.height; let at = NSEvent::mouseLocation(); - let (x, y) = (at.x, height - at.y); + from_appkit(at.x, at.y, height) +} + +/// A point in AppKit's global coordinates (origin at the bottom left of the main display, the one +/// with the menu bar, y up) in winit's (origin at its top left, y down), given that display's +/// height. Only the main display's height: winit flips window positions the same way +/// (`flip_window_screen_coordinates`, against `CGMainDisplayID`), whatever display the window is +/// on, so a display left of or above the main one gives negative coordinates in both. +fn from_appkit(x: f64, y: f64, main_height: f64) -> Option { + let y = main_height - y; (x.is_finite() && y.is_finite()).then(|| egui::pos2(x as f32, y as f32)) } + +#[cfg(test)] +mod tests { + use super::from_appkit; + + #[test] + fn appkit_points_flip_against_the_main_display_only() { + // The main display is 1000 points high: its top left is (0, 0), its bottom left (0, 1000). + assert_eq!(from_appkit(0.0, 1000.0, 1000.0), Some(egui::pos2(0.0, 0.0))); + assert_eq!(from_appkit(200.0, 100.0, 1000.0), Some(egui::pos2(200.0, 900.0))); + // A second display above the main one, and one to its left: negative, as winit reports a + // window there. + assert_eq!(from_appkit(300.0, 1200.0, 1000.0), Some(egui::pos2(300.0, -200.0))); + assert_eq!(from_appkit(-800.0, 500.0, 1000.0), Some(egui::pos2(-800.0, 500.0))); + assert_eq!(from_appkit(f64::NAN, 0.0, 1000.0), None); + assert_eq!(from_appkit(0.0, 0.0, f64::INFINITY), None); + } +} diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b2b433b71..55a257dd3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -206,7 +206,7 @@ impl DesignApp { // must not replay shortcuts or dropped files from stale input. if ctx.current_pass_index() == 0 { #[cfg(not(target_arch = "wasm32"))] - self.take_pending_drops(&ctx); + self.take_pending_drops(); menus::shortcuts(self, &ctx); } let t0 = now_ms(); diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 2682478c4..27049a1a7 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -59,10 +59,13 @@ impl DesignApp { _ => None, }); let generation = self.input_generation(); + // A drop without pointer events (dragged in from another application) asks the + // system now, while the pointer is still where the files were let go. + let system = if pointer.is_none() && !raw.dropped_files.is_empty() { self.system_pointer(ctx, raw) } else { None }; for file in std::mem::take(&mut raw.dropped_files) { let path = file.path().to_string_lossy().to_string(); if !path.is_empty() { - self.pending_drops.push(PendingDrop { path, pointer, generation }); + self.pending_drops.push(PendingDrop { path, pointer, system, generation }); } } } @@ -144,37 +147,29 @@ impl DesignApp { /// Open or place the files dropped since the last UI pass, at the pointer. Files dropped /// without pointer events (dragged in from another application) are placed where the system - /// says the pointer is, so one dropped on a frame still fills it. + /// said the pointer was when they arrived, so one dropped on a frame still fills it. #[cfg(not(target_arch = "wasm32"))] - pub(crate) fn take_pending_drops(&mut self, ctx: &egui::Context) { + pub(crate) fn take_pending_drops(&mut self) { // Sample the generation once for the whole batch: placing the first valid file must not // suppress later files that belong to the same captured batch. let current = self.input_generation(); - let drops: Vec<_> = std::mem::take(&mut self.pending_drops).into_iter().filter(|d| d.generation == current).collect(); - if drops.is_empty() { - return; - } - // Each file keeps the pointer it was dropped at; the system is asked once, for those - // that came without one. - let system = drops.iter().any(|d| d.pointer.is_none()).then(|| self.system_pointer(ctx)).flatten(); let mut frame_free = true; - for drop in drops { - let _ = self.place_dropped(&drop.path, drop.pointer.or(system), &mut frame_free); + for drop in std::mem::take(&mut self.pending_drops) { + if drop.generation == current { + let _ = self.place_dropped(&drop.path, drop.pointer.or(drop.system), &mut frame_free); + } } } /// Where the pointer is in the window, asked of the system ([`crate::Services::pointer`]), /// for files dropped without pointer events: dragged in from another application, they bring - /// none. `None` when the system doesn't say or the window's place isn't known. - pub(crate) fn system_pointer(&self, ctx: &egui::Context) -> Option { + /// none. Converted with the window's place in `raw` (that input's own viewport info, else the + /// last pass's). `None` when the system doesn't say or the window's place isn't known. + #[cfg(not(target_arch = "wasm32"))] + fn system_pointer(&self, ctx: &egui::Context, raw: &egui::RawInput) -> Option { let at = (self.services.pointer.as_ref()?)()?; - // The system's points are unscaled; egui's (the window's rect too) are divided by the - // UI scale. - let zoom = ctx.zoom_factor(); - let at = if zoom.is_finite() && zoom > 0.0 { at / zoom } else { at }; - let inner = ctx.input(|i| i.viewport().inner_rect)?; - let local = at - inner.min.to_vec2(); - (local.x.is_finite() && local.y.is_finite()).then_some(local) + let inner = raw.viewports.get(&raw.viewport_id).and_then(|v| v.inner_rect).or_else(|| ctx.input(|i| i.viewport().inner_rect))?; + screen_to_window(at, ctx.zoom_factor(), inner) } /// The current state an injected batch belongs to. @@ -224,3 +219,12 @@ impl DesignApp { self.control_input_frame.store(false, std::sync::atomic::Ordering::Relaxed); } } + +/// A point on the screen in the system's unscaled points, in the window whose content is `inner` +/// (egui's points, divided by the UI scale `zoom`). `None` when the result isn't finite. +#[cfg(not(target_arch = "wasm32"))] +fn screen_to_window(at: egui::Pos2, zoom: f32, inner: egui::Rect) -> Option { + let at = if zoom.is_finite() && zoom > 0.0 { at / zoom } else { at }; + let local = at - inner.min.to_vec2(); + (local.x.is_finite() && local.y.is_finite()).then_some(local) +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c780d632a..531a8dbe7 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -111,6 +111,10 @@ struct InputGeneration { struct PendingDrop { path: String, pointer: Option, + /// Where the system said the pointer was in the window when this drop's raw input arrived, + /// for a drop that brought no pointer events ([`crate::Services::pointer`]). Each drop keeps + /// its own, converted with the window's place and the UI scale of that input. + system: Option, generation: InputGeneration, } diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 107e9e775..32d7e4599 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -47,6 +47,6 @@ pub struct Services { /// The pointer's place on the screen, asked when a file is dropped: a file dragged in from /// another application brings no pointer events with it (winit reports none during a drag on /// macOS), so without it a drop can't tell which frame it landed on. `None`: a drop without - /// pointer events loads the place cursor. + /// pointer events lands in the middle of the view (`canvas::drop_point`), filling no frame. pub pointer: Option, } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index e53e603a1..46c3ce3e2 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -899,6 +899,15 @@ fn a_graphic_dropped_on_a_frame_fills_it() { assert!(matches!(d.item(designcraft_doc::ItemId(frame)).unwrap().content, designcraft_doc::Content::Graphic(_))); } +/// The raw input of a drop without pointer events, with the window's content at `inner`. +#[cfg(not(target_arch = "wasm32"))] +fn pointerless_drop(path: &std::path::Path, inner: egui::Rect) -> egui::RawInput { + let mut raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, inner.size())), ..Default::default() }; + raw.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { inner_rect: Some(inner), ..Default::default() }); + raw.dropped_files.push(dropped_file(path)); + raw +} + /// A file dragged in from the Finder brings no pointer events (winit sends none during a drag on /// macOS): the drop asks the system where the pointer is, so one dropped on a frame fills it. #[cfg(not(target_arch = "wasm32"))] @@ -911,13 +920,13 @@ fn a_file_dropped_without_pointer_events_fills_the_frame_under_the_system_pointe let window = egui::vec2(300.0, 200.0); app.services.pointer = Some(Box::new(move || Some(((inside + window).to_vec2() * zoom).to_pos2()))); let path = dropped_png("drop-system-pointer"); - app.pending_drops.push(crate::PendingDrop { path: path.to_string_lossy().into_owned(), pointer: None, generation: app.input_generation() }); let ctx = egui::Context::default(); ctx.set_zoom_factor(zoom); - let rect = egui::Rect::from_min_size(egui::Pos2::ZERO + window, egui::vec2(1400.0, 900.0)); - let mut raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, rect.size())), ..Default::default() }; - raw.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { inner_rect: Some(rect), ..Default::default() }); - ctx.run_ui(raw, |ui| app.take_pending_drops(ui.ctx())).textures_delta.clear(); + // The zoom takes effect from the next pass, as it has by the time the system drops a file. + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + let mut raw = pointerless_drop(&path, egui::Rect::from_min_size(egui::Pos2::ZERO + window, egui::vec2(1400.0, 900.0))); + app.raw_input_hook(&ctx, &mut raw); + ctx.run_ui(raw, |_| app.take_pending_drops()).textures_delta.clear(); let _ = std::fs::remove_file(&path); assert!(app.pending_drops.is_empty()); let d = &app.session.doc().unwrap().doc; @@ -929,6 +938,65 @@ fn a_file_dropped_without_pointer_events_fills_the_frame_under_the_system_pointe } } +/// A drop without pointer events keeps the place the system gave when its input arrived, +/// converted with that input's window: the pointer and the window moving before the UI pass that +/// places it don't move the drop. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_pointerless_drop_keeps_the_system_pointer_of_its_own_input() { + let (mut app, frame, inside, outside) = app_with_drop_frame(); + let at = std::rc::Rc::new(std::cell::Cell::new(inside)); + let reported = at.clone(); + app.services.pointer = Some(Box::new(move || Some(reported.get()))); + let ctx = egui::Context::default(); + let window = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); + let path = dropped_png("drop-own-input"); + let mut raw = pointerless_drop(&path, window); + app.raw_input_hook(&ctx, &mut raw); + // Before the pass that places it, the window moves and the pointer leaves the frame; a later + // input with no drop doesn't ask the system again. + let moved = window.translate(egui::vec2(50.0, 40.0)); + at.set(outside + moved.min.to_vec2()); + let mut later = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, moved.size())), ..Default::default() }; + later.viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo { inner_rect: Some(moved), ..Default::default() }); + app.raw_input_hook(&ctx, &mut later); + ctx.run_ui(later, |_| app.take_pending_drops()).textures_delta.clear(); + let _ = std::fs::remove_file(&path); + let d = &app.session.doc().unwrap().doc; + assert_eq!(d.spreads[0].items.len(), 1, "no new object"); + let designcraft_doc::Content::Graphic(g) = &d.item(designcraft_doc::ItemId(frame)).unwrap().content else { + panic!("the file fills the frame it was dropped on") + }; + assert!(d.assets[&g.asset].name.contains("drop-own-input")); +} + +/// A filled compound path (Object > Compound Paths > Make) is a frame a dropped image fills, as +/// in InDesign, through its ring and not its hole. +#[test] +fn a_graphic_dropped_on_a_compound_path_fills_it() { + let (mut app, frame, _, _) = app_with_drop_frame(); + let hole = app.run("frame.create", json!({"rect": [66, 66, 106, 106]})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(app.run("object.makeCompoundPath", json!({"ids": [frame, hole]})).unwrap()["id"].as_u64(), Some(frame)); + app.run("object.fill", json!({"ids": [frame], "swatch": "[Black]"})).unwrap(); + let (view, rect) = (app.view().unwrap(), app.canvas_rect.unwrap()); + let st = app.session.active().unwrap(); + let layout = designcraft_tools::CanvasLayout::new(&st.doc, false); + let slot = layout.slot(designcraft_doc::SpreadRef::Doc(0)).unwrap(); + let screen = |x, y| canvas::Xf::new(rect, view).to_screen(slot.to_canvas(designcraft_geom::Point::new(x, y))); + // On the ring, between the outer edge (36) and the hole (66); the hole's middle is no frame. + let ring = screen(50.0, 50.0); + assert!(canvas::drop_frame(&app, Some(screen(86.0, 86.0))).is_none(), "the hole"); + let path = dropped_png("drop-compound"); + let r = app.open_dropped_at(&path.to_string_lossy(), Some(ring)); + let _ = std::fs::remove_file(&path); + assert_eq!(r.unwrap()["id"].as_u64(), Some(frame), "the compound path under the pointer is filled"); + let d = &app.session.doc().unwrap().doc; + assert_eq!(d.spreads[0].items.len(), 1, "no new object"); + let it = d.item(designcraft_doc::ItemId(frame)).unwrap(); + assert!(matches!(it.content, designcraft_doc::Content::Graphic(_))); + assert_eq!(it.path.subpaths.len(), 2, "it keeps its hole"); +} + #[test] fn a_locked_frame_is_not_a_drop_target() { let (mut app, frame, inside, _) = app_with_drop_frame(); From 1bea5300d894522f4accd767e6a56995ff6ed26a Mon Sep 17 00:00:00 2001 From: moppeeer Date: Wed, 4 Nov 2026 19:00:49 +0100 Subject: [PATCH 019/322] guide.selectAll: say it skips guides on a layer that locks its guides Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/guides.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/guides.rs b/crates/engine/src/cmd/guides.rs index 6988bf53b..24ccf1696 100644 --- a/crates/engine/src/cmd/guides.rs +++ b/crates/engine/src/cmd/guides.rs @@ -118,7 +118,7 @@ pub fn specs() -> Vec { "Select All Guides", ["Edit"], Some("Cmd+Alt+G"), - "{spread?} — every guide on the spread that is not locked or on a locked or hidden layer → {selected: n}", + "{spread?} — every guide on the spread that is not locked or on a layer that is locked, hidden or locks its guides → {selected: n}", has_doc, select_all ), From e4f82e243eaa96591f3d88cb00b341a1b42ef0b3 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 11:05:45 -0500 Subject: [PATCH 020/322] Place: switching, opening or closing a document leaves the place cursor's tool Review fix for #2309: set_active, add_document and close_document emptied the place cursor but kept the placeGun tool, so the next canvas click failed with 'nothing loaded in the place cursor'. One helper, Session::unload_place_cursor, empties the cursor and its queue and goes back to the Selection tool when the place cursor's tool is active; validate_place_cursor uses it too. Test: changing_documents_unloads_the_place_cursor_and_its_tool. --- ROADMAP.md | 2 +- crates/engine/src/cmd/file/place.rs | 4 +--- crates/engine/src/lib.rs | 9 +++------ crates/engine/src/tests.rs | 27 +++++++++++++++++++++++++++ crates/engine/src/tooling.rs | 10 ++++++++++ docs/multi-image-placement.md | 1 + 6 files changed, 43 insertions(+), 10 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index df9b5fea0..b080dfc9c 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -408,7 +408,7 @@ Newest first. - **2026-10-30** · Import warnings about a story have a Show button: it closes the warnings (the status line keeps them) and selects the story's first frame, fitted in the window. `file.open` returns `warningItems`, the frame each IDML or InDesign warning is about (or null), matching the converter's INDD story numbers (`story 30892`, written to IDML as `u78ac`) and IDML `Self` names to the imported stories. No readiness percentage change. - **2026-10-30** · Parent pages: a running-header variable shows its name in angle brackets on the parent itself (it was blank), as InDesign shows it; on the document pages, and in text with no page, it shows its text as before. No readiness percentage change. - **2026-10-30** · Without facing pages, a page of a multi-page spread shows the parent page in its place, as in InDesign: the second page of a two-page spread shows the parent's second page. Every single-sided page showed the parent's first page, so an InDesign book set up without facing pages but laid out in two-page spreads repeated the left parent page's items (a black heading bar) on its right pages and lost the right parent page's. No readiness percentage change. -- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. +- **2026-10-30** · Placing several images works as in InDesign. File › Place takes several files, and they load the place cursor in the order chosen: it shows the first one's thumbnail with how many are loaded ("(6)"), each click places the next, arrow keys while dragging lay out a grid (`place.grid`), and Escape unloads the rest (`place.cancel`). Switching, opening or closing a document unloads it too, back to the Selection tool. A drag with the cursor draws the frame at the graphic's proportions, with its scale. Ported from #1307, #1392 and #1432 (multi-image placement, cursor thumbnail and count); see [multi-image placement](docs/multi-image-placement.md). No readiness percentage change. - **2026-10-30** · macOS: a file dragged in from the Finder fills the frame it is dropped on. winit sends no pointer events during such a drag, so the drop asks the system where the pointer is (`Services::pointer`, from `NSEvent.mouseLocation`), at any UI scale. No readiness percentage change. - **2026-10-30** · File > Package opens a dialog, as the reference app's: a Summary of fonts, links and images and inks, pages for each, a Printing Instructions step, and a PDF made with the options of a preset (#1514, #1515). - **2026-10-30** · IDML import reads TOC separators and entry styles written with the `$ID/` prefix or as `Properties` children, and the TOC separator notation (`^t`, `^y`, `^m`, `^>`) is shared by the dialog and IDML, with a special-character menu on the separator field (#1249, #1255). diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index ddad5ba96..081e3bd27 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -313,9 +313,7 @@ fn validate_place_cursor(s: &mut Session, command: &str) -> Result<()> { } let valid = s.loaded.iter().chain(s.loaded_queue.iter()).all(|image| s.doc().is_ok_and(|d| d.doc.assets.contains_key(&image.asset))); if !valid { - s.loaded = None; - s.loaded_queue.clear(); - s.set_tool("selection"); + s.unload_place_cursor(); return Err(bad(command, "the loaded graphic is no longer in the document")); } Ok(()) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 397be3203..33af11c42 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -552,8 +552,7 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.active = Some(i); } } @@ -563,8 +562,7 @@ impl Session { } self.reset_find_scope(); self.stop_data_preview(); - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.docs.push(d); self.active = Some(self.docs.len() - 1); self.docs.len() - 1 @@ -587,8 +585,7 @@ impl Session { recovery::discard_document(self, i, recovery_dir.as_deref()); } if i < self.docs.len() { - self.loaded = None; - self.loaded_queue.clear(); + self.unload_place_cursor(); self.reset_find_scope(); self.docs.remove(i); self.active = if self.docs.is_empty() { None } else { Some(i.min(self.docs.len() - 1)) }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 564e42605..a2751de72 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2127,6 +2127,33 @@ fn undoing_loaded_assets_cancels_every_placement_cursor() { } } +/// Switching, opening or closing a document empties the place cursor and leaves its tool: a click +/// on the canvas then selects, instead of failing with nothing loaded. Another tool stays. +#[test] +fn changing_documents_unloads_the_place_cursor_and_its_tool() { + let changes: [fn(&mut Session); 3] = [ + |s| s.set_active(0), + |s| { + s.execute("file.new", &json!({})).unwrap(); + }, + |s| s.close_document(1), + ]; + for (n, change) in changes.into_iter().enumerate() { + let mut s = session(); + s.execute("file.new", &json!({})).unwrap(); + load_test_images(&mut s, 3); + assert_eq!(s.tool_id(), "placeGun"); + change(&mut s); + assert!(s.loaded.is_none() && s.loaded_queue.is_empty(), "change {n}"); + assert_eq!(s.tool_id(), "selection", "change {n}"); + // Holding another tool, the change keeps it. + s.execute("file.new", &json!({})).unwrap(); + s.set_tool("rectangle"); + s.set_active(0); + assert_eq!(s.tool_id(), "rectangle", "change {n}"); + } +} + /// Issue #1637: with several objects selected, a click on one of them (no drag) makes it the key /// object, and Align to Key Object leaves it in place. A second click on it drops the key. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 6dfd23703..9bde0acfd 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -87,6 +87,16 @@ impl Session { } } + /// Empty the place cursor (its graphic and the ones queued after it). Holding the place + /// cursor's tool, go back to the Selection tool: with nothing loaded, a click would only fail. + pub(crate) fn unload_place_cursor(&mut self) { + self.loaded = None; + self.loaded_queue.clear(); + if self.tool_id() == "placeGun" { + self.set_tool("selection"); + } + } + pub fn layout(&self) -> CanvasLayout { match self.active() { Some(st) => CanvasLayout::new(&st.doc, st.editing_parents), diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index da8f180bf..ca0d38415 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -7,6 +7,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Click an existing graphic frame to replace its contents. - While drawing, Right/Left add/remove columns and Up/Down add/remove rows. Release to place a grid in row order with 6-point gutters. Extra images remain in the cursor; unused grid cells create no empty frames. A drag too small for the grid's cells shows and places one frame instead, as an ordinary drag does. - Press Escape or select another tool to cancel the remaining placement. +- Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. From d721ef9f62176f0317ca176b7ae1075e2f5c1c2a Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 19:36:38 -0500 Subject: [PATCH 021/322] Place: a grid previews the cells it places on a rotated spread The preview divided the dragged rectangle on the canvas and the release divided it on the spread, so on a rotated spread two columns previewed across the canvas and landed down it. The preview now takes the release's cells and shows each where it lands on the canvas. --- crates/tools/src/nav.rs | 13 +++++++++---- crates/tools/src/tests.rs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/tools/src/nav.rs b/crates/tools/src/nav.rs index d4925009f..c86fc4fec 100644 --- a/crates/tools/src/nav.rs +++ b/crates/tools/src/nav.rs @@ -197,11 +197,16 @@ impl Tool for PlaceGun { // no frame is drawn yet, the loaded cursor shows what lands. let click = (self.cur - a).hypot() < cx.tol(3.0); // A grid draws its cells; one too small for them falls back to the single frame, as the - // release does. - if !click { - let cells = grid_cells(designcraft_geom::Rect::from_points(a, self.cur), self.columns, self.rows); + // release does. The cells are the release's, worked out on the spread: on a rotated spread + // its columns don't run across the canvas. + if !click && let Some((sr, sa)) = cx.layout.spread_at(a) { + let cells = grid_cells(designcraft_geom::Rect::from_points(sa, cx.layout.to_spread(sr, self.cur)), self.columns, self.rows); if !cells.is_empty() { - return cells.into_iter().map(crate::Overlay::Marquee).collect(); + let on_canvas = |x: f64, y: f64| cx.layout.to_canvas(sr, Point::new(x, y)); + return cells + .into_iter() + .map(|c| crate::Overlay::Marquee(designcraft_geom::Rect::from_points(on_canvas(c.x0, c.y0), on_canvas(c.x1, c.y1)))) + .collect(); } } let Some(size) = cx.loaded else { diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 6fb3a6af7..9fd67fdd8 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2441,3 +2441,40 @@ fn place_gun_grid_too_small_for_its_cells_previews_and_places_one_frame() { assert_eq!(out, single_out); assert!(matches!(out.as_slice(), [Action::Exec(cmd, _)] if cmd == "place.drop"), "{out:?}"); } + +/// On a rotated spread a place-cursor grid previews the cells it places: worked out on the spread, +/// then shown on the canvas, so two columns on the spread don't preview as two across the canvas. +#[test] +fn place_gun_grid_preview_matches_the_release_on_a_rotated_spread() { + let mut d = Document::new(&NewDocument::default()); + std::sync::Arc::make_mut(&mut d.spreads[0]).pages[0].view_rotation = 1; + let (s, c, l) = (Selection::default(), Cache::new(), CanvasLayout::new(&d, false)); + let cx = ctx(&d, &s, &c, &l); + let (start, end) = (Point::new(10.0, 10.0), Point::new(210.0, 110.0)); + let (spread, a) = l.spread_at(start).unwrap(); + let b = l.to_spread(spread, end); + let mut t = create("placeGun"); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, start.x, start.y)); + let _ = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, end.x, end.y)); + assert_eq!(t.key(&cx, ToolKey::Right, Mods::default()), vec![Action::Handled]); + let shown = t.overlays(&cx); + let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, end.x, end.y)); + assert!(matches!(out.as_slice(), [Action::Exec(cmd, p)] if cmd == "place.grid" && p["columns"] == 2), "{out:?}"); + // Two columns on the spread, 6 pt apart, each shown where its corners land on the canvas. + let r = Rect::from_points(a, b); + let w = (r.width() - 6.0) / 2.0; + let expected: Vec = [r.x0, r.x0 + w + 6.0] + .into_iter() + .map(|x| Overlay::Marquee(Rect::from_points(l.to_canvas(spread, Point::new(x, r.y0)), l.to_canvas(spread, Point::new(x + w, r.y1))))) + .collect(); + assert_eq!(shown.len(), 2, "{shown:?}"); + for (got, want) in shown.iter().zip(&expected) { + let (Overlay::Marquee(got), Overlay::Marquee(want)) = (got, want) else { panic!("{got:?}") }; + for (g, w) in [(got.x0, want.x0), (got.y0, want.y0), (got.x1, want.x1), (got.y1, want.y1)] { + assert!((g - w).abs() < 1e-6, "{shown:?} against {expected:?}"); + } + } + // A quarter turn: the columns stack down the canvas. + let (Overlay::Marquee(first), Overlay::Marquee(second)) = (&shown[0], &shown[1]) else { panic!("{shown:?}") }; + assert!((first.x0 - second.x0).abs() < 1e-6, "{shown:?}"); +} From 92d3e74a3979598137c0dad4d59bf9827aef10a4 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 19:36:38 -0500 Subject: [PATCH 022/322] Place: a multi-page PDF in a batch keeps the images loaded before it Confirming the PDF's Import Options placed it without append, so in a batch such as [a.png, b.png, multi.pdf] it replaced the images already in the cursor. The dialog now carries append, on both the native and the delivered-file paths. A single multi-page PDF still replaces what the cursor holds. --- crates/ui-egui/src/app/files.rs | 62 +++++++++++++++++++++++++++++---- crates/ui-egui/src/dialogs.rs | 6 ++-- docs/multi-image-placement.md | 2 +- 3 files changed, 61 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 3df85b504..8b1682d83 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -44,7 +44,8 @@ impl DesignApp { let target = self.session.active().map(|d| d.uid); let pages = self.services.read.as_mut().and_then(|r| r(path).ok()).and_then(|b| designcraft_render::pdf_page_count(&b)).unwrap_or(1); if pages > 1 { - self.ui.dialog = Some(dialogs::Dialog::new("pdfImport", json!({"path": path, "page": "1", "pages": pages, "target": target}))); + self.ui.dialog = + Some(dialogs::Dialog::new("pdfImport", json!({"path": path, "page": "1", "pages": pages, "target": target, "append": append}))); return Ok(Value::Null); } } @@ -135,10 +136,12 @@ impl DesignApp { self.pending_pdf = None; } - pub(crate) fn confirm_pdf_import(&mut self, page: u64, crop: String) -> Result { + /// Import Options confirmed for the delivered PDF; a placed one is added to the place cursor + /// when `append`, so the images loaded before it stay. + pub(crate) fn confirm_pdf_import(&mut self, page: u64, crop: String, append: bool) -> Result { let file = self.pending_pdf.take().ok_or("PDF import cancelled: no pending file")?; self.activate_import_target(&file.request)?; - let params = json!({"name": file.name, "base64": designcraft_engine::cmd::base64_encode(&file.bytes), "pdfPage": page, "pdfCrop": crop}); + let params = json!({"name": file.name, "base64": designcraft_engine::cmd::base64_encode(&file.bytes), "pdfPage": page, "pdfCrop": crop, "append": append}); if file.request.purpose == "place" { self.place_file(params) } else { self.open_file("file.place", params) } } @@ -243,8 +246,10 @@ impl DesignApp { if place && lower.ends_with(".pdf") { let pages = designcraft_render::pdf_page_count(&file.bytes).unwrap_or(1); if pages > 1 { - self.ui.dialog = - Some(dialogs::Dialog::new("pdfImport", json!({"async": true, "name": file.name.clone(), "page": "1", "pages": pages}))); + self.ui.dialog = Some(dialogs::Dialog::new( + "pdfImport", + json!({"async": true, "name": file.name.clone(), "page": "1", "pages": pages, "append": append}), + )); self.pending_pdf = Some(file); return Ok(Value::Null); } @@ -770,7 +775,7 @@ pub(crate) mod browser_import_tests { app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!(page.to_string())); // The native dialog clamps zero to one; positive invalid pages must fail. if page == 0 { - assert!(app.confirm_pdf_import(page, "crop".into()).is_err()); + assert!(app.confirm_pdf_import(page, "crop".into(), false).is_err()); } else { assert!(dialogs::confirm(&mut app).is_err()); } @@ -908,6 +913,51 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "one.pdf", "b.png"], "in the order dropped, all in the cursor"); } + /// A multi-page PDF after images in a native batch asks which page, then queues after them. + #[test] + fn native_batch_keeps_its_images_when_a_multi_page_pdf_is_confirmed() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + app.place_paths(vec![path("a.svg"), path("b.svg"), path("three.pdf")]).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "b.svg", "three.pdf"]); + } + + /// The same for files delivered by the host (a browser's Place): the images stay. + #[test] + fn inbox_keeps_its_images_when_a_multi_page_pdf_is_confirmed() { + let mut app = app(); + let request = app.import_request("place"); + for (name, bytes) in [("a.png", png(200)), ("b.png", png(90)), ("three.pdf", pdf_pages(3))] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["a.png", "b.png", "three.pdf"]); + } + + /// A single multi-page PDF still replaces what the cursor holds, as any single Place does. + #[test] + fn a_single_multi_page_pdf_replaces_the_cursor_when_confirmed() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("three.pdf").to_string_lossy().to_string(); + std::fs::write(&path, pdf_pages(3)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let b64 = designcraft_engine::cmd::base64_encode(&image()); + app.run("place.load", json!({"base64": b64, "name": "a.svg"})).unwrap(); + app.open_picked("place", path).unwrap(); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["three.pdf"]); + } + #[test] fn batch_cancel_status_uses_the_interface_language() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7662c0cb0..460a4bc71 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4630,12 +4630,14 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { }, }; if d.b("async") { - return app.confirm_pdf_import(page, if crop.is_empty() { "crop".into() } else { crop }); + return app.confirm_pdf_import(page, if crop.is_empty() { "crop".into() } else { crop }, d.b("append")); } if let Some(target) = d.fields.get("target").and_then(Value::as_u64) { app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target) })?; } - app.place_file(json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }})) + app.place_file( + json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }, "append": d.b("append")}), + ) } "print" => { let pages = if d.s("range") == "all" { Value::Null } else { json!(d.s("pages")) }; diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index ca0d38415..cae08a519 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From 267917b8de223df327e336e79c4ca646eda4de1e Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 19:56:22 -0500 Subject: [PATCH 023/322] Place: drops that arrive before one UI pass stay separate All pending drops went into one batch, so two single images counted as several: both queued and neither filled the frame it was dropped on. Files of one raw input now share a batch, and each batch is opened on its own. --- crates/ui-egui/src/app/input.rs | 13 +++++++------ crates/ui-egui/src/lib.rs | 3 +++ crates/ui-egui/src/tests.rs | 31 +++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/app/input.rs b/crates/ui-egui/src/app/input.rs index 465eeaaff..fe5fb673b 100644 --- a/crates/ui-egui/src/app/input.rs +++ b/crates/ui-egui/src/app/input.rs @@ -62,10 +62,11 @@ impl DesignApp { // A drop without pointer events (dragged in from another application) asks the // system now, while the pointer is still where the files were let go. let system = if pointer.is_none() && !raw.dropped_files.is_empty() { self.system_pointer(ctx, raw) } else { None }; + let batch = self.pending_drops.last().map_or(0, |d| d.batch.wrapping_add(1)); for file in std::mem::take(&mut raw.dropped_files) { let path = file.path().to_string_lossy().to_string(); if !path.is_empty() { - self.pending_drops.push(PendingDrop { path, pointer, system, generation }); + self.pending_drops.push(PendingDrop { path, pointer, system, batch, generation }); } } } @@ -154,12 +155,12 @@ impl DesignApp { // suppress later files that belong to the same captured batch. let current = self.input_generation(); let drops: Vec<_> = std::mem::take(&mut self.pending_drops).into_iter().filter(|d| d.generation == current).collect(); - if drops.is_empty() { - return; - } // Dropped together, they go together: several images load the place cursor at once. Each - // file keeps the pointer it was dropped at, or the system's from when it arrived. - self.open_dropped_batch(drops.into_iter().map(|d| (d.path, d.pointer.or(d.system))).collect()); + // file keeps the pointer it was dropped at, or the system's from when it arrived. Separate + // drops stay separate, so a single image still fills the frame it was dropped on. + for batch in drops.chunk_by(|a, b| a.batch == b.batch) { + self.open_dropped_batch(batch.iter().map(|d| (d.path.clone(), d.pointer.or(d.system))).collect()); + } } /// Where the pointer is in the window, asked of the system ([`crate::Services::pointer`]), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 531a8dbe7..239127c3b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -115,6 +115,9 @@ struct PendingDrop { /// for a drop that brought no pointer events ([`crate::Services::pointer`]). Each drop keeps /// its own, converted with the window's place and the UI scale of that input. system: Option, + /// Which drop this file came with: files of one raw input share it, so drops that arrive + /// before the same UI pass stay separate. + batch: u64, generation: InputGeneration, } diff --git a/crates/ui-egui/src/tests.rs b/crates/ui-egui/src/tests.rs index 5692ba7fe..39534b0eb 100644 --- a/crates/ui-egui/src/tests.rs +++ b/crates/ui-egui/src/tests.rs @@ -1011,6 +1011,37 @@ fn a_pointerless_drop_keeps_the_system_pointer_of_its_own_input() { assert!(d.assets[&g.asset].name.contains("drop-own-input")); } +/// Two drops that arrive before one UI pass stay separate: the first still fills the frame it was +/// dropped on, and the second, off any frame, loads the place cursor. Merged, they'd both queue. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn separate_drops_before_one_pass_are_not_one_batch() { + let (mut app, frame, inside, outside) = app_with_drop_frame(); + let at = std::rc::Rc::new(std::cell::Cell::new(inside)); + let reported = at.clone(); + app.services.pointer = Some(Box::new(move || Some(reported.get()))); + let ctx = egui::Context::default(); + let window = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)); + let (first, second) = (dropped_png("separate-drop-a"), dropped_png("separate-drop-b")); + let mut raw = pointerless_drop(&first, window); + app.raw_input_hook(&ctx, &mut raw); + at.set(outside); + let mut raw = pointerless_drop(&second, window); + app.raw_input_hook(&ctx, &mut raw); + assert_eq!(app.pending_drops.len(), 2); + ctx.run_ui(raw, |_| app.take_pending_drops()).textures_delta.clear(); + let _ = std::fs::remove_file(&first); + let _ = std::fs::remove_file(&second); + let d = &app.session.doc().unwrap().doc; + let designcraft_doc::Content::Graphic(g) = &d.item(designcraft_doc::ItemId(frame)).unwrap().content else { + panic!("the first drop fills the frame it was dropped on") + }; + assert!(d.assets[&g.asset].name.contains("separate-drop-a")); + let loaded = app.session.loaded.as_ref().expect("the second drop loads the place cursor"); + assert!(d.assets[&loaded.asset].name.contains("separate-drop-b")); + assert!(app.session.loaded_queue.is_empty()); +} + /// A filled compound path (Object > Compound Paths > Make) is a frame a dropped image fills, as /// in InDesign, through its ring and not its hole. #[test] From 391e0881b4e75294694916c1a8aa01f1e400bb08 Mon Sep 17 00:00:00 2001 From: texjer Date: Wed, 4 Nov 2026 19:56:42 -0500 Subject: [PATCH 024/322] Place: the grid tool sends the gutter it previews The preview's 6 pt duplicated place.grid's default, so changing one would leave the preview out of step with what lands. The tool now sends its gutter with the command. --- crates/tools/src/nav.rs | 5 +++-- crates/tools/src/tests.rs | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/nav.rs b/crates/tools/src/nav.rs index c86fc4fec..456c73ba9 100644 --- a/crates/tools/src/nav.rs +++ b/crates/tools/src/nav.rs @@ -155,7 +155,7 @@ impl Tool for PlaceGun { if !grid_cells(r, self.columns, self.rows).is_empty() { return vec![Action::Exec( "place.grid".into(), - json!({"spread": crate::spread_json(sr), "rect": [r.x0, r.y0, r.x1, r.y1], "columns": self.columns, "rows": self.rows}), + json!({"spread": crate::spread_json(sr), "rect": [r.x0, r.y0, r.x1, r.y1], "columns": self.columns, "rows": self.rows, "gutter": PLACE_GRID_GUTTER}), )]; } // The frame the drag drew: at the graphic's proportions from where it started. @@ -239,7 +239,8 @@ Y: {pct}" } } -/// The gutter between place-grid cells, in points: `place.grid`'s default. +/// The gutter between place-grid cells, in points. The tool sends it with `place.grid`, so the +/// preview and what lands can't disagree if the command's default changes. const PLACE_GRID_GUTTER: f64 = 6.0; /// The cells of a `columns` × `rows` place grid drawn over `rect`, [`PLACE_GRID_GUTTER`] apart, as diff --git a/crates/tools/src/tests.rs b/crates/tools/src/tests.rs index 9fd67fdd8..4949e20e4 100644 --- a/crates/tools/src/tests.rs +++ b/crates/tools/src/tests.rs @@ -2459,7 +2459,7 @@ fn place_gun_grid_preview_matches_the_release_on_a_rotated_spread() { assert_eq!(t.key(&cx, ToolKey::Right, Mods::default()), vec![Action::Handled]); let shown = t.overlays(&cx); let out = t.pointer(&cx, &PointerEvent::new(PointerKind::Up, end.x, end.y)); - assert!(matches!(out.as_slice(), [Action::Exec(cmd, p)] if cmd == "place.grid" && p["columns"] == 2), "{out:?}"); + assert!(matches!(out.as_slice(), [Action::Exec(cmd, p)] if cmd == "place.grid" && p["columns"] == 2 && p["gutter"] == 6.0), "{out:?}"); // Two columns on the spread, 6 pt apart, each shown where its corners land on the canvas. let r = Rect::from_points(a, b); let w = (r.width() - 6.0) / 2.0; From 8f2451bc6642d4cf7d8995e4cfa0e25e417f3106 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:13:55 -0500 Subject: [PATCH 025/322] Place: a PDF later in a batch joins the place cursor, whatever is selected With a graphic frame selected, `file.place` chose that frame before it looked at the place cursor, so a PDF confirmed with `append` filled the frame and left the images around it queued. An appended file now skips the selected-frame fallback; an explicit `frame` still applies, and a single placed file still fills the selected frame. --- crates/engine/src/cmd/file/place.rs | 9 ++++++--- crates/ui-egui/src/app/files.rs | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 081e3bd27..5ecd31268 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -100,8 +100,11 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { (nw, nh) } }; + // A file joining the place cursor's queue goes after the ones already there, whatever is selected. + let load_cursor_param = p.get("loadCursor").and_then(Value::as_bool) == Some(true); + let append = p.get("append").and_then(Value::as_bool) == Some(true); let target_frame = crate::cmd::id_param(p, "frame").or_else(|| { - if ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { + if (load_cursor_param && append) || ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { return None; } let st = s.active()?; @@ -115,8 +118,8 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { let lid = s.doc()?.active_layer; let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); - if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { - return load_cursor(s, asset, (bw, bh), p.get("append").and_then(Value::as_bool) == Some(true)); + if target_frame.is_none() && px.is_none() && py.is_none() && load_cursor_param { + return load_cursor(s, asset, (bw, bh), append); } s.edit(|d, sel| { let fresh = AssetId(d.alloc()); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 8b1682d83..48ca90e26 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1010,6 +1010,27 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg", "c.svg", "a.svg"]); } + /// A PDF later in a batch joins the place cursor with the images around it, even with a + /// graphic frame selected: it doesn't fill that frame and leave the others queued. + #[test] + fn a_pdf_in_a_batch_queues_rather_than_filling_the_selected_frame() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("one.pdf"), pdf_pages(1)).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let f = designcraft_doc::ItemId( + app.run("frame.create", json!({"rect": [200, 200, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(), + ); + assert!(app.session.active().unwrap().selection.items.contains(&f)); + app.place_paths(vec![path("a.svg"), path("one.pdf"), path("b.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg"]); + let frame = app.session.active().unwrap().doc.item(f).unwrap(); + assert!(!matches!(frame.content, designcraft_doc::Content::Graphic(_)), "the selected frame stays empty"); + } + /// File › Place with several files chosen in the dialog loads them all into the place /// cursor, in the order chosen; with one, it is placed as before. #[test] From e2b21cb3db126feb09e4bc4f6253c7c895ea01eb Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:13:55 -0500 Subject: [PATCH 026/322] Place: a PDF later in a batch joins the place cursor, whatever is selected With a graphic frame selected, `file.place` chose that frame before it looked at the place cursor, so a PDF confirmed with `append` filled the frame and left the images around it queued. An appended file now skips the selected-frame fallback; an explicit `frame` still applies, and a single placed file still fills the selected frame. --- crates/engine/src/cmd/file/place.rs | 9 ++++++--- crates/ui-egui/src/app/files.rs | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 081e3bd27..5ecd31268 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -100,8 +100,11 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { (nw, nh) } }; + // A file joining the place cursor's queue goes after the ones already there, whatever is selected. + let load_cursor_param = p.get("loadCursor").and_then(Value::as_bool) == Some(true); + let append = p.get("append").and_then(Value::as_bool) == Some(true); let target_frame = crate::cmd::id_param(p, "frame").or_else(|| { - if ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { + if (load_cursor_param && append) || ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { return None; } let st = s.active()?; @@ -115,8 +118,8 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { let lid = s.doc()?.active_layer; let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); - if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { - return load_cursor(s, asset, (bw, bh), p.get("append").and_then(Value::as_bool) == Some(true)); + if target_frame.is_none() && px.is_none() && py.is_none() && load_cursor_param { + return load_cursor(s, asset, (bw, bh), append); } s.edit(|d, sel| { let fresh = AssetId(d.alloc()); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index d98fba286..ba5b23105 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1063,6 +1063,27 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg", "c.svg", "a.svg"]); } + /// A PDF later in a batch joins the place cursor with the images around it, even with a + /// graphic frame selected: it doesn't fill that frame and leave the others queued. + #[test] + fn a_pdf_in_a_batch_queues_rather_than_filling_the_selected_frame() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("one.pdf"), pdf_pages(1)).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let f = designcraft_doc::ItemId( + app.run("frame.create", json!({"rect": [200, 200, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(), + ); + assert!(app.session.active().unwrap().selection.items.contains(&f)); + app.place_paths(vec![path("a.svg"), path("one.pdf"), path("b.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg"]); + let frame = app.session.active().unwrap().doc.item(f).unwrap(); + assert!(!matches!(frame.content, designcraft_doc::Content::Graphic(_)), "the selected frame stays empty"); + } + /// File › Place with several files chosen in the dialog loads them all into the place /// cursor, in the order chosen; with one, it is placed as before. #[test] From 64cc0c072dc11f6b2776d9b34aaf3fdf3712f647 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:13:55 -0500 Subject: [PATCH 027/322] Place: a PDF later in a batch joins the place cursor, whatever is selected With a graphic frame selected, `file.place` chose that frame before it looked at the place cursor, so a PDF confirmed with `append` filled the frame and left the images around it queued. An appended file now skips the selected-frame fallback; an explicit `frame` still applies, and a single placed file still fills the selected frame. --- crates/engine/src/cmd/file/place.rs | 9 ++++++--- crates/ui-egui/src/app/files.rs | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index f80d9d69f..6bf3d263d 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -100,8 +100,11 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { (nw, nh) } }; + // A file joining the place cursor's queue goes after the ones already there, whatever is selected. + let load_cursor_param = p.get("loadCursor").and_then(Value::as_bool) == Some(true); + let append = p.get("append").and_then(Value::as_bool) == Some(true); let target_frame = crate::cmd::id_param(p, "frame").or_else(|| { - if ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { + if (load_cursor_param && append) || ["x", "y", "spread", "width"].iter().any(|key| p.get(*key).is_some_and(|value| !value.is_null())) { return None; } let st = s.active()?; @@ -115,8 +118,8 @@ pub(super) fn file_place(s: &mut Session, p: &Value) -> Result { let lid = s.doc()?.active_layer; let px = p.get("x").and_then(Value::as_f64); let py = p.get("y").and_then(Value::as_f64); - if target_frame.is_none() && px.is_none() && py.is_none() && p.get("loadCursor").and_then(Value::as_bool) == Some(true) { - return load_cursor(s, asset, (bw, bh), p.get("append").and_then(Value::as_bool) == Some(true)); + if target_frame.is_none() && px.is_none() && py.is_none() && load_cursor_param { + return load_cursor(s, asset, (bw, bh), append); } s.edit(|d, sel| { let fresh = AssetId(d.alloc()); diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index e0bc04e22..ee576ccec 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1014,6 +1014,27 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg", "c.svg", "a.svg"]); } + /// A PDF later in a batch joins the place cursor with the images around it, even with a + /// graphic frame selected: it doesn't fill that frame and leave the others queued. + #[test] + fn a_pdf_in_a_batch_queues_rather_than_filling_the_selected_frame() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("one.pdf"), pdf_pages(1)).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let f = designcraft_doc::ItemId( + app.run("frame.create", json!({"rect": [200, 200, 300, 300], "content": "graphic"})).unwrap()["id"].as_u64().unwrap(), + ); + assert!(app.session.active().unwrap().selection.items.contains(&f)); + app.place_paths(vec![path("a.svg"), path("one.pdf"), path("b.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "one.pdf", "b.svg"]); + let frame = app.session.active().unwrap().doc.item(f).unwrap(); + assert!(!matches!(frame.content, designcraft_doc::Content::Graphic(_)), "the selected frame stays empty"); + } + /// File › Place with several files chosen in the dialog loads them all into the place /// cursor, in the order chosen; with one, it is placed as before. #[test] From 5868b6036584aff4d155ee181c9124e5ec12f08b Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:54:26 -0500 Subject: [PATCH 028/322] Place: the 1000-image cap holds for the whole place cursor when appending Appending only checked each batch against the cap, and a single image or a PDF added with append wasn't checked at all, so repeated appends could grow the cursor without limit. Refused before decoding a batch or adding an asset. --- crates/engine/src/cmd/file/place.rs | 90 ++++++++++++++++++++++++++++- docs/multi-image-placement.md | 2 +- 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 5ecd31268..5ac886618 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -253,6 +253,7 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES { return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images"))); } + check_cursor_room(s, sources.len(), append, "place.load")?; let mut images = Vec::with_capacity(sources.len()); for source in sources { let (bytes, name, link) = read_source(source)?; @@ -280,9 +281,18 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { Ok(json!({"remaining": loaded_count(s), "loaded": true})) } -/// Most images one `place.load` takes. +/// Most images the place cursor holds, and so most one `place.load` takes. const MAX_LOADED_IMAGES: usize = 1000; +/// Whether `incoming` images fit in the place cursor: appended, they go after the ones it holds. +fn check_cursor_room(s: &Session, incoming: usize, append: bool, command: &str) -> Result<()> { + let held = if append { loaded_count(s) } else { 0 }; + if held.saturating_add(incoming) > MAX_LOADED_IMAGES { + return Err(bad(command, format!("the place cursor holds at most {MAX_LOADED_IMAGES} images, and it has {held}"))); + } + Ok(()) +} + /// How many images the place cursor holds: the current one and those queued after it. fn loaded_count(s: &Session) -> usize { s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some())) @@ -291,6 +301,7 @@ fn loaded_count(s: &Session) -> usize { /// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with /// `append` and an image already loaded, queued after it). fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result { + check_cursor_room(s, 1, append, "place.load")?; let name = asset.name.clone(); let (pw, ph) = asset.pixels.unwrap_or_default(); let aid = s.edit(|d, _| { @@ -1067,3 +1078,80 @@ mod nested_frame_tests { assert_eq!(d.spreads[0].items.len(), 1, "no new object"); } } + +#[cfg(test)] +mod cursor_cap_tests { + use serde_json::{Value, json}; + + use super::MAX_LOADED_IMAGES; + use crate::Session; + + fn png() -> String { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: [200, 90, 30, 255].repeat(16) }.to_png(); + super::super::base64_encode(&png) + } + + /// A session whose place cursor holds `held` images, loaded without decoding each of them. + fn holding(held: usize) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("place.load", &json!({"base64": png(), "name": "first.png"})).unwrap(); + let first = s.loaded.unwrap(); + s.loaded_queue = std::iter::repeat_n(first, held - 1).collect(); + s + } + + fn count(s: &Session) -> usize { + super::loaded_count(s) + } + + /// Every way of adding to the cursor stops at the cap, and a refused add changes nothing. + #[test] + fn appending_stops_at_the_cap_on_the_whole_cursor() { + let image = png(); + let single = json!({"base64": image, "name": "a.png", "append": true}); + let placed = json!({"base64": image, "name": "a.png", "append": true, "loadCursor": true}); + let two = json!({"files": [{"base64": image, "name": "a.png"}, {"base64": image, "name": "b.png"}], "append": true}); + for (command, params) in [("place.load", &single), ("file.place", &placed), ("place.load", &two)] { + let mut s = holding(MAX_LOADED_IMAGES); + let assets = s.doc().unwrap().doc.assets.len(); + assert!(s.execute(command, params).is_err(), "{command} {params}"); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{command} {params}"); + assert_eq!(s.doc().unwrap().doc.assets.len(), assets, "{command} {params}"); + } + // One over, as a batch. + let mut s = holding(MAX_LOADED_IMAGES - 1); + assert!(s.execute("place.load", &two).is_err()); + assert_eq!(count(&s), MAX_LOADED_IMAGES - 1); + } + + /// The last places up to the cap load, and an unreadable batch reports the cap before decoding. + #[test] + fn appending_up_to_the_cap_still_loads() { + let image = png(); + for params in + [json!({"base64": image, "name": "a.png", "append": true}), json!({"files": [{"base64": image, "name": "a.png"}], "append": true})] + { + let mut s = holding(MAX_LOADED_IMAGES - 1); + s.execute("place.load", ¶ms).unwrap(); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{params}"); + } + let mut s = holding(MAX_LOADED_IMAGES); + let error = + s.execute("place.load", &json!({"files": [{"base64": "not an image", "name": "a.png"}], "append": true})).unwrap_err().to_string(); + assert!(error.contains(&MAX_LOADED_IMAGES.to_string()), "{error}"); + } + + /// Without `append` the new images replace the cursor, so what it holds doesn't count. + #[test] + fn replacing_a_full_cursor_is_not_capped() { + let image = png(); + let mut s = holding(MAX_LOADED_IMAGES); + let result: Value = s.execute("place.load", &json!({"base64": image, "name": "a.png"})).unwrap(); + assert_eq!(result["loaded"], true); + assert_eq!(count(&s), 1); + let mut s = holding(MAX_LOADED_IMAGES); + s.execute("place.load", &json!({"files": [{"base64": image, "name": "a.png"}]})).unwrap(); + assert_eq!(count(&s), 1); + } +} diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index cae08a519..bb58b600a 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From 15eeacc8456af6d9e194647b6d11c9b40c40b907 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 15:00:33 -0500 Subject: [PATCH 029/322] Place: the files after a multi-page PDF in a batch wait for its options They were left behind in place_paths when the PDF's Import Options opened, so the PDF was placed alone and the rest of what was chosen never loaded. They now wait in the dialog and carry on when it is confirmed; Cancel ends the batch. --- crates/ui-egui/src/app/files.rs | 82 +++++++++++++++++++++++++++------ crates/ui-egui/src/dialogs.rs | 16 ++++++- docs/multi-image-placement.md | 2 +- 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 48ca90e26..6f5368ad8 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -52,18 +52,21 @@ impl DesignApp { self.place_file(if append { json!({"path": path, "append": true}) } else { json!({"path": path}) }) } - /// Place an ordered batch of files, as File › Place with several chosen. The batch stops when - /// a file opens a dialog (a multi-page PDF's Import Options, an alert), as the inbox's does; - /// every file that loads the cursor adds to what the earlier ones loaded, in the order the - /// files were chosen (images in a row load together, before the file after them). A file that - /// can't be placed gets an alert and stops the batch; its error is returned, so automation - /// doesn't carry on as if the batch had loaded. + /// Place an ordered batch of files, as File › Place with several chosen. A multi-page PDF's + /// Import Options pause the batch: the files after it wait in the dialog and carry on when it + /// is confirmed, and Cancel ends the batch. Any other dialog (an alert, one already open) stops + /// it, as the inbox's does. Every file that loads the cursor adds to what the earlier ones + /// loaded, in the order the files were chosen (images in a row load together, before the file + /// after them). A file that can't be placed gets an alert and stops the batch; its error is + /// returned, so automation doesn't carry on as if the batch had loaded. pub(crate) fn place_paths(&mut self, paths: Vec) -> Result<(), String> { let mut images = Vec::new(); // Images already in the place cursor stay: the batch queues after them. let mut loaded = self.session.loaded.is_some(); - // `None` at the end loads the images left. - for path in paths.into_iter().map(Some).chain([None]) { + let mut paths = paths.into_iter(); + loop { + // `None` at the end loads the images left. + let path = paths.next(); if let Some(p) = &path && is_cursor_image(p) { @@ -71,7 +74,7 @@ impl DesignApp { continue; } if path.is_none() && images.is_empty() { - break; + return Ok(()); } if self.ui.dialog.is_some() { self.status(crate::i18n::tr(&self.ui.language, "Place cancelled while a dialog is open")); @@ -81,12 +84,14 @@ impl DesignApp { let r = self.load_place_cursor(std::mem::take(&mut images), loaded)?; loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); } - if let Some(p) = path { - let r = self.place_path(&p, loaded)?; - loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + let Some(p) = path else { return Ok(()) }; + let r = self.place_path(&p, loaded)?; + loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + if let Some(d) = self.ui.dialog.as_mut().filter(|d| d.id == "pdfImport") { + d.fields.insert(dialogs::PDF_IMPORT_REST.into(), json!(paths.collect::>())); + return Ok(()); } } - Ok(()) } /// `place.load` of `files` (`{path}` or `{name, base64}` each), queued after the images @@ -943,6 +948,57 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "b.png", "three.pdf"]); } + /// The files after a multi-page PDF in a native batch wait for its Import Options, through a + /// second such PDF too, and keep the order chosen. + #[test] + fn native_batch_continues_after_a_multi_page_pdf_is_confirmed() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + for name in ["a.svg", "b.svg", "c.svg", "d.svg"] { + std::fs::write(path(name), image()).unwrap(); + } + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + std::fs::write(path("two.pdf"), pdf_pages(2)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"].map(path).to_vec(); + app.place_paths(batch).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg"], "waiting for the first PDF's options"); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport"), "the second PDF asks in its turn"); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg"]); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"]); + } + + /// A refused page number keeps the rest of the batch waiting; Cancel ends the batch, and what + /// loaded before the PDF stays. + #[test] + fn native_batch_waits_through_a_refused_page_and_ends_at_cancel() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg"].map(path).to_vec(); + app.place_paths(batch.clone()).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("4-5")); + assert!(dialogs::confirm(&mut app).is_err()); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("2")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg"]); + + let mut app = self::app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + app.place_paths(batch).unwrap(); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg"]); + } + /// A single multi-page PDF still replaces what the cursor holds, as any single Place does. #[test] fn a_single_multi_page_pdf_replaces_the_cursor_when_confirmed() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4633620f3..b104a0ae1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1562,6 +1562,9 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, Ok(p) } +/// In a native batch's `pdfImport` dialog: the paths chosen after its PDF, placed once it is confirmed. +pub(crate) const PDF_IMPORT_REST: &str = "rest"; + /// File › Document Setup, filled from the document. /// The active document's ruler unit (picas without a document). fn doc_unit(app: &DesignApp) -> Unit { @@ -4711,9 +4714,18 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { if let Some(target) = d.fields.get("target").and_then(Value::as_u64) { app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target) })?; } - app.place_file( + let placed = app.place_file( json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }, "append": d.b("append")}), - ) + )?; + // The files chosen after this PDF, which waited for its options. + let rest: Vec = d + .fields + .get(PDF_IMPORT_REST) + .and_then(Value::as_array) + .map(|paths| paths.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default(); + app.place_paths(rest)?; + Ok(placed) } "print" => { let pages = if d.s("range") == "range" { json!(d.s("pages")) } else { Value::Null }; diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index bb58b600a..a99b4e144 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch pauses the batch at its import options; once confirmed, it queues after the images loaded before it and the rest of the batch follows. Cancelling them ends the batch, and the images already loaded stay. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From ba2237f8d5e13a910135bca16416ec8e4ce9bd59 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:54:26 -0500 Subject: [PATCH 030/322] Place: the 1000-image cap holds for the whole place cursor when appending Appending only checked each batch against the cap, and a single image or a PDF added with append wasn't checked at all, so repeated appends could grow the cursor without limit. Refused before decoding a batch or adding an asset. --- crates/engine/src/cmd/file/place.rs | 90 ++++++++++++++++++++++++++++- docs/multi-image-placement.md | 2 +- 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 5ecd31268..5ac886618 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -253,6 +253,7 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES { return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images"))); } + check_cursor_room(s, sources.len(), append, "place.load")?; let mut images = Vec::with_capacity(sources.len()); for source in sources { let (bytes, name, link) = read_source(source)?; @@ -280,9 +281,18 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { Ok(json!({"remaining": loaded_count(s), "loaded": true})) } -/// Most images one `place.load` takes. +/// Most images the place cursor holds, and so most one `place.load` takes. const MAX_LOADED_IMAGES: usize = 1000; +/// Whether `incoming` images fit in the place cursor: appended, they go after the ones it holds. +fn check_cursor_room(s: &Session, incoming: usize, append: bool, command: &str) -> Result<()> { + let held = if append { loaded_count(s) } else { 0 }; + if held.saturating_add(incoming) > MAX_LOADED_IMAGES { + return Err(bad(command, format!("the place cursor holds at most {MAX_LOADED_IMAGES} images, and it has {held}"))); + } + Ok(()) +} + /// How many images the place cursor holds: the current one and those queued after it. fn loaded_count(s: &Session) -> usize { s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some())) @@ -291,6 +301,7 @@ fn loaded_count(s: &Session) -> usize { /// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with /// `append` and an image already loaded, queued after it). fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result { + check_cursor_room(s, 1, append, "place.load")?; let name = asset.name.clone(); let (pw, ph) = asset.pixels.unwrap_or_default(); let aid = s.edit(|d, _| { @@ -1067,3 +1078,80 @@ mod nested_frame_tests { assert_eq!(d.spreads[0].items.len(), 1, "no new object"); } } + +#[cfg(test)] +mod cursor_cap_tests { + use serde_json::{Value, json}; + + use super::MAX_LOADED_IMAGES; + use crate::Session; + + fn png() -> String { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: [200, 90, 30, 255].repeat(16) }.to_png(); + super::super::base64_encode(&png) + } + + /// A session whose place cursor holds `held` images, loaded without decoding each of them. + fn holding(held: usize) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("place.load", &json!({"base64": png(), "name": "first.png"})).unwrap(); + let first = s.loaded.unwrap(); + s.loaded_queue = std::iter::repeat_n(first, held - 1).collect(); + s + } + + fn count(s: &Session) -> usize { + super::loaded_count(s) + } + + /// Every way of adding to the cursor stops at the cap, and a refused add changes nothing. + #[test] + fn appending_stops_at_the_cap_on_the_whole_cursor() { + let image = png(); + let single = json!({"base64": image, "name": "a.png", "append": true}); + let placed = json!({"base64": image, "name": "a.png", "append": true, "loadCursor": true}); + let two = json!({"files": [{"base64": image, "name": "a.png"}, {"base64": image, "name": "b.png"}], "append": true}); + for (command, params) in [("place.load", &single), ("file.place", &placed), ("place.load", &two)] { + let mut s = holding(MAX_LOADED_IMAGES); + let assets = s.doc().unwrap().doc.assets.len(); + assert!(s.execute(command, params).is_err(), "{command} {params}"); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{command} {params}"); + assert_eq!(s.doc().unwrap().doc.assets.len(), assets, "{command} {params}"); + } + // One over, as a batch. + let mut s = holding(MAX_LOADED_IMAGES - 1); + assert!(s.execute("place.load", &two).is_err()); + assert_eq!(count(&s), MAX_LOADED_IMAGES - 1); + } + + /// The last places up to the cap load, and an unreadable batch reports the cap before decoding. + #[test] + fn appending_up_to_the_cap_still_loads() { + let image = png(); + for params in + [json!({"base64": image, "name": "a.png", "append": true}), json!({"files": [{"base64": image, "name": "a.png"}], "append": true})] + { + let mut s = holding(MAX_LOADED_IMAGES - 1); + s.execute("place.load", ¶ms).unwrap(); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{params}"); + } + let mut s = holding(MAX_LOADED_IMAGES); + let error = + s.execute("place.load", &json!({"files": [{"base64": "not an image", "name": "a.png"}], "append": true})).unwrap_err().to_string(); + assert!(error.contains(&MAX_LOADED_IMAGES.to_string()), "{error}"); + } + + /// Without `append` the new images replace the cursor, so what it holds doesn't count. + #[test] + fn replacing_a_full_cursor_is_not_capped() { + let image = png(); + let mut s = holding(MAX_LOADED_IMAGES); + let result: Value = s.execute("place.load", &json!({"base64": image, "name": "a.png"})).unwrap(); + assert_eq!(result["loaded"], true); + assert_eq!(count(&s), 1); + let mut s = holding(MAX_LOADED_IMAGES); + s.execute("place.load", &json!({"files": [{"base64": image, "name": "a.png"}]})).unwrap(); + assert_eq!(count(&s), 1); + } +} diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 50061c8c0..478ad6755 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images, or drop a se - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. ## Dropping files From 3111d4086a0b216e01545529508b4e900476d2b7 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 15:00:33 -0500 Subject: [PATCH 031/322] Place: the files after a multi-page PDF in a batch wait for its options They were left behind in place_paths when the PDF's Import Options opened, so the PDF was placed alone and the rest of what was chosen never loaded. They now wait in the dialog and carry on when it is confirmed; Cancel ends the batch. --- crates/ui-egui/src/app/files.rs | 82 +++++++++++++++++++++++++++------ crates/ui-egui/src/dialogs.rs | 16 ++++++- docs/multi-image-placement.md | 2 +- 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index ba5b23105..4cd29d214 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -52,18 +52,21 @@ impl DesignApp { self.place_file(if append { json!({"path": path, "append": true}) } else { json!({"path": path}) }) } - /// Place an ordered batch of files, as File › Place with several chosen. The batch stops when - /// a file opens a dialog (a multi-page PDF's Import Options, an alert), as the inbox's does; - /// every file that loads the cursor adds to what the earlier ones loaded, in the order the - /// files were chosen (images in a row load together, before the file after them). A file that - /// can't be placed gets an alert and stops the batch; its error is returned, so automation - /// doesn't carry on as if the batch had loaded. + /// Place an ordered batch of files, as File › Place with several chosen. A multi-page PDF's + /// Import Options pause the batch: the files after it wait in the dialog and carry on when it + /// is confirmed, and Cancel ends the batch. Any other dialog (an alert, one already open) stops + /// it, as the inbox's does. Every file that loads the cursor adds to what the earlier ones + /// loaded, in the order the files were chosen (images in a row load together, before the file + /// after them). A file that can't be placed gets an alert and stops the batch; its error is + /// returned, so automation doesn't carry on as if the batch had loaded. pub(crate) fn place_paths(&mut self, paths: Vec) -> Result<(), String> { let mut images = Vec::new(); // Images already in the place cursor stay: the batch queues after them. let mut loaded = self.session.loaded.is_some(); - // `None` at the end loads the images left. - for path in paths.into_iter().map(Some).chain([None]) { + let mut paths = paths.into_iter(); + loop { + // `None` at the end loads the images left. + let path = paths.next(); if let Some(p) = &path && is_cursor_image(p) { @@ -71,7 +74,7 @@ impl DesignApp { continue; } if path.is_none() && images.is_empty() { - break; + return Ok(()); } if self.ui.dialog.is_some() { self.status(crate::i18n::tr(&self.ui.language, "Place cancelled while a dialog is open")); @@ -81,12 +84,14 @@ impl DesignApp { let r = self.load_place_cursor(std::mem::take(&mut images), loaded)?; loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); } - if let Some(p) = path { - let r = self.place_path(&p, loaded)?; - loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + let Some(p) = path else { return Ok(()) }; + let r = self.place_path(&p, loaded)?; + loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + if let Some(d) = self.ui.dialog.as_mut().filter(|d| d.id == "pdfImport") { + d.fields.insert(dialogs::PDF_IMPORT_REST.into(), json!(paths.collect::>())); + return Ok(()); } } - Ok(()) } /// `place.load` of `files` (`{path}` or `{name, base64}` each), queued after the images @@ -996,6 +1001,57 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "b.png", "three.pdf"]); } + /// The files after a multi-page PDF in a native batch wait for its Import Options, through a + /// second such PDF too, and keep the order chosen. + #[test] + fn native_batch_continues_after_a_multi_page_pdf_is_confirmed() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + for name in ["a.svg", "b.svg", "c.svg", "d.svg"] { + std::fs::write(path(name), image()).unwrap(); + } + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + std::fs::write(path("two.pdf"), pdf_pages(2)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"].map(path).to_vec(); + app.place_paths(batch).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg"], "waiting for the first PDF's options"); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport"), "the second PDF asks in its turn"); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg"]); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"]); + } + + /// A refused page number keeps the rest of the batch waiting; Cancel ends the batch, and what + /// loaded before the PDF stays. + #[test] + fn native_batch_waits_through_a_refused_page_and_ends_at_cancel() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg"].map(path).to_vec(); + app.place_paths(batch.clone()).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("4-5")); + assert!(dialogs::confirm(&mut app).is_err()); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("2")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg"]); + + let mut app = self::app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + app.place_paths(batch).unwrap(); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg"]); + } + /// A single multi-page PDF still replaces what the cursor holds, as any single Place does. #[test] fn a_single_multi_page_pdf_replaces_the_cursor_when_confirmed() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 4633620f3..b104a0ae1 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1562,6 +1562,9 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, Ok(p) } +/// In a native batch's `pdfImport` dialog: the paths chosen after its PDF, placed once it is confirmed. +pub(crate) const PDF_IMPORT_REST: &str = "rest"; + /// File › Document Setup, filled from the document. /// The active document's ruler unit (picas without a document). fn doc_unit(app: &DesignApp) -> Unit { @@ -4711,9 +4714,18 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { if let Some(target) = d.fields.get("target").and_then(Value::as_u64) { app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target) })?; } - app.place_file( + let placed = app.place_file( json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }, "append": d.b("append")}), - ) + )?; + // The files chosen after this PDF, which waited for its options. + let rest: Vec = d + .fields + .get(PDF_IMPORT_REST) + .and_then(Value::as_array) + .map(|paths| paths.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default(); + app.place_paths(rest)?; + Ok(placed) } "print" => { let pages = if d.s("range") == "range" { json!(d.s("pages")) } else { Value::Null }; diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 478ad6755..e64a26fbc 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images, or drop a se - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch pauses the batch at its import options; once confirmed, it queues after the images loaded before it and the rest of the batch follows. Cancelling them ends the batch, and the images already loaded stay. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. ## Dropping files From 5e1cb976f9fc3aeaded864cc5952851ac6e81306 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 14:54:26 -0500 Subject: [PATCH 032/322] Place: the 1000-image cap holds for the whole place cursor when appending Appending only checked each batch against the cap, and a single image or a PDF added with append wasn't checked at all, so repeated appends could grow the cursor without limit. Refused before decoding a batch or adding an asset. --- crates/engine/src/cmd/file/place.rs | 90 ++++++++++++++++++++++++++++- docs/multi-image-placement.md | 2 +- 2 files changed, 90 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file/place.rs b/crates/engine/src/cmd/file/place.rs index 6bf3d263d..c462fe773 100644 --- a/crates/engine/src/cmd/file/place.rs +++ b/crates/engine/src/cmd/file/place.rs @@ -253,6 +253,7 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { if sources.is_empty() || sources.len() > MAX_LOADED_IMAGES { return Err(bad("place.load", format!("select between 1 and {MAX_LOADED_IMAGES} images"))); } + check_cursor_room(s, sources.len(), append, "place.load")?; let mut images = Vec::with_capacity(sources.len()); for source in sources { let (bytes, name, link) = read_source(source)?; @@ -280,9 +281,18 @@ pub(super) fn place_load(s: &mut Session, p: &Value) -> Result { Ok(json!({"remaining": loaded_count(s), "loaded": true})) } -/// Most images one `place.load` takes. +/// Most images the place cursor holds, and so most one `place.load` takes. const MAX_LOADED_IMAGES: usize = 1000; +/// Whether `incoming` images fit in the place cursor: appended, they go after the ones it holds. +fn check_cursor_room(s: &Session, incoming: usize, append: bool, command: &str) -> Result<()> { + let held = if append { loaded_count(s) } else { 0 }; + if held.saturating_add(incoming) > MAX_LOADED_IMAGES { + return Err(bad(command, format!("the place cursor holds at most {MAX_LOADED_IMAGES} images, and it has {held}"))); + } + Ok(()) +} + /// How many images the place cursor holds: the current one and those queued after it. fn loaded_count(s: &Session) -> usize { s.loaded_queue.len().saturating_add(usize::from(s.loaded.is_some())) @@ -291,6 +301,7 @@ fn loaded_count(s: &Session) -> usize { /// Add a decoded asset with a fresh id, replacing the previous placement queue (or, with /// `append` and an image already loaded, queued after it). fn load_cursor(s: &mut Session, mut asset: Asset, size: (f64, f64), append: bool) -> Result { + check_cursor_room(s, 1, append, "place.load")?; let name = asset.name.clone(); let (pw, ph) = asset.pixels.unwrap_or_default(); let aid = s.edit(|d, _| { @@ -1107,3 +1118,80 @@ mod nested_frame_tests { assert_eq!(d.spreads[0].items.len(), 1, "no new object"); } } + +#[cfg(test)] +mod cursor_cap_tests { + use serde_json::{Value, json}; + + use super::MAX_LOADED_IMAGES; + use crate::Session; + + fn png() -> String { + let png = designcraft_render::Rendered { width: 4, height: 4, pixels: [200, 90, 30, 255].repeat(16) }.to_png(); + super::super::base64_encode(&png) + } + + /// A session whose place cursor holds `held` images, loaded without decoding each of them. + fn holding(held: usize) -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + s.execute("place.load", &json!({"base64": png(), "name": "first.png"})).unwrap(); + let first = s.loaded.unwrap(); + s.loaded_queue = std::iter::repeat_n(first, held - 1).collect(); + s + } + + fn count(s: &Session) -> usize { + super::loaded_count(s) + } + + /// Every way of adding to the cursor stops at the cap, and a refused add changes nothing. + #[test] + fn appending_stops_at_the_cap_on_the_whole_cursor() { + let image = png(); + let single = json!({"base64": image, "name": "a.png", "append": true}); + let placed = json!({"base64": image, "name": "a.png", "append": true, "loadCursor": true}); + let two = json!({"files": [{"base64": image, "name": "a.png"}, {"base64": image, "name": "b.png"}], "append": true}); + for (command, params) in [("place.load", &single), ("file.place", &placed), ("place.load", &two)] { + let mut s = holding(MAX_LOADED_IMAGES); + let assets = s.doc().unwrap().doc.assets.len(); + assert!(s.execute(command, params).is_err(), "{command} {params}"); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{command} {params}"); + assert_eq!(s.doc().unwrap().doc.assets.len(), assets, "{command} {params}"); + } + // One over, as a batch. + let mut s = holding(MAX_LOADED_IMAGES - 1); + assert!(s.execute("place.load", &two).is_err()); + assert_eq!(count(&s), MAX_LOADED_IMAGES - 1); + } + + /// The last places up to the cap load, and an unreadable batch reports the cap before decoding. + #[test] + fn appending_up_to_the_cap_still_loads() { + let image = png(); + for params in + [json!({"base64": image, "name": "a.png", "append": true}), json!({"files": [{"base64": image, "name": "a.png"}], "append": true})] + { + let mut s = holding(MAX_LOADED_IMAGES - 1); + s.execute("place.load", ¶ms).unwrap(); + assert_eq!(count(&s), MAX_LOADED_IMAGES, "{params}"); + } + let mut s = holding(MAX_LOADED_IMAGES); + let error = + s.execute("place.load", &json!({"files": [{"base64": "not an image", "name": "a.png"}], "append": true})).unwrap_err().to_string(); + assert!(error.contains(&MAX_LOADED_IMAGES.to_string()), "{error}"); + } + + /// Without `append` the new images replace the cursor, so what it holds doesn't count. + #[test] + fn replacing_a_full_cursor_is_not_capped() { + let image = png(); + let mut s = holding(MAX_LOADED_IMAGES); + let result: Value = s.execute("place.load", &json!({"base64": image, "name": "a.png"})).unwrap(); + assert_eq!(result["loaded"], true); + assert_eq!(count(&s), 1); + let mut s = holding(MAX_LOADED_IMAGES); + s.execute("place.load", &json!({"files": [{"base64": image, "name": "a.png"}]})).unwrap(); + assert_eq!(count(&s), 1); + } +} diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 99e8c809d..58cbdb60b 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -11,7 +11,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in For larger selections, choose **File > Place Contact Sheet…** after loading the images. Set columns, rows, gutter and page margin. All remaining images are fitted proportionally and centered in equal frames across as many new pages as needed. The default is 3 columns by 4 rows. New pages use the last document page's size and have no parent-page artwork. The entire contact sheet is one undo step. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. Image batches support up to 1000 images. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid or contact-sheet area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid or contact-sheet area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From dd311b88031dcae02e0e2223883517cc6a134eb0 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 15:00:33 -0500 Subject: [PATCH 033/322] Place: the files after a multi-page PDF in a batch wait for its options They were left behind in place_paths when the PDF's Import Options opened, so the PDF was placed alone and the rest of what was chosen never loaded. They now wait in the dialog and carry on when it is confirmed; Cancel ends the batch. --- crates/ui-egui/src/app/files.rs | 82 +++++++++++++++++++++++++++------ crates/ui-egui/src/dialogs.rs | 16 ++++++- docs/multi-image-placement.md | 2 +- 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index ee576ccec..bf9ce5e7b 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -52,18 +52,21 @@ impl DesignApp { self.place_file(if append { json!({"path": path, "append": true}) } else { json!({"path": path}) }) } - /// Place an ordered batch of files, as File › Place with several chosen. The batch stops when - /// a file opens a dialog (a multi-page PDF's Import Options, an alert), as the inbox's does; - /// every file that loads the cursor adds to what the earlier ones loaded, in the order the - /// files were chosen (images in a row load together, before the file after them). A file that - /// can't be placed gets an alert and stops the batch; its error is returned, so automation - /// doesn't carry on as if the batch had loaded. + /// Place an ordered batch of files, as File › Place with several chosen. A multi-page PDF's + /// Import Options pause the batch: the files after it wait in the dialog and carry on when it + /// is confirmed, and Cancel ends the batch. Any other dialog (an alert, one already open) stops + /// it, as the inbox's does. Every file that loads the cursor adds to what the earlier ones + /// loaded, in the order the files were chosen (images in a row load together, before the file + /// after them). A file that can't be placed gets an alert and stops the batch; its error is + /// returned, so automation doesn't carry on as if the batch had loaded. pub(crate) fn place_paths(&mut self, paths: Vec) -> Result<(), String> { let mut images = Vec::new(); // Images already in the place cursor stay: the batch queues after them. let mut loaded = self.session.loaded.is_some(); - // `None` at the end loads the images left. - for path in paths.into_iter().map(Some).chain([None]) { + let mut paths = paths.into_iter(); + loop { + // `None` at the end loads the images left. + let path = paths.next(); if let Some(p) = &path && is_cursor_image(p) { @@ -71,7 +74,7 @@ impl DesignApp { continue; } if path.is_none() && images.is_empty() { - break; + return Ok(()); } if self.ui.dialog.is_some() { self.status(crate::i18n::tr(&self.ui.language, "Place cancelled while a dialog is open")); @@ -81,12 +84,14 @@ impl DesignApp { let r = self.load_place_cursor(std::mem::take(&mut images), loaded)?; loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); } - if let Some(p) = path { - let r = self.place_path(&p, loaded)?; - loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + let Some(p) = path else { return Ok(()) }; + let r = self.place_path(&p, loaded)?; + loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); + if let Some(d) = self.ui.dialog.as_mut().filter(|d| d.id == "pdfImport") { + d.fields.insert(dialogs::PDF_IMPORT_REST.into(), json!(paths.collect::>())); + return Ok(()); } } - Ok(()) } /// `place.load` of `files` (`{path}` or `{name, base64}` each), queued after the images @@ -947,6 +952,57 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "b.png", "three.pdf"]); } + /// The files after a multi-page PDF in a native batch wait for its Import Options, through a + /// second such PDF too, and keep the order chosen. + #[test] + fn native_batch_continues_after_a_multi_page_pdf_is_confirmed() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + for name in ["a.svg", "b.svg", "c.svg", "d.svg"] { + std::fs::write(path(name), image()).unwrap(); + } + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + std::fs::write(path("two.pdf"), pdf_pages(2)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"].map(path).to_vec(); + app.place_paths(batch).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg"], "waiting for the first PDF's options"); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport"), "the second PDF asks in its turn"); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg"]); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg", "c.svg", "two.pdf", "d.svg"]); + } + + /// A refused page number keeps the rest of the batch waiting; Cancel ends the batch, and what + /// loaded before the PDF stays. + #[test] + fn native_batch_waits_through_a_refused_page_and_ends_at_cancel() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("a.svg"), image()).unwrap(); + std::fs::write(path("b.svg"), image()).unwrap(); + std::fs::write(path("three.pdf"), pdf_pages(3)).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let batch = ["a.svg", "three.pdf", "b.svg"].map(path).to_vec(); + app.place_paths(batch.clone()).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("4-5")); + assert!(dialogs::confirm(&mut app).is_err()); + app.ui.dialog.as_mut().unwrap().fields.insert("page".into(), json!("2")); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(loaded_names(&app), ["a.svg", "three.pdf", "b.svg"]); + + let mut app = self::app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + app.place_paths(batch).unwrap(); + dialogs::cancel(&mut app); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.svg"]); + } + /// A single multi-page PDF still replaces what the cursor holds, as any single Place does. #[test] fn a_single_multi_page_pdf_replaces_the_cursor_when_confirmed() { diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e6f6311b2..6730c3590 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1563,6 +1563,9 @@ fn text_frame_params(app: &DesignApp, d: &Dialog) -> Result, Ok(p) } +/// In a native batch's `pdfImport` dialog: the paths chosen after its PDF, placed once it is confirmed. +pub(crate) const PDF_IMPORT_REST: &str = "rest"; + /// File › Document Setup, filled from the document. /// The active document's ruler unit (picas without a document). fn doc_unit(app: &DesignApp) -> Unit { @@ -4758,9 +4761,18 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { if let Some(target) = d.fields.get("target").and_then(Value::as_u64) { app.activate_import_target(&crate::ImportRequest { purpose: "place".into(), target: Some(target) })?; } - app.place_file( + let placed = app.place_file( json!({"path": d.s("path"), "pdfPage": page, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }, "append": d.b("append")}), - ) + )?; + // The files chosen after this PDF, which waited for its options. + let rest: Vec = d + .fields + .get(PDF_IMPORT_REST) + .and_then(Value::as_array) + .map(|paths| paths.iter().filter_map(Value::as_str).map(str::to_string).collect()) + .unwrap_or_default(); + app.place_paths(rest)?; + Ok(placed) } "print" => { let pages = if d.s("range") == "range" { json!(d.s("pages")) } else { Value::Null }; diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index 58cbdb60b..8086650f5 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -11,7 +11,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in For larger selections, choose **File > Place Contact Sheet…** after loading the images. Set columns, rows, gutter and page margin. All remaining images are fitted proportionally and centered in equal frames across as many new pages as needed. The default is 3 columns by 4 rows. New pages use the last document page's size and have no parent-page artwork. The entire contact sheet is one undo step. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch stops the batch at its import options; once confirmed, it queues after the images loaded before it. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid or contact-sheet area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch pauses the batch at its import options; once confirmed, it queues after the images loaded before it and the rest of the batch follows. Cancelling them ends the batch, and the images already loaded stay. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid or contact-sheet area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From a66355b6ca2f44fa526b01b2b547a2636e6d1e49 Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 15:45:45 -0500 Subject: [PATCH 034/322] Place: say what a dropped batch does at a multi-page PDF MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit File › Place now carries on after the PDF's options; a drop still cancels the rest. --- crates/ui-egui/src/app/files.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 4cd29d214..730b6e222 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -295,7 +295,8 @@ impl DesignApp { /// cursor, each run of them where it came in the order, after any images it already holds, /// whatever is under the pointer: click to place them one by one, drag with the arrow keys for /// a grid. The rest of the drop is cancelled once a file opens a dialog (a multi-page PDF's - /// Import Options, an alert), as File › Place with several chosen is. + /// Import Options, an alert): unlike File › Place with several chosen, nothing waits for a + /// PDF's options to be confirmed. pub fn open_dropped_batch(&mut self, drops: Vec<(String, Option)>) { let several = drops.iter().filter(|(p, _)| is_cursor_image(p)).count() > 1; // Only the first graphic of a drop fills the frame under the pointer. From fea50adfafe5bb1290edde8a6e15c3cca86ad0cb Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 15:58:57 -0500 Subject: [PATCH 035/322] Place: contact sheet numbers mean the document unit however they arrive A number sent over ui.dialog.open or ui.dialog.set showed as 2 in the field but was sent as 2 points, while a typed 2 meant the ruler unit. --- crates/ui-egui/src/app/files.rs | 34 +++++++++++++++++++++++++++++++++ crates/ui-egui/src/dialogs.rs | 7 +++++-- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index bf9ce5e7b..38d7f137a 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -1124,6 +1124,40 @@ pub(crate) mod browser_import_tests { assert_eq!(d.s("gutter"), "6pt"); } + /// A bare number in a field means the document's ruler unit, whether it was typed or came as + /// a number over `ui.dialog.open` or `ui.dialog.set`. + #[test] + fn contact_sheet_numbers_are_in_the_document_unit_however_they_came() { + let frames = |margin: Value, gutter: Value, set: bool| { + let mut app = app(); + app.run("document.preferences", json!({"horizontalUnits": "inches"})).unwrap(); + let request = app.import_request("place"); + for name in ["one.png", "two.png"] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { + request: request.clone(), + name: name.into(), + bytes: png(200), + }); + } + app.drain_inbox(); + let fields = json!({"columns": 2, "rows": 1, "gutter": gutter, "margin": margin}); + app.ui.dialog = Some(dialogs::contact_sheet_dialog(&app, if set { json!({"columns": 2, "rows": 1}) } else { fields.clone() })); + if set { + let d = app.ui.dialog.as_mut().unwrap(); + d.set_field("gutter", fields["gutter"].clone()); + d.set_field("margin", fields["margin"].clone()); + } + dialogs::confirm(&mut app).unwrap(); + let doc = &app.session.doc().unwrap().doc; + doc.spreads.last().unwrap().items.iter().map(|item| item.bounds()).collect::>() + }; + let typed = frames(json!("1"), json!("0.5"), false); + assert_eq!(typed.len(), 2); + assert_eq!(frames(json!(1), json!(0.5), false), typed, "numbers over ui.dialog.open"); + assert_eq!(frames(json!(1), json!(0.5), true), typed, "numbers over ui.dialog.set"); + assert_eq!(frames(json!("72pt"), json!("36pt"), false), typed, "an explicit unit still says what it means"); + } + #[test] fn contact_sheet_validation_preserves_fields_and_pending_images() { let mut app = app(); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6730c3590..f6a15386b 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4721,11 +4721,14 @@ fn confirm_part3(app: &mut DesignApp, d: Dialog) -> Result { } "contactSheet" => { let result = (|| { + // A bare number means the ruler unit, as typed or as a JSON number (`Dialog::m` + // takes the latter as points). + let measure = |k: &str| parse_measure(&d.s(k), d.unit).ok(); let params = json!({ "columns": d.s("columns").trim().parse::().map_err(|_| "Columns must be a whole number")?, "rows": d.s("rows").trim().parse::().map_err(|_| "Rows must be a whole number")?, - "gutter": d.m("gutter").ok_or("Enter a valid gutter")?, - "margin": d.m("margin").ok_or("Enter a valid margin")?, + "gutter": measure("gutter").ok_or("Enter a valid gutter")?, + "margin": measure("margin").ok_or("Enter a valid margin")?, }); app.run("place.contactSheet", params) })(); From d5bb8a378c8c3ccb676885c19b2bc1feb49672ca Mon Sep 17 00:00:00 2001 From: texjer Date: Thu, 5 Nov 2026 18:40:41 -0500 Subject: [PATCH 036/322] Place: a browser batch waits for a PDF's options; a PDF first joins the cursor Files delivered after a multi-page PDF were dropped when its Import Options opened, with a status asking to choose them again, and choosing them again replaced the cursor. They now wait with the PDF and carry on when it is confirmed; Cancel ends the batch, as a native one's does. A batch starting with a single-page PDF, or in a browser with one image before a PDF, filled the selected frame instead of entering the place cursor. A browser delivers one Place's files together, so several in one delivery now count as a batch. One file alone still fills the frame. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/app/files.rs | 145 ++++++++++++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 2 + docs/multi-image-placement.md | 2 +- 4 files changed, 142 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index b2b433b71..0048a8c4e 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -39,6 +39,7 @@ impl DesignApp { let dialog_wake = std::sync::Arc::new(std::sync::OnceLock::new()); DesignApp { pending_pdf: None, + pending_pdf_rest: Vec::new(), #[cfg(not(target_arch = "wasm32"))] file_dialogs: file_dialogs::new_dialogs(dialog_wake.clone()), #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/app/files.rs b/crates/ui-egui/src/app/files.rs index 6f5368ad8..712f2b500 100644 --- a/crates/ui-egui/src/app/files.rs +++ b/crates/ui-egui/src/app/files.rs @@ -61,6 +61,8 @@ impl DesignApp { /// returned, so automation doesn't carry on as if the batch had loaded. pub(crate) fn place_paths(&mut self, paths: Vec) -> Result<(), String> { let mut images = Vec::new(); + // Several files go to the place cursor, even a PDF first with a frame selected. + let batch = paths.len() > 1; // Images already in the place cursor stay: the batch queues after them. let mut loaded = self.session.loaded.is_some(); let mut paths = paths.into_iter(); @@ -85,7 +87,7 @@ impl DesignApp { loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); } let Some(p) = path else { return Ok(()) }; - let r = self.place_path(&p, loaded)?; + let r = self.place_path(&p, batch || loaded)?; loaded |= r.get("loaded").and_then(Value::as_bool) == Some(true); if let Some(d) = self.ui.dialog.as_mut().filter(|d| d.id == "pdfImport") { d.fields.insert(dialogs::PDF_IMPORT_REST.into(), json!(paths.collect::>())); @@ -138,16 +140,28 @@ impl DesignApp { } pub(crate) fn cancel_pdf_import(&mut self) { + self.release_pending_pdf(); + } + + fn release_pending_pdf(&mut self) { self.pending_pdf = None; + self.pending_pdf_rest = Vec::new(); } /// Import Options confirmed for the delivered PDF; a placed one is added to the place cursor - /// when `append`, so the images loaded before it stay. + /// when `append`, so the images loaded before it stay. The files of its batch that waited for + /// the options carry on; if it can't be placed, the batch ends, as a native one does. pub(crate) fn confirm_pdf_import(&mut self, page: u64, crop: String, append: bool) -> Result { let file = self.pending_pdf.take().ok_or("PDF import cancelled: no pending file")?; + let rest = std::mem::take(&mut self.pending_pdf_rest); self.activate_import_target(&file.request)?; let params = json!({"name": file.name, "base64": designcraft_engine::cmd::base64_encode(&file.bytes), "pdfPage": page, "pdfCrop": crop, "append": append}); - if file.request.purpose == "place" { self.place_file(params) } else { self.open_file("file.place", params) } + if file.request.purpose != "place" { + return self.open_file("file.place", params); + } + let placed = self.place_file(params)?; + self.import_delivered(rest, true); + Ok(placed) } /// A single unresolved PDF owns its bytes. Later deliveries cancel explicitly rather than @@ -158,7 +172,7 @@ impl DesignApp { let owns_dialog = self.ui.dialog.as_ref().is_some_and(|d| d.id == "pdfImport" && d.fields.get("async").and_then(Value::as_bool) == Some(true)); if !target_exists || !owns_dialog { - self.pending_pdf = None; + self.release_pending_pdf(); if !target_exists { if owns_dialog { self.ui.dialog = None; @@ -169,14 +183,23 @@ impl DesignApp { } let Some(inbox) = self.services.inbox.clone() else { return }; let files = std::mem::take(&mut *inbox.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); + // A browser delivers one Place's files together. Several go to the place cursor, even a + // PDF first with a frame selected, as a native batch's do. + let batch = files.iter().filter(|f| f.request.purpose == "place").count() > 1; + self.import_delivered(files, batch); + } + + /// Imports `files` in the order they came; placed ones are added to the place cursor when + /// `append`, and after the first that loads it. A multi-page PDF's Import Options pause a + /// Place: the files after it wait with it and carry on when it is confirmed, and Cancel ends + /// the batch. + fn import_delivered(&mut self, files: Vec, mut append: bool) { let cursor_image = |file: &ImportedFile| { file.request.purpose == "place" && !file.name.to_ascii_lowercase().ends_with(".pdf") && (is_cursor_image(&file.name) || designcraft_render::image_size(&file.bytes).is_some()) }; - // In the order they came: consecutive images for the same document load the place - // cursor together; after the first placement into it, the later ones are added to it. - let mut append = false; + // Consecutive images for the same document load the place cursor together. let mut files = files.into_iter().peekable(); while let Some(file) = files.next() { if file.request.purpose == "shortcuts" { @@ -220,11 +243,17 @@ impl DesignApp { continue; } let name = file.name.clone(); + let target = file.request.target; match self.import_file(file, append) { Ok(_) if placing => append = true, Ok(_) => {} Err(e) => self.status(format!("{name}: {e}")), } + if placing && self.pending_pdf.is_some() { + while let Some(next) = files.next_if(|n| n.request.purpose == "place" && n.request.target == target) { + self.pending_pdf_rest.push(next); + } + } } } @@ -918,6 +947,108 @@ pub(crate) mod browser_import_tests { assert_eq!(loaded_names(&app), ["a.png", "one.pdf", "b.png"], "in the order dropped, all in the cursor"); } + /// A graphic frame, holding a picture and selected, with an empty place cursor; the frame's id. + fn select_a_graphic_frame(app: &mut DesignApp) -> u64 { + let frame = app.run("frame.create", json!({"rect": [10, 10, 100, 100]})).unwrap()["id"].as_u64().unwrap(); + let b64 = designcraft_engine::cmd::base64_encode(&image()); + app.run("file.place", json!({"base64": b64, "name": "old.svg", "frame": frame})).unwrap(); + app.run("selection.set", json!({"ids": [frame]})).unwrap(); + assert!(app.session.loaded.is_none()); + frame + } + + fn frame_asset(app: &DesignApp, frame: u64) -> String { + let doc = &app.session.active().unwrap().doc; + let designcraft_doc::Content::Graphic(g) = &doc.item(designcraft_doc::ItemId(frame)).unwrap().content else { panic!("a graphic") }; + doc.assets[&g.asset].name.clone() + } + + /// A PDF first in a native batch joins the cursor like the rest; the selected frame keeps its + /// picture. A PDF alone still fills it. + #[test] + fn native_batch_starting_with_a_pdf_leaves_the_selected_frame() { + let dir = tempfile::tempdir().unwrap(); + let path = |n: &str| dir.path().join(n).to_string_lossy().to_string(); + std::fs::write(path("one.pdf"), pdf_pages(1)).unwrap(); + std::fs::write(path("a.svg"), image()).unwrap(); + let mut app = app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let frame = select_a_graphic_frame(&mut app); + app.place_paths(vec![path("one.pdf"), path("a.svg")]).unwrap(); + assert_eq!(loaded_names(&app), ["one.pdf", "a.svg"]); + assert_eq!(frame_asset(&app, frame), "old.svg"); + + let mut app = self::app(); + app.services.read = Some(Box::new(|p| std::fs::read(p).map_err(|e| e.to_string()))); + let frame = select_a_graphic_frame(&mut app); + app.place_paths(vec![path("one.pdf")]).unwrap(); + assert!(app.session.loaded.is_none()); + assert_eq!(frame_asset(&app, frame), "one.pdf"); + } + + /// The same for files a host delivers (a browser's Place), with a PDF or an image first. + #[test] + fn inbox_batch_leaves_the_selected_frame() { + for names in [["one.pdf", "a.png"], ["a.png", "one.pdf"]] { + let mut app = app(); + let frame = select_a_graphic_frame(&mut app); + let request = app.import_request("place"); + for name in names { + let bytes = if name.ends_with(".pdf") { pdf_pages(1) } else { png(200) }; + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + assert_eq!(loaded_names(&app), names); + assert_eq!(frame_asset(&app, frame), "old.svg"); + } + // One file alone still fills it. + let mut app = app(); + let frame = select_a_graphic_frame(&mut app); + let request = app.import_request("place"); + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request, name: "one.pdf".into(), bytes: pdf_pages(1) }); + app.drain_inbox(); + assert_eq!(frame_asset(&app, frame), "one.pdf"); + } + + /// The files a host delivered after a multi-page PDF wait for its Import Options, through a + /// second such PDF too, keep their order and don't replace what the cursor holds. + #[test] + fn inbox_batch_continues_after_a_multi_page_pdf_is_confirmed() { + let mut app = app(); + let request = app.import_request("place"); + let files = + [("a.png", png(200)), ("three.pdf", pdf_pages(3)), ("b.png", png(90)), ("c.png", png(40)), ("two.pdf", pdf_pages(2)), ("d.png", png(20))]; + for (name, bytes) in files { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + assert_eq!(loaded_names(&app), ["a.png"], "waiting for the first PDF's options"); + assert_eq!(app.pending_pdf_rest.len(), 4); + dialogs::confirm(&mut app).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.id.as_str()), Some("pdfImport"), "the second PDF asks in its turn"); + assert_eq!(loaded_names(&app), ["a.png", "three.pdf", "b.png", "c.png"]); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(loaded_names(&app), ["a.png", "three.pdf", "b.png", "c.png", "two.pdf", "d.png"]); + assert!(app.pending_pdf.is_none() && app.pending_pdf_rest.is_empty()); + } + + /// Cancel ends a delivered batch, as a native one's does: what it loaded stays, the waiting + /// files are released. + #[test] + fn inbox_batch_ends_when_a_multi_page_pdf_is_cancelled() { + let mut app = app(); + let request = app.import_request("place"); + for (name, bytes) in [("a.png", png(200)), ("three.pdf", pdf_pages(3)), ("b.png", png(90))] { + app.services.inbox.as_ref().unwrap().lock().unwrap().push(ImportedFile { request: request.clone(), name: name.into(), bytes }); + } + app.drain_inbox(); + assert_eq!(app.pending_pdf_rest.len(), 1); + dialogs::cancel(&mut app); + assert!(app.pending_pdf.is_none() && app.pending_pdf_rest.is_empty()); + assert_eq!(loaded_names(&app), ["a.png"]); + } + /// A multi-page PDF after images in a native batch asks which page, then queues after them. #[test] fn native_batch_keeps_its_images_when_a_multi_page_pdf_is_confirmed() { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 6775c7755..ef7b7b0a4 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -131,6 +131,8 @@ struct ShotRequest { pub struct DesignApp { pending_pdf: Option, + /// The files of the batch after `pending_pdf`, which wait for its Import Options. + pending_pdf_rest: Vec, /// File and message dialogs: asked for during a frame, shown by the host at its end, answered /// on a later frame (see `app/file_dialogs.rs`). #[cfg(not(target_arch = "wasm32"))] diff --git a/docs/multi-image-placement.md b/docs/multi-image-placement.md index a99b4e144..c6b719584 100644 --- a/docs/multi-image-placement.md +++ b/docs/multi-image-placement.md @@ -9,7 +9,7 @@ Choose **File > Place** (Cmd+D on macOS) and select several images. They load in - Press Escape or select another tool to cancel the remaining placement. - Switching to, opening or closing a document also cancels it, and goes back to the Selection tool. -A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. A multi-page PDF in a batch pauses the batch at its import options; once confirmed, it queues after the images loaded before it and the rest of the batch follows. Cancelling them ends the batch, and the images already loaded stay. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. +A single selected file retains the normal Place behavior, including filling a selected frame and PDF import options. Several files go to the place cursor whatever is selected, even with a PDF first. A multi-page PDF in a batch pauses the batch at its import options; once confirmed, it queues after the images loaded before it and the rest of the batch follows. Cancelling them ends the batch, and the images already loaded stay. The place cursor holds up to 1000 images, counting those already in it when a batch adds to them. Rows and columns each range from 1 to 100. A batch containing an unreadable image fails without replacing the existing queue or changing the document. An invalid grid area also leaves the document and queue unchanged. Images here are PNG, JPEG, GIF, WebP, BMP, TIFF, SVG, PSD and EPS files. From 147b3f475056967353606b90fa0dc8bb39de7f27 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 9 Nov 2026 06:30:13 -0500 Subject: [PATCH 037/322] Release 0.19.0 --- Cargo.lock | 42 +++++++++++++++++++++--------------------- Cargo.toml | 2 +- 2 files changed, 22 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3bc1e94a2..2cef88cfb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1306,7 +1306,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.17.0" +version = "0.19.0" dependencies = [ "arboard", "craft-update", @@ -1331,7 +1331,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1348,7 +1348,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.17.0" +version = "0.19.0" dependencies = [ "craft-cms", "kurbo", @@ -1360,7 +1360,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1380,7 +1380,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.17.0" +version = "0.19.0" dependencies = [ "chrono", "designcraft-color", @@ -1393,7 +1393,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.17.0" +version = "0.19.0" dependencies = [ "caseless", "craft-atomic", @@ -1433,7 +1433,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.17.0" +version = "0.19.0" dependencies = [ "chrono", "designcraft-color", @@ -1443,7 +1443,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.17.0" +version = "0.19.0" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1456,7 +1456,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-doc", "designcraft-images", @@ -1468,7 +1468,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.17.0" +version = "0.19.0" dependencies = [ "flo_curves", "kurbo", @@ -1481,7 +1481,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1496,7 +1496,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.17.0" +version = "0.19.0" dependencies = [ "craft-cms", "designcraft-color", @@ -1514,7 +1514,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-engine", "designcraft-geom", @@ -1527,7 +1527,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.17.0" +version = "0.19.0" dependencies = [ "chrono", "craft-cms", @@ -1553,7 +1553,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.17.0" +version = "0.19.0" dependencies = [ "chrono", "designcraft-color", @@ -1571,7 +1571,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.17.0" +version = "0.19.0" dependencies = [ "craft-pdf", "designcraft-color", @@ -1590,7 +1590,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-doc", "quick-xml 0.41.0", @@ -1599,7 +1599,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1611,7 +1611,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.17.0" +version = "0.19.0" dependencies = [ "craft-dialogs", "craft-keymap", @@ -1645,7 +1645,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.17.0" +version = "0.19.0" dependencies = [ "designcraft-engine", "designcraft-format", @@ -7679,7 +7679,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.17.0" +version = "0.19.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 6a07b01b1..5a4143f12 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.17.0" +version = "0.19.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" From 741ccbbabb7bde2a60c1f40d2f32b2b2a71477dd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 14:27:23 -0500 Subject: [PATCH 038/322] Release 0.20.1: repair Flatpak update checks and self-updates (#2627) * Release 0.20.1: fix Flatpak update permissions * test: avoid unchecked option parsing in Flatpak regression --- Cargo.lock | 42 +++++++++---------- Cargo.toml | 2 +- crates/ui-egui/tests/flatpak_updates.rs | 27 ++++++++++++ .../ai.storyteller.designcraft.bundle.yml | 2 + .../flatpak/ai.storyteller.designcraft.yml | 2 + 5 files changed, 53 insertions(+), 22 deletions(-) create mode 100644 crates/ui-egui/tests/flatpak_updates.rs diff --git a/Cargo.lock b/Cargo.lock index 5505fc5f3..48cd5dd5f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1306,7 +1306,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.20.0" +version = "0.20.1" dependencies = [ "arboard", "craft-update", @@ -1331,7 +1331,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1348,7 +1348,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-cms", "kurbo", @@ -1360,7 +1360,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1380,7 +1380,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "designcraft-color", @@ -1393,7 +1393,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.20.0" +version = "0.20.1" dependencies = [ "caseless", "craft-atomic", @@ -1433,7 +1433,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "designcraft-color", @@ -1443,7 +1443,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.20.0" +version = "0.20.1" dependencies = [ "core-text", "harfrust 0.13.3", @@ -1456,7 +1456,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-doc", "designcraft-images", @@ -1468,7 +1468,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.20.0" +version = "0.20.1" dependencies = [ "flo_curves", "kurbo", @@ -1481,7 +1481,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1496,7 +1496,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-cms", "designcraft-color", @@ -1514,7 +1514,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-engine", "designcraft-geom", @@ -1527,7 +1527,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "craft-cms", @@ -1553,7 +1553,7 @@ dependencies = [ [[package]] name = "designcraft-pptx" -version = "0.20.0" +version = "0.20.1" dependencies = [ "chrono", "designcraft-color", @@ -1571,7 +1571,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-pdf", "designcraft-color", @@ -1590,7 +1590,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-doc", "quick-xml 0.41.0", @@ -1599,7 +1599,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1611,7 +1611,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.20.0" +version = "0.20.1" dependencies = [ "craft-dialogs", "craft-keymap", @@ -1645,7 +1645,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.20.0" +version = "0.20.1" dependencies = [ "designcraft-engine", "designcraft-format", @@ -7679,7 +7679,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.20.0" +version = "0.20.1" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index ee27e5fbd..496998bcb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"] default-members = ["crates/*", "apps/designcraft", "apps/designcraft-cli", "xtask"] [workspace.package] -version = "0.20.0" +version = "0.20.1" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95" diff --git a/crates/ui-egui/tests/flatpak_updates.rs b/crates/ui-egui/tests/flatpak_updates.rs new file mode 100644 index 000000000..01d835f42 --- /dev/null +++ b/crates/ui-egui/tests/flatpak_updates.rs @@ -0,0 +1,27 @@ +//! Release and source Flatpaks must allow release checks and host update helpers. +fn finish_args(manifest: &str) -> Vec<&str> { + manifest + .split("finish-args:") + .nth(1) + .unwrap_or_default() + .lines() + .take_while(|line| line.is_empty() || line.starts_with(' ') || line.starts_with('#')) + .filter_map(|line| line.trim().strip_prefix("- ")) + .map(|arg| arg.trim_matches(['\'', '"'])) + .collect() +} + +#[test] +fn flatpak_update_permissions() { + let manifests = [ + include_str!("../../../packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml"), + include_str!("../../../packaging/linux/flatpak/ai.storyteller.designcraft.yml"), + ]; + let args = manifests.map(finish_args); + assert_eq!(args[0], args[1], "source and release permissions must agree"); + for permissions in args { + for required in ["--share=network", "--talk-name=org.freedesktop.Flatpak"] { + assert!(permissions.contains(&required), "missing update permission: {required}"); + } + } +} diff --git a/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml b/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml index 750400657..eac2602c6 100644 --- a/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml +++ b/packaging/linux/flatpak/ai.storyteller.designcraft.bundle.yml @@ -17,6 +17,8 @@ runtime-version: '25.08' sdk: org.freedesktop.Sdk command: designcraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland diff --git a/packaging/linux/flatpak/ai.storyteller.designcraft.yml b/packaging/linux/flatpak/ai.storyteller.designcraft.yml index fd56910ce..4cbee1c12 100644 --- a/packaging/linux/flatpak/ai.storyteller.designcraft.yml +++ b/packaging/linux/flatpak/ai.storyteller.designcraft.yml @@ -18,6 +18,8 @@ sdk-extensions: - org.freedesktop.Sdk.Extension.rust-stable command: designcraft finish-args: + # The shared updater inspects and updates this installation via flatpak-spawn --host. + - --talk-name=org.freedesktop.Flatpak - --filesystem=xdg-data/ArtCraft/versions:ro # Display: Wayland first; X11 only when no Wayland compositor is running. - --socket=wayland From b9894b47c5131ab47c996e507fe2083f62525acf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 11:14:54 -0800 Subject: [PATCH 039/322] Images: decode the images in view together before drawing A render decoded each placed image that was not cached yet while drawing it, one after another, so page thumbnails, image exports and the first canvas frame of a page with several large photos took the sum of their decodes. Before drawing, the renderer now lists the images in view (with the same culling as drawing: hidden items and layers, nonprinting items, items out of view, PDF layer choices) and decodes the uncached ones on up to eight threads, with the mip levels they are drawn at. It leaves the work to the render when fewer than two images need decoding, on the web, and in Fast display. The images it decodes stay within what the cache keeps, sized by their pixels (PDF pages and SVGs at the size they are rasterized at), and decodes in flight together stay within half the cache budget. --- ROADMAP.md | 1 + crates/render/src/decode.rs | 34 ++++- crates/render/src/draw.rs | 151 +++++++++++++++------- crates/render/src/driver.rs | 33 +++-- crates/render/src/images.rs | 248 +++++++++++++++++++++++++++++++++++- crates/render/src/stroke.rs | 45 ++++--- crates/render/src/tests.rs | 86 +++++++++++++ 7 files changed, 517 insertions(+), 81 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index 1ed2064a0..00836637e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -388,6 +388,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m ## Progress log +- **2026-11-12** · A render decodes the placed images in view that are not cached yet on several threads before it draws, instead of one after another while drawing. Page thumbnails, image exports and the first canvas frame of a page with six 24 MP photos take about 1.2 s instead of 2.8 s. No readiness percentage change. - **2026-11-12** · An edit of a long threaded story composes the paragraphs it can change and copies the other lines from the composition before the edit; every typed character composed the whole story. In a 240-paragraph story a typed character composes 3 paragraphs (240 before). An edit that moves lines into other frames composes on until a paragraph starts in the same frame and place as before, or to the story's end, and stories with footnotes, tables, anchored objects, balanced columns or keep options that move lines are composed whole. No readiness percentage change. - **2026-11-12** · Type shortcuts: Justify All Lines ⇧⌘F, Insert White Space › Em Space ⇧⌘M and En Space ⇧⌘N (shown in the menu, enabled at an insertion point), Paragraph Rules… ⌥⌘J (shown in the Paragraph panel menu). On the Mac a menu-bar insert (Em/En Space, Current Page Number) no longer types into the document while a text field has focus, a dialog or Quick Apply is open, or an input method is composing. An alignment the paragraphs already have records no undo step (#1138). No readiness percentage change. - **2026-11-12** · The status bar's preflight count and the Preflight panel take their issues from a check on a background worker, which checks the newest state of the document and shows the issues last found meanwhile. Moving or resizing a frame and typing no longer wait for a check of the whole document on every drag step and keystroke. No readiness percentage change. diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 135dbf108..5668a205f 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -6,16 +6,46 @@ pub fn decode_pixmap(bytes: &[u8]) -> Option { decode_pixmap_page(bytes, 0) } +/// Longer side (pixels) PDF pages and SVGs are drawn at by [`decode_pixmap_page`]. +const VECTOR_SIDE: u32 = 3000; + +/// About how many bytes [`decode_pixmap_page`] of `bytes` takes, with its smaller levels (a third +/// more): PDF pages and SVGs at [`VECTOR_SIDE`] pixels on the longer side, an EPS without a +/// preview at up to 8 pixels per point and 4000 pixels on the longer side (as its PostScript is +/// drawn), other images and previews at their pixel size. 0 when the size can't be read. +pub(crate) fn decoded_bytes(bytes: &[u8], page: u32) -> usize { + let drawn = |(w, h): (f64, f64), side: f64, most: f64| { + let k = (side / w.max(h).max(1e-3)).min(most); + ((w * k).round().max(1.0), (h * k).round().max(1.0)) + }; + let size = if designcraft_images::is_eps(bytes) { + image_size(bytes).zip(designcraft_images::eps_size(bytes)).map(|((pw, ph), (w, h))| { + // Without a preview, the pixel size is the 2 pixels per point placeholder's. + let placeholder = ((w * 2.0).round().clamp(2.0, 4000.0), (h * 2.0).round().clamp(2.0, 4000.0)); + let px = (pw as f64, ph as f64); + if px == placeholder { drawn((w, h), 4000.0, 8.0) } else { px } + }) + } else if is_pdf(bytes) { + // As render_pdf_page scales: at most 8 times the page size. + pdf_page_size(bytes, page as usize).map(|s| drawn(s, VECTOR_SIDE as f64, 8.0)) + } else if designcraft_images::is_svg(bytes) { + designcraft_images::natural_size(bytes).map(|s| drawn(s, VECTOR_SIDE as f64, f64::INFINITY)) + } else { + image_size(bytes).map(|(w, h)| (w as f64, h as f64)) + }; + size.map_or(0, |(w, h)| (w * h * 16.0 / 3.0) as usize) +} + /// [`decode_pixmap`] for page `page` of a PDF (other formats have one page). pub fn decode_pixmap_page(bytes: &[u8], page: u32) -> Option { // Documents retain the EPS source; only display its TIFF preview or placeholder. let proxy = if designcraft_images::is_eps(bytes) { Some(designcraft_images::eps_proxy(bytes)?.0) } else { None }; let bytes = proxy.as_deref().unwrap_or(bytes); if is_pdf(bytes) { - return render_pdf_page(bytes, page as usize, 3000); + return render_pdf_page(bytes, page as usize, VECTOR_SIDE); } if designcraft_images::is_svg(bytes) { - let (px, w, h) = designcraft_images::render_svg(bytes, 3000)?; + let (px, w, h) = designcraft_images::render_svg(bytes, VECTOR_SIDE)?; let data = px.as_chunks::<4>().0.iter().map(|p| vello_cpu::color::PremulRgba8 { r: p[0], g: p[1], b: p[2], a: p[3] }).collect(); return Some(Pixmap::from_parts(data, w.min(u16::MAX as u32) as u16, h.min(u16::MAX as u32) as u16)); } diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 625338eb0..add9daa87 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -1,8 +1,9 @@ use super::color::{HIDDEN_LAYERS, blend_mode, color_of, overprints, rect_overlaps, screen_color, set_fill_paint, spread_blends}; -use super::types::{DisplayQuality, Frame}; +use super::stroke::image_want; +use super::types::{DisplayQuality, Frame, RenderOptions}; use super::{ - Affine, Arc, BezPath, BlendMode, Compose, ComposedStory, Content, DcBlend, Item, Mix, RenderContext, Renderer, Shape, ShownOn, SpreadRef, - StoryId, Vec2, blendspace, corners, fx, grid, kurbo, peniko, + Affine, Arc, BezPath, BlendMode, Compose, ComposedStory, Content, DcBlend, Document, Item, Mix, RenderContext, Renderer, Shape, ShownOn, + SpreadRef, StoryId, Vec2, blendspace, corners, fx, grid, images, kurbo, peniko, }; /// An item's fill under its content; an overprinting fill multiplies into what is beneath. @@ -25,6 +26,104 @@ fn draw_body_fill(ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, x } } +/// Each item spread `sr` draws at the top level, in drawing order (layers back to front; within +/// each layer parent items first), with its transform to the spread and where it shows. +fn each_top_item(doc: &Document, sr: SpreadRef, opts: &RenderOptions, mut visit: impl FnMut(&Item, Affine, ShownOn)) { + let Some(sp) = doc.spread(sr) else { return }; + for layer in doc.layers.iter().rev() { + if !layer.visible || opts.printing_only && !layer.printable { + continue; + } + // Document pages show their parent and its bases; a parent spread shows its bases. + let first = match sr { + SpreadRef::Doc(si) => Some(doc.first_page_of_spread(si)), + SpreadRef::Parent(_) => None, + }; + // Base items compose for where they show: the document page, or this parent spread. + let shown_on = |pi: usize| match (sr, first) { + (SpreadRef::Parent(p), _) => ShownOn::Parent(p), + (_, Some(a)) => ShownOn::Page(a + pi), + (_, None) => ShownOn::Own, + }; + for (pi, page) in sp.pages.iter().enumerate() { + if !page.show_parent_items { + continue; + } + let chain = doc.shown_parent_pages(sr, pi); + // This page's overrides and those of every parent page behind it (#1469). + let overridden = doc.overridden_parent_items(sr, pi); + for (ppi, ppage) in chain { + let Some(parent) = doc.parents.get(ppi) else { continue }; + let Some(ppg) = parent.pages.get(ppage) else { continue }; + let dx = page.x - ppg.x; + for it in &parent.items { + if it.layer != layer.id || overridden.contains(&it.id) { + continue; + } + // Parent items belong to the parent page they sit on. + if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 { + continue; + } + visit(it, Affine::translate((dx, 0.0)), shown_on(pi)); + } + } + } + for it in &sp.items { + if it.layer == layer.id { + visit(it, Affine::IDENTITY, ShownOn::Own); + } + } + } +} + +/// The placed images drawing spread `sr` in frame `f` takes from the image cache (see +/// [`images::warm`]), with the culling [`Renderer::draw_item`] applies. Images inside text (inline +/// and anchored objects) are left to the render. +pub(crate) fn wanted_images(f: &Frame, sr: SpreadRef, out: &mut Vec) { + // Fast display draws grey boxes for images. + if f.opts.quality == DisplayQuality::Fast { + return; + } + each_top_item(f.doc, sr, f.opts, |it, parent, _| wanted_in(f, it, parent, 0, out)); +} + +fn wanted_in(f: &Frame, it: &Item, parent: Affine, depth: usize, out: &mut Vec) { + // As deep as draw_item draws. + if depth >= 64 || it.hidden || f.opts.hidden.contains(&it.id) || f.opts.printing_only && it.nonprinting { + return; + } + let xf = parent * it.xf; + if !it.children().is_empty() && !it.has_nested_items() { + for c in it.shown_children() { + wanted_in(f, c, xf, depth + 1, out); + } + return; + } + let vb = xf.transform_rect_bbox(it.inner_bounds()).inflate(it.stroke.extent() + 2.0, it.stroke.extent() + 2.0); + let fx_outset = if it.effects.any() && f.opts.quality != DisplayQuality::Fast { fx::outset(it) } else { 0.0 }; + if !rect_overlaps(vb.inflate(fx_outset, fx_outset), f.visible) { + return; + } + match &it.content { + Content::Graphic(g) => { + let g = &if it.media.is_some() { it.drawn_graphic(&f.doc.assets).unwrap_or_else(|| g.clone()) } else { g.clone() }; + let Some(asset) = f.doc.assets.get(&g.asset) else { return }; + let hidden = it.has_pdf_layer_override().then(|| it.pdf_hidden_layers.clone()); + let previous = HIDDEN_LAYERS.with(|h| h.replace(hidden)); + if let Some((want, ..)) = image_want(f, asset, g, xf) { + out.push(want); + } + HIDDEN_LAYERS.with(|h| h.replace(previous)); + } + Content::Group { items } if it.has_nested_items() => { + for c in items { + wanted_in(f, c, xf, depth + 1, out); + } + } + _ => {} + } +} + impl Renderer { pub(crate) fn draw_spread(&mut self, ctx: &mut RenderContext, f: &Frame, sr: SpreadRef) { let doc = f.doc; @@ -70,51 +169,7 @@ impl Renderer { if isolate { ctx.push_layer(None, None, None, None, None); } - // Layers back to front; within each layer parent items first. - for layer in doc.layers.iter().rev() { - if !layer.visible || f.opts.printing_only && !layer.printable { - continue; - } - // Document pages show their parent and its bases; a parent spread shows its bases. - let first = match sr { - SpreadRef::Doc(si) => Some(doc.first_page_of_spread(si)), - SpreadRef::Parent(_) => None, - }; - // Base items compose for where they show: the document page, or this parent spread. - let shown_on = |pi: usize| match (sr, first) { - (SpreadRef::Parent(p), _) => ShownOn::Parent(p), - (_, Some(a)) => ShownOn::Page(a + pi), - (_, None) => ShownOn::Own, - }; - for (pi, page) in sp.pages.iter().enumerate() { - if !page.show_parent_items { - continue; - } - let chain = doc.shown_parent_pages(sr, pi); - // This page's overrides and those of every parent page behind it (#1469). - let overridden = doc.overridden_parent_items(sr, pi); - for (ppi, ppage) in chain { - let Some(parent) = doc.parents.get(ppi) else { continue }; - let Some(ppg) = parent.pages.get(ppage) else { continue }; - let dx = page.x - ppg.x; - for it in &parent.items { - if it.layer != layer.id || overridden.contains(&it.id) { - continue; - } - // Parent items belong to the parent page they sit on. - if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 { - continue; - } - self.draw_item(ctx, f, it, Affine::translate((dx, 0.0)), shown_on(pi)); - } - } - } - for it in &sp.items { - if it.layer == layer.id { - self.draw_item(ctx, f, it, Affine::IDENTITY, ShownOn::Own); - } - } - } + each_top_item(doc, sr, f.opts, |it, parent, page| self.draw_item(ctx, f, it, parent, page)); if isolate { ctx.pop_layer(); } diff --git a/crates/render/src/driver.rs b/crates/render/src/driver.rs index c837e3686..e217def45 100644 --- a/crates/render/src/driver.rs +++ b/crates/render/src/driver.rs @@ -1,8 +1,10 @@ use super::color::{PLATE, RICH_BLACK, blend_space_view, rect_overlaps}; use super::decode::now; +use super::draw::wanted_images; use super::types::{Frame, FrameStats, MAX_PAGE_PIXELS, MAX_SIDE, Placed, RenderOptions, Rendered, default_threads}; use super::{ - Affine, Cache, Document, HashMap, PageSide, Rect, RenderContext, Renderer, Resources, SpreadRef, Vec2, blendspace, kurbo, peniko, text, vello_cpu, + Affine, Cache, Document, HashMap, PageSide, Rect, RenderContext, Renderer, Resources, SpreadRef, Vec2, blendspace, images, kurbo, peniko, text, + vello_cpu, }; impl Renderer { @@ -100,17 +102,26 @@ impl Renderer { } let px = 1.0 / view.determinant().abs().sqrt().max(1e-12); let canvas_visible = view.inverse().transform_rect_bbox(Rect::new(0.0, 0.0, w as f64, h as f64)); - for pl in spreads { - let Some(sp) = doc.spread(pl.spread) else { continue }; - let sview = view * pl.xf; - let visible = pl.xf.inverse().transform_rect_bbox(canvas_visible); - let bounds = sp.bounds(); - // Cull spreads far outside the viewport (pasteboard items may extend; allow a margin). - if !rect_overlaps(bounds.inflate(2000.0, 2000.0), visible) { - continue; + let frames: Vec<(Frame, SpreadRef)> = spreads + .iter() + .filter_map(|pl| { + let sp = doc.spread(pl.spread)?; + let visible = pl.xf.inverse().transform_rect_bbox(canvas_visible); + // Cull spreads far outside the viewport (pasteboard items may extend; allow a margin). + rect_overlaps(sp.bounds().inflate(2000.0, 2000.0), visible) + .then_some((Frame { doc, cache, view: view * pl.xf, visible, px, opts, mt }, pl.spread)) + }) + .collect(); + // Decode the images in view that aren't cached yet together, before drawing them. + if images::can_warm() { + let mut wanted = Vec::new(); + for (f, sr) in &frames { + wanted_images(f, *sr, &mut wanted); } - let f = Frame { doc, cache, view: sview, visible, px, opts, mt }; - self.draw_spread(&mut ctx, &f, pl.spread); + images::warm(wanted); + } + for (f, sr) in &frames { + self.draw_spread(&mut ctx, f, *sr); } ctx.flush(); // Render straight into the returned buffer (no extra copy of the frame). diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 37606097d..ee0d917ba 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -6,10 +6,12 @@ //! are evicted beyond a memory budget; at most `MAX_BAD` failed assets are remembered. use std::collections::HashMap; -use std::sync::{Arc, Mutex}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex}; use vello_cpu::Pixmap; +use crate::decode::decoded_bytes; use crate::{decode_pixmap_page, halve}; /// Decoded pixels kept (bytes). @@ -114,7 +116,10 @@ pub fn decoded(bytes: &Arc>, page: u32) -> Option> { return None; } // Decode outside the lock: other threads keep drawing cached images meanwhile. - match decode_pixmap_page(bytes, page) { + let pm = decode_pixmap_page(bytes, page); + #[cfg(test)] + DECODED_ON.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push((id, std::thread::current().id())); + match pm { Some(pm) => { let pm = Arc::new(pm); store(bytes, page, 0, pm.clone()); @@ -149,6 +154,160 @@ pub fn mip(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Op Some(pm) } +/// The decodes [`decoded`] ran: the address of the encoded bytes and the thread. +#[cfg(test)] +pub(crate) static DECODED_ON: Mutex> = Mutex::new(Vec::new()); + +/// A placed image a render draws, as [`mip`] takes it: the encoded bytes, the PDF page, the +/// width (points) and the device pixels per point. +pub(crate) struct Want { + pub bytes: Arc>, + pub page: u32, + pub width_pt: f64, + pub on_screen: f64, +} + +/// Threads [`warm`] decodes on (1 on the web, which has none). +fn workers() -> usize { + #[cfg(target_arch = "wasm32")] + { + 1 + } + #[cfg(not(target_arch = "wasm32"))] + { + std::thread::available_parallelism().map_or(2, std::num::NonZero::get).clamp(2, 8) + } +} + +/// Whether [`warm`] can decode on several threads here. +pub(crate) fn can_warm() -> bool { + workers() >= 2 +} + +/// Whether a decode of about `size` bytes may start while decodes of `in_flight` bytes run: when +/// none run, or when together they take at most half the budget. +fn admits(in_flight: usize, size: usize) -> bool { + in_flight == 0 || in_flight.saturating_add(size) <= BUDGET / 2 +} + +/// Bytes decoding at once and the most there were, with the signal that some finished. +type Gate = (Mutex<(usize, usize)>, Condvar); + +/// Takes a finished decode's bytes off its [`Gate`] when dropped. +struct Release<'a>(&'a Gate, usize); + +impl Drop for Release<'_> { + fn drop(&mut self) { + let mut g = self.0.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + g.0 = g.0.saturating_sub(self.1); + drop(g); + self.0.1.notify_all(); + } +} + +/// Decode the images in `wants` that are not cached yet on several threads at once, with the +/// mip levels they are drawn at, so the render that draws them next finds them cached instead +/// of decoding them one after another. Does nothing when fewer than two images need decoding. +/// The images in view that are cached count against the cache budget first; a new image that +/// would take the total past what the cache keeps (by its pixel size) is left to the render. +/// Decodes wait while those in flight together would take more than half the budget. Returns +/// the most bytes (estimated) that were decoding at once. +pub(crate) fn warm(wants: Vec) -> usize { + let workers = workers(); + if workers < 2 { + return 0; + } + // What is drawn of each asset and page, in drawing order. + let mut assets: Vec<((usize, u32), Vec)> = Vec::new(); + let mut index: HashMap<(usize, u32), usize> = HashMap::new(); + for w in wants { + let key = (Arc::as_ptr(&w.bytes) as usize, w.page); + match index.get(&key).and_then(|&i| assets.get_mut(i)) { + Some(a) => a.1.push(w), + None => { + index.insert(key, assets.len()); + assets.push((key, vec![w])); + } + } + } + // The bytes each asset in view holds in the cache, when it is cached or failed, and the bytes + // of everything else cached. Its levels become the most recently used, so the stores below + // evict other images first. + let (held, others) = with(|c| { + c.clock += 1; + let clock = c.clock; + let mut held: HashMap<(usize, u32), usize> = HashMap::new(); + for (k, e) in c.map.iter_mut() { + if index.contains_key(&(k.0, k.1)) { + e.stamp = clock; + *held.entry((k.0, k.1)).or_default() += size_of(&e.pm); + } + } + let in_view = held.values().sum::(); + // Smaller levels alone don't make an asset cached. + held.retain(|k, _| c.map.contains_key(&(k.0, k.1, 0))); + for k in index.keys() { + if c.bad.contains_key(k) { + held.entry(*k).or_default(); + } + } + (held, c.bytes.saturating_sub(in_view)) + }); + // One image to decode gains nothing from threads (and is not worth sizing). + if assets.iter().filter(|(key, _)| !held.contains_key(key)).count() < 2 { + return 0; + } + let mut pixels = held.values().fold(0usize, |n, b| n.saturating_add(*b)); + let mut jobs: Vec<(usize, Vec)> = Vec::new(); + for (key, wanted) in assets { + if held.contains_key(&key) { + continue; + } + let size = wanted.first().map_or(0, |w| decoded_bytes(&w.bytes, w.page)); + // A store past the budget evicts down to three quarters of it: the images in view must + // fit in that, unless they and the rest fit in the budget. + let total = pixels.saturating_add(size); + if total > BUDGET * 3 / 4 && others.saturating_add(total) > BUDGET { + continue; + } + pixels = total; + jobs.push((size, wanted)); + } + if jobs.len() < 2 { + return 0; + } + // While it converts the pixels, a decode holds buffers of about its size besides the cache: + // a decode waits while those in flight would take it past half the budget (one always runs). + let gate: Gate = (Mutex::new((0, 0)), Condvar::new()); + let lock = || gate.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..workers.min(jobs.len()) { + let work = || { + while let Some((size, job)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { + let mut g = lock(); + while !admits(g.0, *size) { + g = gate.1.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner); + } + g.0 += size; + g.1 = g.1.max(g.0); + drop(g); + // Released even if the decode panics, so no other decode waits forever. + let _release = Release(&gate, *size); + for w in job { + let _ = mip(&w.bytes, w.page, w.width_pt, w.on_screen); + } + } + }; + // A thread that can't start leaves its share to the others, or to the render. + if std::thread::Builder::new().name("image decode".into()).spawn_scoped(s, work).is_err() { + break; + } + } + }); + gate.0.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner).1 +} + /// Drop every decoded image. pub fn clear() { with(|c| { @@ -176,4 +335,89 @@ mod tests { let last = &buffers[MAX_BAD + 9]; assert!(c.bad.contains_key(&(Arc::as_ptr(last) as usize, 0))); } + + fn png(side: u32, value: u8) -> Arc> { + let mut out = Vec::new(); + let img = image::RgbaImage::from_pixel(side, side, image::Rgba([value, 0, 0, 255])); + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + Arc::new(out) + } + + fn want(bytes: &Arc>) -> Want { + Want { bytes: bytes.clone(), page: 0, width_pt: 100.0, on_screen: 1.0 } + } + + /// A PSD header claiming `side` pixels square (its pixels don't decode). + fn psd(side: u32) -> Arc> { + let mut psd = b"8BPS".to_vec(); + psd.resize(26, 0); + psd[14..18].copy_from_slice(&side.to_be_bytes()); + psd[18..22].copy_from_slice(&side.to_be_bytes()); + Arc::new(psd) + } + + /// Where the decode log ends now. Taken after the test's images are made: while they live, + /// no other buffer has their address, so later entries with it are theirs. + fn mark() -> usize { + DECODED_ON.lock().unwrap().len() + } + + /// The threads that decoded `bytes` after `since`. + fn decoders(bytes: &Arc>, since: usize) -> Vec { + let id = Arc::as_ptr(bytes) as usize; + DECODED_ON.lock().unwrap().iter().skip(since).filter(|(a, _)| *a == id).map(|(_, t)| *t).collect() + } + + #[test] + fn warm_decodes_several_images_off_the_calling_thread() { + let images: Vec<_> = (0..3u8).map(|i| png(8, 40 + i)).collect(); + let since = mark(); + // The same image drawn at two sizes is one decode. + let mut wants: Vec = images.iter().map(want).collect(); + wants.push(Want { on_screen: 0.1, ..want(&images[0]) }); + warm(wants); + let me = std::thread::current().id(); + for img in &images { + let on = decoders(img, since); + assert_eq!(on.len(), 1, "decoded once"); + assert_ne!(on[0], me, "decoded on a worker"); + } + } + + #[test] + fn warm_leaves_one_image_or_an_over_budget_one_to_the_render() { + // A header claiming 100,000 pixels square is far past the budget. + let (one, huge, a, b, c) = (png(8, 7), psd(100_000), png(8, 9), png(8, 11), png(8, 13)); + let since = mark(); + warm(vec![want(&one)]); + assert!(decoders(&one, since).is_empty(), "one image: no threads"); + // The huge one, first or not, is left to the render; the small images beside it are + // decoded ahead. + warm(vec![want(&huge), want(&a), want(&b)]); + assert!(decoders(&huge, since).is_empty(), "over budget: not decoded ahead"); + assert_eq!((decoders(&a, since).len(), decoders(&b, since).len()), (1, 1)); + // With the huge one and a single small image, nothing is left to do together. + warm(vec![want(&c), want(&huge)]); + assert!(decoders(&c, since).is_empty() && decoders(&huge, since).is_empty()); + } + + #[test] + fn warm_decodes_large_images_one_at_a_time() { + // Two 7,000 pixel square images fit the budget together, but decoding both at once would + // take more than half of it; the small image still decodes beside them. + let (d, e, small) = (psd(7000), psd(7000), png(8, 15)); + let since = mark(); + let large = decoded_bytes(&d, 0); + assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); + assert!(admits(0, large) && !admits(large, large) && admits(large, decoded_bytes(&small, 0))); + assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); + let peak = warm(vec![want(&d), want(&e), want(&small)]); + assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); + assert!(peak >= large, "the large images were decoded ahead"); + let me = std::thread::current().id(); + for img in [&d, &e, &small] { + let on = decoders(img, since); + assert!(on.len() == 1 && on[0] != me); + } + } } diff --git a/crates/render/src/stroke.rs b/crates/render/src/stroke.rs index a63dd44a3..a10df2da2 100644 --- a/crates/render/src/stroke.rs +++ b/crates/render/src/stroke.rs @@ -6,6 +6,30 @@ use super::{ pdf_layers, peniko, vello_cpu, }; +/// The pixels drawing placed graphic `g` takes from the image cache, the page rectangle they +/// cover in graphic space and that page's height (points). `None` for video and sound, Fast +/// display and a PDF whose hidden layers can't be applied (none of these draw image pixels). +pub(crate) fn image_want(f: &Frame, asset: &designcraft_doc::Asset, g: &designcraft_doc::Graphic, xf: Affine) -> Option<(images::Want, Rect, f64)> { + if designcraft_doc::media_kind(&asset.mime).is_some() || f.opts.quality == DisplayQuality::Fast { + return None; + } + // Pick a mip level close to the on-screen size (Typical: a 72 ppi proxy). + let on_screen = (f.view * xf * g.xf).determinant().abs().sqrt(); + let on_screen = if f.opts.quality == DisplayQuality::Typical { on_screen.min(1.0) } else { on_screen }; + let hidden = HIDDEN_LAYERS.with(|h| h.borrow().clone()); + let data = match hidden.as_deref().filter(|_| is_pdf(&asset.data)) { + // An explicit choice (including all-on) that cannot be rewritten fails closed: + // stale persisted/relinked choices must not reveal hidden source content. + Some(hidden) => pdf_layers::layered(&asset.data, hidden)?, + None => asset.data.clone(), + }; + // A placed PDF cropped to a box: the whole page, placed so that the box spans graphic space. + let [l, t, r, b] = shown_box(asset).unwrap_or([0.0, 0.0, 1.0, 1.0]); + let (page_w, page_h) = (g.size.0 / (r - l), g.size.1 / (b - t)); + let page = Rect::new(-l * page_w, -t * page_h, (1.0 - l) * page_w, (1.0 - t) * page_h); + Some((images::Want { bytes: data, page: asset.page, width_pt: page_w, on_screen }, page, page_h)) +} + /// `stroke` as round dots `weight` wide, one every `2 × weight`. Kurbo's stroker drops /// zero-length dashes, so each dot is a dash a hair long, centred where the zero-length dash /// would be (so the path's ends get dots too). @@ -170,24 +194,9 @@ impl Renderer { ctx.fill_rect(&Rect::new(0.0, 0.0, g.size.0, g.size.1)); return; } - // Pick a mip level close to the on-screen size (Typical: a 72 ppi proxy). - let on_screen = (f.view * xf * g.xf).determinant().abs().sqrt(); - let on_screen = if f.opts.quality == DisplayQuality::Typical { on_screen.min(1.0) } else { on_screen }; - let hidden = HIDDEN_LAYERS.with(|h| h.borrow().clone()); - let data = match hidden.as_deref().filter(|_| is_pdf(&asset.data)) { - // An explicit choice (including all-on) that cannot be rewritten fails closed: - // stale persisted/relinked choices must not reveal hidden source content. - Some(hidden) => { - let Some(variant) = pdf_layers::layered(&asset.data, hidden) else { return }; - variant - } - None => asset.data.clone(), - }; - // A placed PDF cropped to a box: the whole page, placed so that the box spans graphic space. - let [l, t, r, b] = shown_box(asset).unwrap_or([0.0, 0.0, 1.0, 1.0]); - let (page_w, page_h) = (g.size.0 / (r - l), g.size.1 / (b - t)); - let page = Rect::new(-l * page_w, -t * page_h, (1.0 - l) * page_w, (1.0 - t) * page_h); - let Some(pm) = images::mip(&data, asset.page, page_w, on_screen) else { return }; + let Some((want, page, page_h)) = image_want(f, asset, g, xf) else { return }; + let page_w = want.width_pt; + let Some(pm) = images::mip(&want.bytes, want.page, page_w, want.on_screen) else { return }; // A coloured image is already in the plate's inks (its colours come from `color_of`). let pm = match (colorize::colorized(f.doc, &g.fill, &asset.data, &pm), PLATE.with(std::cell::Cell::get)) { (Some(coloured), _) => coloured, diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 3287ab836..5d4f6a048 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -773,3 +773,89 @@ fn dotted_strokes_draw_every_dot() { let dots = outline.elements().iter().filter(|e| matches!(e, kurbo::PathEl::MoveTo(_))).count(); assert_eq!(dots, 13); } + +/// The size the image cache budgets for a decode is the size the decode has: a PDF page by the +/// pixels it is rasterized at, not by its size in points. +#[test] +fn decode_size_estimates_match_the_decodes() { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(30, 20, image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let pdf = one_page_pdf("0 0 1 rg 0 0 100 100 re f"); + for bytes in [&png, &pdf] { + let pm = decode_pixmap_page(bytes, 0).unwrap(); + assert_eq!(decode::decoded_bytes(bytes, 0), pm.width() as usize * pm.height() as usize * 16 / 3); + } + assert_eq!(decode::decoded_bytes(b"not an image", 0), 0); + // An EPS drawn from its PostScript is budgeted at no less than it takes. + let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 100 50\n%%EndComments\n0 0 1 setrgbcolor 0 0 100 50 rectfill\n%%EOF\n"; + let pm = decode_pixmap_page(eps, 0).unwrap(); + let drawn = pm.width() as usize * pm.height() as usize * 16 / 3; + assert!(drawn > 200 * 100 * 16 / 3, "drawn above 2 pixels per point: {}×{}", pm.width(), pm.height()); + assert!(decode::decoded_bytes(eps, 0) >= drawn); +} + +#[test] +fn images_in_view_are_decoded_together_before_drawing() { + let mut d = Document::new(&NewDocument::default()); + let lid = d.default_layer(); + // Place a 4×4 PNG of one red value in `r`; returns its encoded bytes. + let place = |d: &mut Document, r: Rect, red: u8, hidden: bool| { + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([red, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let data = Arc::new(png); + let aid = designcraft_doc::AssetId(d.alloc()); + let asset = designcraft_doc::Asset { + id: aid, + name: "red.png".into(), + mime: "image/png".into(), + data: data.clone(), + pixels: Some((4, 4)), + ..Default::default() + }; + d.assets.insert(aid, Arc::new(asset)); + let mut it = Item::new(designcraft_doc::ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(r)); + it.hidden = hidden; + it.content = designcraft_doc::Content::Graphic(designcraft_doc::Graphic { + layer_options: None, + asset: aid, + size: (r.width(), r.height()), + xf: Affine::translate((r.x0, r.y0)), + clip: None, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + wrap: Default::default(), + fill: Default::default(), + }); + d.insert_item(SpreadRef::Doc(0), it, None).unwrap(); + data + }; + let shown: Vec<_> = + (0..3).map(|i| place(&mut d, Rect::new(20.0 + 90.0 * i as f64, 20.0, 100.0 + 90.0 * i as f64, 100.0), 200 + i as u8, false)).collect(); + let hidden = place(&mut d, Rect::new(20.0, 150.0, 100.0, 230.0), 10, true); + let outside = place(&mut d, Rect::new(400.0, 600.0, 500.0, 700.0), 20, false); + // Decodes logged from here on with these buffers' addresses are theirs (they live on). + let since = images::DECODED_ON.lock().unwrap().len(); + let cache = Cache::new(); + let mut r = Renderer::new(); + r.threads = 0; + let placed = [Placed { spread: SpreadRef::Doc(0), xf: Affine::IDENTITY }]; + let img = r.render(&d, &cache, &placed, (300, 300), Affine::IDENTITY, &RenderOptions { background: Some([255; 4]), ..Default::default() }); + for i in 0..3u8 { + assert_eq!(img.pixel(60 + 90 * u32::from(i), 60)[..3], [200 + i, 0, 0], "image {i} drawn"); + } + let me = std::thread::current().id(); + let decoded_on = |data: &Arc>| -> Vec { + let id = Arc::as_ptr(data) as usize; + images::DECODED_ON.lock().unwrap().iter().skip(since).filter(|(a, _)| *a == id).map(|(_, t)| *t).collect() + }; + for (i, data) in shown.iter().enumerate() { + let on = decoded_on(data); + assert_eq!(on.len(), 1, "image {i} decoded once"); + assert_ne!(on[0], me, "image {i} decoded ahead, off the render thread"); + } + assert!(decoded_on(&hidden).is_empty(), "a hidden image is not decoded"); + assert!(decoded_on(&outside).is_empty(), "an image out of view is not decoded"); +} From 2b6fb6fa061d9b954f87a07bc14d83d0c324917b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 11:56:44 -0800 Subject: [PATCH 040/322] Images: count a decode's buffers at their peak before decoding in parallel The gate that limits parallel decodes counted each image at its cached size (4 bytes a pixel and a third more for the smaller levels). A decode holds more than that while it converts the pixels: an 8-bit image keeps its RGBA copy beside the decoded or the premultiplied pixels, 8 bytes a pixel. Two 5,500 pixel square images passed the gate together and could hold more than half the cache budget at once. - decode_sizes returns the cached size and the peak size from one size read. The peak counts the samples as stored beside their converted copy (designcraft_images::decode_bytes_per_pixel): 8 bytes a pixel for 8-bit color, 10 for 16-bit RGB, 12 for 16-bit CMYK TIFFs and 16-bit RGBA, 10 for 8-bit CMYKA TIFFs, 15 for 16-bit CMYKA TIFFs, 9 for PSDs. An EPS counts as its TIFF preview. PDF pages, SVGs and EPS files without a preview count 8. - warm budgets the cache with the cached size and gates decodes with the peak size. - Every warm call in the process shares one gate, so the canvas worker, thumbnails and exports together stay within half the budget while they decode. warm returns the most its own call had decoding. - An EPS without a preview is sized at the larger of its drawn PostScript and its placeholder. The placeholder is clamped to 4000 pixels on each side, so a 10,000 by 4,000 point EPS that is not drawn takes 4000 by 4000 pixels, not the 4000 by 1600 counted before. --- crates/images/src/eps.rs | 2 +- crates/images/src/lib.rs | 33 +++++++++ crates/images/src/tests.rs | 26 ++++++++ crates/render/src/decode.rs | 32 +++++++-- crates/render/src/images.rs | 129 ++++++++++++++++++++++++++++-------- crates/render/src/tests.rs | 8 +++ 6 files changed, 197 insertions(+), 33 deletions(-) diff --git a/crates/images/src/eps.rs b/crates/images/src/eps.rs index bd2498f1a..1f209ccf0 100644 --- a/crates/images/src/eps.rs +++ b/crates/images/src/eps.rs @@ -98,7 +98,7 @@ pub fn eps_size(bytes: &[u8]) -> Option<(f64, f64)> { ((0.001..=20_000.0).contains(&w) && (0.001..=20_000.0).contains(&h)).then_some((w, h)) } -fn preview(bytes: &[u8]) -> Option<(&[u8], (u32, u32))> { +pub(crate) fn preview(bytes: &[u8]) -> Option<(&[u8], (u32, u32))> { let (_, tiff) = sections(bytes); let tiff = tiff?; let (w, h) = crate::pixel_size(tiff)?; diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 081af6c2b..820f9a8b4 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -442,6 +442,39 @@ pub fn decode_rgba(bytes: &[u8]) -> Option { to_display_rgba(px, Some(&icc), &DisplayColour::active()) } +/// About how many bytes a pixel [`decode_rgba`] of `bytes` holds at once, with a premultiplied +/// copy of its result: the samples as stored beside the copy they are converted to, and at least +/// 8 (the RGBA result and its premultiplied copy). 16-bit CMYK TIFF samples are narrowed into an +/// 8-bit copy and CMYK alpha is split off into one, so a 16-bit CMYKA TIFF counts 15. An EPS +/// counts as its TIFF preview, or 8 for its placeholder or drawn PostScript. +pub fn decode_bytes_per_pixel(bytes: &[u8]) -> usize { + if is_eps(bytes) { + return eps::preview(bytes).map_or(8, |(tiff, _)| if is_eps(tiff) { 8 } else { decode_bytes_per_pixel(tiff) }); + } + if is_psd(bytes) { + // RGBA-sized channels, an alpha plane, and the RGBA copy of CMYK inks. + return 9; + } + if let Some(mut d) = tiff_decoder(bytes) { + let cmyk = match d.colortype() { + Ok(tiff::ColorType::CMYK(bits)) => Some((4, bits)), + Ok(tiff::ColorType::CMYKA(bits)) => Some((5, bits)), + _ => None, + }; + if let Some((samples, bits)) = cmyk { + let stored = samples * usize::from(bits).div_ceil(8); + let copy = if bits > 8 || samples == 5 { samples } else { 0 }; + return (stored + copy).max(samples + 4).max(8); + } + } + let sample = image::ImageReader::new(std::io::Cursor::new(bytes)) + .with_guessed_format() + .ok() + .and_then(|r| r.into_decoder().ok()) + .map_or(4, |d| usize::from(image::ImageDecoder::color_type(&d).bytes_per_pixel())); + (sample + 4).max(8) +} + /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than /// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads /// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. diff --git a/crates/images/src/tests.rs b/crates/images/src/tests.rs index cd577f09a..0d8e65ab2 100644 --- a/crates/images/src/tests.rs +++ b/crates/images/src/tests.rs @@ -372,6 +372,32 @@ fn cmyk_tiff_keeps_inks() { assert_eq!(decode_cmyk_tiff(&b[..b.len() / 2]), None, "truncated"); } +/// A decode holds the samples as stored beside the copy they are converted to. +#[test] +fn decode_bytes_per_pixel_counts_the_stored_samples_and_their_copy() { + use tiff::encoder::colortype::{CMYK8, CMYK16, CMYKA8, RGB16}; + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 4], false)), 8); + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 5], true)), 10); + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 4], false)), 12); + assert_eq!(decode_bytes_per_pixel(&tiff_of::(1, 1, &[0; 3], false)), 10); + let mut psd = b"8BPS".to_vec(); + psd.resize(26, 0); + assert_eq!(decode_bytes_per_pixel(&psd), 9); + assert_eq!(decode_bytes_per_pixel(b"not an image"), 8); + // An EPS counts as its TIFF preview, or 8 without one. + let ps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\nnewpath\n%%EOF\n"; + assert_eq!(decode_bytes_per_pixel(ps), 8); + let preview = tiff_of::(1, 1, &[0; 4], false); + let mut dos = vec![0xC5, 0xD0, 0xD3, 0xC6]; + for v in [30, ps.len(), 0, 0, 30 + ps.len(), preview.len()] { + dos.extend((v as u32).to_le_bytes()); + } + dos.extend([0xFF, 0xFF]); + dos.extend_from_slice(ps); + dos.extend_from_slice(&preview); + assert_eq!(decode_bytes_per_pixel(&dos), 12); +} + /// Indexed colour (PhotometricInterpretation 3), which the `tiff` encoder has no type for. struct Palette; impl tiff::encoder::colortype::ColorType for Palette { diff --git a/crates/render/src/decode.rs b/crates/render/src/decode.rs index 5668a205f..dfaed5c55 100644 --- a/crates/render/src/decode.rs +++ b/crates/render/src/decode.rs @@ -12,18 +12,39 @@ const VECTOR_SIDE: u32 = 3000; /// About how many bytes [`decode_pixmap_page`] of `bytes` takes, with its smaller levels (a third /// more): PDF pages and SVGs at [`VECTOR_SIDE`] pixels on the longer side, an EPS without a /// preview at up to 8 pixels per point and 4000 pixels on the longer side (as its PostScript is -/// drawn), other images and previews at their pixel size. 0 when the size can't be read. +/// drawn) or at its placeholder's size when that is larger, other images and previews at their +/// pixel size. 0 when the size can't be read. +#[cfg(test)] pub(crate) fn decoded_bytes(bytes: &[u8], page: u32) -> usize { + decode_sizes(bytes, page).0 +} + +/// [`decoded_bytes`] of `bytes`, and about how many bytes [`decode_pixmap_page`] of it holds at +/// once while it runs: a raster as decoded and its RGBA copy, or that copy and the premultiplied +/// pixels, whichever is more ([`designcraft_images::decode_bytes_per_pixel`]: 8 bytes a pixel +/// for 8-bit color, 12 for 16-bit RGBA, an EPS as its TIFF preview). PDF pages, SVGs and EPS +/// files without a preview count 8 bytes a pixel. Both are 0 when the size can't be read. +pub(crate) fn decode_sizes(bytes: &[u8], page: u32) -> (usize, usize) { + let Some((w, h)) = drawn_size(bytes, page) else { return (0, 0) }; + let raster = !is_pdf(bytes) && !designcraft_images::is_svg(bytes); + let per_pixel = if raster { designcraft_images::decode_bytes_per_pixel(bytes) } else { 8 } as f64; + ((w * h * 16.0 / 3.0) as usize, (w * h * per_pixel) as usize) +} + +/// The pixel size [`decode_pixmap_page`] of `bytes` draws at, as [`decoded_bytes`] describes it. +fn drawn_size(bytes: &[u8], page: u32) -> Option<(f64, f64)> { let drawn = |(w, h): (f64, f64), side: f64, most: f64| { let k = (side / w.max(h).max(1e-3)).min(most); ((w * k).round().max(1.0), (h * k).round().max(1.0)) }; - let size = if designcraft_images::is_eps(bytes) { + if designcraft_images::is_eps(bytes) { image_size(bytes).zip(designcraft_images::eps_size(bytes)).map(|((pw, ph), (w, h))| { - // Without a preview, the pixel size is the 2 pixels per point placeholder's. + // Without a preview, the pixel size is the 2 pixels per point placeholder's. The + // PostScript may be drawn instead, at another size: count the larger of the two. let placeholder = ((w * 2.0).round().clamp(2.0, 4000.0), (h * 2.0).round().clamp(2.0, 4000.0)); let px = (pw as f64, ph as f64); - if px == placeholder { drawn((w, h), 4000.0, 8.0) } else { px } + let rendered = drawn((w, h), 4000.0, 8.0); + if px == placeholder && rendered.0 * rendered.1 > px.0 * px.1 { rendered } else { px } }) } else if is_pdf(bytes) { // As render_pdf_page scales: at most 8 times the page size. @@ -32,8 +53,7 @@ pub(crate) fn decoded_bytes(bytes: &[u8], page: u32) -> usize { designcraft_images::natural_size(bytes).map(|s| drawn(s, VECTOR_SIDE as f64, f64::INFINITY)) } else { image_size(bytes).map(|(w, h)| (w as f64, h as f64)) - }; - size.map_or(0, |(w, h)| (w * h * 16.0 / 3.0) as usize) + } } /// [`decode_pixmap`] for page `page` of a PDF (other formats have one page). diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index ee0d917ba..dca7bcead 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -11,7 +11,7 @@ use std::sync::{Arc, Condvar, Mutex}; use vello_cpu::Pixmap; -use crate::decode::decoded_bytes; +use crate::decode::decode_sizes; use crate::{decode_pixmap_page, halve}; /// Decoded pixels kept (bytes). @@ -190,18 +190,20 @@ fn admits(in_flight: usize, size: usize) -> bool { in_flight == 0 || in_flight.saturating_add(size) <= BUDGET / 2 } -/// Bytes decoding at once and the most there were, with the signal that some finished. -type Gate = (Mutex<(usize, usize)>, Condvar); +/// Bytes [`warm`] is decoding at once in every render in the process (canvas worker, thumbnails, +/// exports), with the signal that some finished. +static GATE: (Mutex, Condvar) = (Mutex::new(0), Condvar::new()); -/// Takes a finished decode's bytes off its [`Gate`] when dropped. -struct Release<'a>(&'a Gate, usize); +/// Takes a finished decode's bytes off [`GATE`] and off its own call's count when dropped. +struct Release<'a>(&'a AtomicUsize, usize); impl Drop for Release<'_> { fn drop(&mut self) { - let mut g = self.0.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); - g.0 = g.0.saturating_sub(self.1); + self.0.fetch_sub(self.1, Ordering::Relaxed); + let mut g = GATE.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + *g = g.saturating_sub(self.1); drop(g); - self.0.1.notify_all(); + GATE.1.notify_all(); } } @@ -210,8 +212,8 @@ impl Drop for Release<'_> { /// of decoding them one after another. Does nothing when fewer than two images need decoding. /// The images in view that are cached count against the cache budget first; a new image that /// would take the total past what the cache keeps (by its pixel size) is left to the render. -/// Decodes wait while those in flight together would take more than half the budget. Returns -/// the most bytes (estimated) that were decoding at once. +/// Decodes wait while those in flight in every render together would take more than half the +/// budget. Returns the most bytes (estimated) this call had decoding at once. pub(crate) fn warm(wants: Vec) -> usize { let workers = workers(); if workers < 2 { @@ -263,7 +265,7 @@ pub(crate) fn warm(wants: Vec) -> usize { if held.contains_key(&key) { continue; } - let size = wanted.first().map_or(0, |w| decoded_bytes(&w.bytes, w.page)); + let (size, decoding) = wanted.first().map_or((0, 0), |w| decode_sizes(&w.bytes, w.page)); // A store past the budget evicts down to three quarters of it: the images in view must // fit in that, unless they and the rest fit in the budget. let total = pixels.saturating_add(size); @@ -271,29 +273,34 @@ pub(crate) fn warm(wants: Vec) -> usize { continue; } pixels = total; - jobs.push((size, wanted)); + jobs.push((decoding, wanted)); } if jobs.len() < 2 { return 0; } - // While it converts the pixels, a decode holds buffers of about its size besides the cache: - // a decode waits while those in flight would take it past half the budget (one always runs). - let gate: Gate = (Mutex::new((0, 0)), Condvar::new()); - let lock = || gate.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + // While it converts the pixels, a decode holds the buffers `decode_sizes` counts: a + // decode waits while those in flight in any render would take it past half the budget (one + // always runs). + let lock = || GATE.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let next = AtomicUsize::new(0); + // This call's bytes decoding, and the most there were. + let (mine, peak) = (AtomicUsize::new(0), AtomicUsize::new(0)); std::thread::scope(|s| { for _ in 0..workers.min(jobs.len()) { let work = || { while let Some((size, job)) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) { let mut g = lock(); - while !admits(g.0, *size) { - g = gate.1.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner); + while !admits(*g, *size) { + #[cfg(test)] + waited(job); + g = GATE.1.wait(g).unwrap_or_else(std::sync::PoisonError::into_inner); } - g.0 += size; - g.1 = g.1.max(g.0); + *g = g.saturating_add(*size); + let now = mine.fetch_add(*size, Ordering::Relaxed).saturating_add(*size); + peak.fetch_max(now, Ordering::Relaxed); drop(g); // Released even if the decode panics, so no other decode waits forever. - let _release = Release(&gate, *size); + let _release = Release(&mine, *size); for w in job { let _ = mip(&w.bytes, w.page, w.width_pt, w.on_screen); } @@ -305,7 +312,19 @@ pub(crate) fn warm(wants: Vec) -> usize { } } }); - gate.0.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner).1 + peak.into_inner() +} + +/// The images whose decode waited at [`GATE`] (the address of the encoded bytes), with the +/// signal that one did. +#[cfg(test)] +static WAITED: (Mutex>, Condvar) = (Mutex::new(Vec::new()), Condvar::new()); + +#[cfg(test)] +fn waited(job: &[Want]) { + let id = job.first().map_or(0, |w| Arc::as_ptr(&w.bytes) as usize); + WAITED.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).push(id); + WAITED.1.notify_all(); } /// Drop every decoded image. @@ -320,6 +339,11 @@ pub fn clear() { #[cfg(test)] mod tests { use super::*; + use crate::decode::decoded_bytes; + + fn decode_peak_bytes(bytes: &[u8], page: u32) -> usize { + decode_sizes(bytes, page).1 + } #[test] fn failed_assets_are_capped_and_oldest_is_dropped() { @@ -403,21 +427,74 @@ mod tests { #[test] fn warm_decodes_large_images_one_at_a_time() { - // Two 7,000 pixel square images fit the budget together, but decoding both at once would + // Two 6,500 pixel square images fit the budget together, but decoding both at once would // take more than half of it; the small image still decodes beside them. - let (d, e, small) = (psd(7000), psd(7000), png(8, 15)); + let (d, e, small) = (psd(6500), psd(6500), png(8, 15)); let since = mark(); let large = decoded_bytes(&d, 0); assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); - assert!(admits(0, large) && !admits(large, large) && admits(large, decoded_bytes(&small, 0))); + let decoding = decode_peak_bytes(&d, 0); + assert!(admits(0, decoding) && !admits(decoding, decoding) && admits(decoding, decode_peak_bytes(&small, 0))); assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); let peak = warm(vec![want(&d), want(&e), want(&small)]); assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); - assert!(peak >= large, "the large images were decoded ahead"); + assert!(peak >= decoding, "the large images were decoded ahead"); let me = std::thread::current().id(); for img in [&d, &e, &small] { let on = decoders(img, since); assert!(on.len() == 1 && on[0] != me); } } + + #[test] + fn warm_counts_a_decode_at_its_peak() { + // A decode holds the RGBA copy beside the decoded or the premultiplied pixels: two 5,500 + // pixel square images would take less than half the budget cached, but more than half of + // it while both decode, so they decode one at a time. + let (f, g) = (psd(5500), psd(5500)); + let decoding = decode_peak_bytes(&f, 0); + assert_eq!(decoding, 5500 * 5500 * 9, "9 bytes a pixel for a PSD"); + assert!(2 * decoded_bytes(&f, 0) <= BUDGET / 2 && !admits(decoding, decode_peak_bytes(&g, 0))); + assert_eq!(warm(vec![want(&f), want(&g)]), decoding, "one decode at a time"); + // 16-bit RGBA decodes at 8 bytes a pixel before its RGBA copy. + let mut deep = Vec::new(); + let img = image::ImageBuffer::, Vec>::from_pixel(4, 4, image::Rgba([9, 0, 0, 65535])); + img.write_to(&mut std::io::Cursor::new(&mut deep), image::ImageFormat::Png).unwrap(); + assert_eq!(decode_peak_bytes(&deep, 0), 16 * 12); + assert_eq!(decode_peak_bytes(&png(8, 1), 0), 64 * 8); + } + + #[test] + fn warm_waits_for_decodes_in_other_renders() { + // Another render's decodes take half the budget: this render's decodes wait for them. + let (a, b) = (png(8, 17), png(8, 19)); + let ids = [Arc::as_ptr(&a) as usize, Arc::as_ptr(&b) as usize]; + let (since, decoded_since) = (WAITED.0.lock().unwrap().len(), mark()); + let other = BUDGET / 2; + *GATE.0.lock().unwrap() += other; + let done = std::sync::atomic::AtomicBool::new(false); + let (waited, peak) = std::thread::scope(|s| { + let render = s.spawn(|| { + let peak = warm(vec![want(&a), want(&b)]); + let w = WAITED.0.lock().unwrap(); + done.store(true, Ordering::SeqCst); + drop(w); + WAITED.1.notify_all(); + peak + }); + let seen = |w: &Vec| w.iter().skip(since).any(|id| ids.contains(id)); + let mut w = WAITED.0.lock().unwrap(); + while !seen(&w) && !done.load(Ordering::SeqCst) { + w = WAITED.1.wait(w).unwrap(); + } + let waited = seen(&w); + drop(w); + *GATE.0.lock().unwrap() -= other; + GATE.1.notify_all(); + (waited, render.join().unwrap()) + }); + assert!(waited, "decoded beside the other render's decodes"); + assert_eq!((decoders(&a, decoded_since).len(), decoders(&b, decoded_since).len()), (1, 1)); + assert!(peak > 0 && peak <= BUDGET / 2, "{peak} bytes decoding at once"); + } } diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 5d4f6a048..82e8fc77f 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -792,6 +792,14 @@ fn decode_size_estimates_match_the_decodes() { let drawn = pm.width() as usize * pm.height() as usize * 16 / 3; assert!(drawn > 200 * 100 * 16 / 3, "drawn above 2 pixels per point: {}×{}", pm.width(), pm.height()); assert!(decode::decoded_bytes(eps, 0) >= drawn); + // A wide EPS whose PostScript isn't drawn keeps its placeholder, clamped to 4000 pixels on + // each side: it is budgeted at no less than that. + let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10000 4000\n%%EndComments\n0 0 moveto 10 10 lineto stroke\n%%EOF\n"; + let pm = decode_pixmap_page(eps, 0).unwrap(); + assert_eq!((pm.width(), pm.height()), (4000, 4000)); + let px = pm.width() as usize * pm.height() as usize; + assert!(decode::decoded_bytes(eps, 0) >= px * 16 / 3); + assert!(decode::decode_sizes(eps, 0).1 >= px * 8); } #[test] From 2794a60bf079b15f7285101f3fcce423d0876af4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:21:20 -0500 Subject: [PATCH 041/322] Account for image decode buffers in warm gate --- crates/render/src/images.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index f9f82ac31..8ae0691c7 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -250,9 +250,9 @@ pub(crate) fn warm(wants: Vec) -> usize { *held.entry((k.0, k.1)).or_default() += size_of(&e.pm); } } - let in_view = held.values().sum::(); // Smaller levels alone don't make an asset cached. held.retain(|k, _| c.map.contains_key(&(k.0, k.1, 0))); + let in_view = held.values().sum::(); for k in index.keys() { if c.bad.contains_key(k) { held.entry(*k).or_default(); @@ -278,7 +278,9 @@ pub(crate) fn warm(wants: Vec) -> usize { continue; } pixels = total; - jobs.push((decoding, wanted)); + // The estimate covers the decoded image and its converted pixels; leave headroom for + // temporary buffers inside individual format decoders. + jobs.push((decoding.saturating_mul(3) / 2, wanted)); } if jobs.len() < 2 { return 0; From 33f0c21510bb765dcfc3fd2a6d87c17af3ddb9d4 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:40:51 -0500 Subject: [PATCH 042/322] Estimate reduced JPEG cache and decode sizes --- crates/render/src/images.rs | 83 ++++++++++++++++++++++++++++++------- 1 file changed, 68 insertions(+), 15 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 8ae0691c7..fd937903d 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -172,6 +172,54 @@ pub(crate) struct Want { pub on_screen: f64, } +/// Dimensions of the JPEG mip level selected for a request. `None` means the request uses the +/// full decode or is not an eligible JPEG, so warming must reserve its full decode size. +fn reduced_sizes(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Option> { + if page != 0 || !bytes.starts_with(&[0xFF, 0xD8]) { + return None; + } + let (mut w, mut h) = crate::image_size(bytes)?; + let ppt = w as f64 / width_pt.max(1e-6); + let mut sizes = vec![(w, h)]; + while ppt / (1u64 << sizes.len()) as f64 >= on_screen * 1.2 && w > 64 && h > 64 && sizes.len() <= 8 { + (w, h) = ((w / 2).max(1), (h / 2).max(1)); + sizes.push((w, h)); + } + Some(sizes) +} + +/// Cache and peak decode estimates for a group of requests that all use reduced JPEG mips. +fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { + let mut dims = None; + let mut levels = [false; 9]; + let mut peak = 0usize; + for w in wants { + let sizes = reduced_sizes(&w.bytes, w.page, w.width_pt, w.on_screen)?; + let level = sizes.len() - 1; + if level == 0 { + return None; + } + let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); + for cached in shrink..=level { + levels[cached] = true; + } + let denom = 1u32 << shrink; + let (w_px, h_px) = sizes[0]; + // The reduced decoder rounds each side up before the mip is cropped to `sizes[shrink]`. + let decode_pixels = w_px.div_ceil(denom) as usize * h_px.div_ceil(denom) as usize; + peak = peak.max(decode_pixels.saturating_mul(8)); + if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { + dims = Some(sizes); + } + } + let dims = dims?; + let cached = levels.iter().enumerate().filter(|(_, keep)| **keep).fold(0usize, |n, (level, _)| { + let (w, h) = dims[level]; + n.saturating_add(w as usize * h as usize * 4) + }); + Some((cached, peak)) +} + /// Threads [`warm`] decodes on (1 on the web, which has none). fn workers() -> usize { #[cfg(target_arch = "wasm32")] @@ -270,7 +318,8 @@ pub(crate) fn warm(wants: Vec) -> usize { if held.contains_key(&key) { continue; } - let (size, decoding) = wanted.first().map_or((0, 0), |w| decode_sizes(&w.bytes, w.page)); + let full = wanted.first().map_or((0, 0), |w| decode_sizes(&w.bytes, w.page)); + let (size, decoding) = reduced_estimates(&wanted).unwrap_or(full); // A store past the budget evicts down to three quarters of it: the images in view must // fit in that, unless they and the rest fit in the budget. let total = pixels.saturating_add(size); @@ -338,21 +387,12 @@ fn waited(job: &[Want]) { /// and halved from there, so a screen-sized level needs no full-size decode. `None` when the /// full size is drawn, for other formats and for JPEGs only a full decode reads (CMYK). fn reduced(bytes: &Arc>, page: u32, width_pt: f64, on_screen: f64) -> Option> { - if page != 0 || !bytes.starts_with(&[0xFF, 0xD8]) { - return None; - } let id = Arc::as_ptr(bytes) as usize; if with(|c| c.bad.contains_key(&(id, page))) { return None; } // The level `mip` picks from a full decode, with each level's size as `halve` gives it. - let (mut w, mut h) = crate::image_size(bytes)?; - let ppt = w as f64 / width_pt.max(1e-6); - let mut sizes = vec![(w, h)]; - while ppt / (1u64 << sizes.len()) as f64 >= on_screen * 1.2 && w > 64 && h > 64 && sizes.len() <= 8 { - (w, h) = ((w / 2).max(1), (h / 2).max(1)); - sizes.push((w, h)); - } + let sizes = reduced_sizes(bytes, page, width_pt, on_screen)?; let level = u8::try_from(sizes.len() - 1).ok()?; if level == 0 { return None; @@ -506,10 +546,11 @@ mod tests { let large = decoded_bytes(&d, 0); assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); let decoding = decode_peak_bytes(&d, 0); - assert!(admits(0, decoding) && !admits(decoding, decoding) && admits(decoding, decode_peak_bytes(&small, 0))); + let reserved = decoding * 3 / 2; + assert!(admits(0, reserved) && !admits(reserved, reserved) && admits(reserved, decode_peak_bytes(&small, 0) * 3 / 2)); assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); let peak = warm(vec![want(&d), want(&e), want(&small)]); - assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); + assert!(peak <= decoding * 3 / 2, "{peak} bytes decoding at once"); assert!(peak >= decoding, "the large images were decoded ahead"); let me = std::thread::current().id(); for img in [&d, &e, &small] { @@ -526,8 +567,9 @@ mod tests { let (f, g) = (psd(5500), psd(5500)); let decoding = decode_peak_bytes(&f, 0); assert_eq!(decoding, 5500 * 5500 * 9, "9 bytes a pixel for a PSD"); - assert!(2 * decoded_bytes(&f, 0) <= BUDGET / 2 && !admits(decoding, decode_peak_bytes(&g, 0))); - assert_eq!(warm(vec![want(&f), want(&g)]), decoding, "one decode at a time"); + let reserved = decoding * 3 / 2; + assert!(2 * decoded_bytes(&f, 0) <= BUDGET / 2 && !admits(reserved, decode_peak_bytes(&g, 0) * 3 / 2)); + assert_eq!(warm(vec![want(&f), want(&g)]), reserved, "one decode at a time"); // 16-bit RGBA decodes at 8 bytes a pixel before its RGBA copy. let mut deep = Vec::new(); let img = image::ImageBuffer::, Vec>::from_pixel(4, 4, image::Rgba([9, 0, 0, 65535])); @@ -601,6 +643,17 @@ mod tests { assert_eq!((full.width(), full.height()), (1024, 768)); } + #[test] + fn warm_estimates_a_jpegs_reduced_levels() { + let bytes = jpeg(1024, 768); + let want = Want { bytes: bytes.clone(), page: 0, width_pt: 1024.0, on_screen: 0.1 }; + let (cached, peak) = reduced_estimates(&[want]).unwrap(); + assert_eq!(cached, 128 * 96 * 4, "only the selected eighth-size mip is cached"); + assert_eq!(peak, 128 * 96 * 8, "only the selected eighth-size mip is decoded"); + let full = decode_sizes(&bytes, 0); + assert!(cached < full.0 && peak < full.1, "reduced estimates {cached}/{peak}, full {full:?}"); + } + #[test] fn reduced_levels_of_odd_sized_jpegs_have_the_halved_size() { let bytes = jpeg(1001, 771); From 764b06526bc4d4ff5f1ddb27d1478c3beb9729d1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:41:55 -0500 Subject: [PATCH 043/322] Estimate reduced JPEG warm reservations --- crates/images/src/jpeg.rs | 30 ++++++++++++++++++++++++++++++ crates/images/src/lib.rs | 6 ++++++ crates/render/src/images.rs | 7 ++----- 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index a4a2a0971..8e504d72c 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -65,6 +65,36 @@ pub(crate) fn decode_cmyk(bytes: &[u8]) -> Option<(CmykRaster, Option>)> /// The largest reduction [`decode_reduced`] reads straight from a JPEG's 8×8 blocks: 1/8. pub(crate) const MAX_SHRINK: u8 = 3; +/// Output size of a JPEG reduction without decoding pixels. `None` when the reduced decoder +/// cannot handle the JPEG, including its full-size resource limits. +pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { + use jpeg_decoder::{CodingProcess, PixelFormat}; + if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { + return None; + } + let mut d = jpeg_decoder::Decoder::new(bytes); + d.set_max_decoding_buffer_size(MAX_BYTES); + d.read_info().ok()?; + let info = d.info()?; + let colour = match info.pixel_format { + PixelFormat::RGB24 => true, + PixelFormat::L8 => false, + PixelFormat::L16 | PixelFormat::CMYK32 => return None, + }; + if crate::over_rgba_budget(u32::from(info.width), u32::from(info.height)) { + return None; + } + if info.coding_process == CodingProcess::DctProgressive { + let side = |n: u16| u64::from(n).next_multiple_of(32); + let components: u64 = if colour { 3 } else { 1 }; + if side(info.width) * side(info.height) * components * 2 > MAX_BYTES as u64 { + return None; + } + } + let reduced = |n: u16| u32::from(n).div_ceil(1 << shrink); + Some((reduced(info.width), reduced(info.height))) +} + /// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for /// `shrink` 1 to [`MAX_SHRINK`]: straight RGBA and whether the image has colour. `None` for CMYK, /// 12-bit and lossless JPEGs, other formats and anything that doesn't decode. `None` as well for a diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index e925de471..07f91a467 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -510,6 +510,12 @@ pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option to_display_rgba(px, Some(&icc), &DisplayColour::active()) } +/// Dimensions of a JPEG decoded at `1/2^shrink`, without decoding its pixels. `None` when the +/// reduced decoder cannot handle the image. +pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { + jpeg::reduced_size(bytes, shrink) +} + /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than /// [`colour::MAX_ICC_BYTES`]. The decoder sizes its buffer from the declared length before it reads /// anything, so such a file must not reach `icc_profile()`; its pixels decode without it. diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index fd937903d..4df71f42b 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -200,14 +200,11 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { return None; } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); + let (decoded_w, decoded_h) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; for cached in shrink..=level { levels[cached] = true; } - let denom = 1u32 << shrink; - let (w_px, h_px) = sizes[0]; - // The reduced decoder rounds each side up before the mip is cropped to `sizes[shrink]`. - let decode_pixels = w_px.div_ceil(denom) as usize * h_px.div_ceil(denom) as usize; - peak = peak.max(decode_pixels.saturating_mul(8)); + peak = peak.max(decoded_w as usize * decoded_h as usize * 8); if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { dims = Some(sizes); } From 067fc9712842f50779f3069aa3ff901f9b3a2acd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:45:02 -0500 Subject: [PATCH 044/322] Use iterator for reduced mip accounting --- crates/render/src/images.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 4df71f42b..e2d49873c 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -201,8 +201,8 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); let (decoded_w, decoded_h) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; - for cached in shrink..=level { - levels[cached] = true; + for cached in levels.iter_mut().take(level + 1).skip(shrink) { + *cached = true; } peak = peak.max(decoded_w as usize * decoded_h as usize * 8); if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { From 1c3285d8a3affaec03949c7fa2b610c4b94dcc34 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:55:11 -0500 Subject: [PATCH 045/322] Count progressive JPEG buffers in warm budget --- crates/images/src/jpeg.rs | 16 +++++++++++----- crates/images/src/lib.rs | 7 ++++--- crates/render/src/images.rs | 4 ++-- 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index 8e504d72c..9db1709cc 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -67,7 +67,7 @@ pub(crate) const MAX_SHRINK: u8 = 3; /// Output size of a JPEG reduction without decoding pixels. `None` when the reduced decoder /// cannot handle the JPEG, including its full-size resource limits. -pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { +pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { use jpeg_decoder::{CodingProcess, PixelFormat}; if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { return None; @@ -84,15 +84,21 @@ pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { if crate::over_rgba_budget(u32::from(info.width), u32::from(info.height)) { return None; } - if info.coding_process == CodingProcess::DctProgressive { + let progressive_bytes = if info.coding_process == CodingProcess::DctProgressive { let side = |n: u16| u64::from(n).next_multiple_of(32); let components: u64 = if colour { 3 } else { 1 }; - if side(info.width) * side(info.height) * components * 2 > MAX_BYTES as u64 { + let bytes = side(info.width) * side(info.height) * components * 2; + if bytes > MAX_BYTES as u64 { return None; } - } + usize::try_from(bytes).ok()? + } else { + 0 + }; let reduced = |n: u16| u32::from(n).div_ceil(1 << shrink); - Some((reduced(info.width), reduced(info.height))) + let (width, height) = (reduced(info.width), reduced(info.height)); + let output_bytes = width as usize * height as usize * 8; + Some((width, height, progressive_bytes.saturating_add(output_bytes))) } /// A YCbCr, RGB or grayscale JPEG decoded at 1/2^`shrink` of its size, each side rounded up, for diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 07f91a467..9afb009fa 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -510,9 +510,10 @@ pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option to_display_rgba(px, Some(&icc), &DisplayColour::active()) } -/// Dimensions of a JPEG decoded at `1/2^shrink`, without decoding its pixels. `None` when the -/// reduced decoder cannot handle the image. -pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32)> { +/// Dimensions and estimated peak bytes for a JPEG decoded at `1/2^shrink`, without decoding its +/// pixels. Progressive JPEG coefficient buffers are included. `None` when the reduced decoder +/// cannot handle the image. +pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { jpeg::reduced_size(bytes, shrink) } diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index e2d49873c..8e57ef448 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -200,11 +200,11 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { return None; } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); - let (decoded_w, decoded_h) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; + let (_, _, decode_peak) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; for cached in levels.iter_mut().take(level + 1).skip(shrink) { *cached = true; } - peak = peak.max(decoded_w as usize * decoded_h as usize * 8); + peak = peak.max(decode_peak); if dims.as_ref().is_none_or(|d: &Vec<(u32, u32)>| d.len() < sizes.len()) { dims = Some(sizes); } From 2eff7e822f799bb740d0bc0447a0c7cdead1c679 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 12 Nov 2026 17:55:36 -0500 Subject: [PATCH 046/322] Name reduced JPEG estimate API --- crates/images/src/jpeg.rs | 2 +- crates/images/src/lib.rs | 4 ++-- crates/render/src/images.rs | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/images/src/jpeg.rs b/crates/images/src/jpeg.rs index 9db1709cc..b6ef06c09 100644 --- a/crates/images/src/jpeg.rs +++ b/crates/images/src/jpeg.rs @@ -67,7 +67,7 @@ pub(crate) const MAX_SHRINK: u8 = 3; /// Output size of a JPEG reduction without decoding pixels. `None` when the reduced decoder /// cannot handle the JPEG, including its full-size resource limits. -pub(crate) fn reduced_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { +pub(crate) fn reduced_estimate(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { use jpeg_decoder::{CodingProcess, PixelFormat}; if !bytes.starts_with(&[0xFF, 0xD8]) || shrink == 0 || shrink > MAX_SHRINK { return None; diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index 9afb009fa..334a62ed9 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -513,8 +513,8 @@ pub fn decode_rgba_reduced(bytes: &[u8], shrink: u8) -> Option /// Dimensions and estimated peak bytes for a JPEG decoded at `1/2^shrink`, without decoding its /// pixels. Progressive JPEG coefficient buffers are included. `None` when the reduced decoder /// cannot handle the image. -pub fn reduced_jpeg_size(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { - jpeg::reduced_size(bytes, shrink) +pub fn reduced_jpeg_estimate(bytes: &[u8], shrink: u8) -> Option<(u32, u32, usize)> { + jpeg::reduced_estimate(bytes, shrink) } /// False when `bytes` is a WebP whose `ICCP` chunk declares more bytes than the file holds or than diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 8e57ef448..01746f19e 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -200,7 +200,7 @@ fn reduced_estimates(wants: &[Want]) -> Option<(usize, usize)> { return None; } let shrink = level.min(usize::from(designcraft_images::MAX_REDUCED_SHRINK)); - let (_, _, decode_peak) = designcraft_images::reduced_jpeg_size(&w.bytes, shrink as u8)?; + let (_, _, decode_peak) = designcraft_images::reduced_jpeg_estimate(&w.bytes, shrink as u8)?; for cached in levels.iter_mut().take(level + 1).skip(shrink) { *cached = true; } From 28d85282834b2861973b2b439e1d9cc639eabfd1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 15:23:04 -0800 Subject: [PATCH 047/322] Images: fit the one-at-a-time warm test to the decode headroom With the 3/2 headroom on each decode, a 6,500 pixel square PSD reserves more than half the budget, so the small image can no longer decode beside it and the test failed before calling warm. 5,000 pixel square images still reserve more than half the budget as a pair and leave room for the small image beside one. --- crates/render/src/images.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/render/src/images.rs b/crates/render/src/images.rs index 01746f19e..16890b591 100644 --- a/crates/render/src/images.rs +++ b/crates/render/src/images.rs @@ -536,19 +536,19 @@ mod tests { #[test] fn warm_decodes_large_images_one_at_a_time() { - // Two 6,500 pixel square images fit the budget together, but decoding both at once would - // take more than half of it; the small image still decodes beside them. - let (d, e, small) = (psd(6500), psd(6500), png(8, 15)); + // Two 5,000 pixel square images take less than half the budget cached, but decoding both + // at once would reserve more than half of it; the small image still decodes beside one. + let (d, e, small) = (psd(5000), psd(5000), png(8, 15)); let since = mark(); let large = decoded_bytes(&d, 0); - assert!(large > BUDGET / 4 && 2 * large <= BUDGET * 3 / 4); + assert!(2 * large <= BUDGET / 2); let decoding = decode_peak_bytes(&d, 0); let reserved = decoding * 3 / 2; assert!(admits(0, reserved) && !admits(reserved, reserved) && admits(reserved, decode_peak_bytes(&small, 0) * 3 / 2)); assert!(admits(0, usize::MAX), "an image over half the budget still decodes alone"); let peak = warm(vec![want(&d), want(&e), want(&small)]); - assert!(peak <= decoding * 3 / 2, "{peak} bytes decoding at once"); - assert!(peak >= decoding, "the large images were decoded ahead"); + assert!(peak <= BUDGET / 2, "{peak} bytes decoding at once"); + assert!(peak >= reserved, "the large images were decoded ahead"); let me = std::thread::current().id(); for img in [&d, &e, &small] { let on = decoders(img, since); From dbb334c529d76e4f3d22afaa86c0a8b10f3a0216 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 12 Nov 2026 15:27:11 -0800 Subject: [PATCH 048/322] Images: pick the images to decode ahead with the scaled stroke and effect bounds The draw path scales an item's stroke extent and effect outset by its transform before culling; the pass that picks images to decode ahead used the unscaled values, so a scaled image whose stroke or shadow reaches the view decoded on the render thread. --- crates/render/src/draw.rs | 7 +++++-- crates/render/src/tests.rs | 9 +++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index 91a492b2e..95e0a159c 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -99,8 +99,11 @@ fn wanted_in(f: &Frame, it: &Item, parent: Affine, depth: usize, out: &mut Vec