From 4e0e3949f1eb91c874f2a47d58c2187031f4c97e Mon Sep 17 00:00:00 2001 From: Brandon Thomas Date: Fri, 9 Oct 2026 21:02:05 -0400 Subject: [PATCH 01/24] Bump version to 0.5.0 (from 0.4.0) for release; refresh contributors Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 40 +++---- Cargo.toml | 2 +- contributors/contributors.json | 187 +++++++++++++++++++++++++++------ 3 files changed, 173 insertions(+), 56 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 671341623..cfc7d3517 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -855,7 +855,7 @@ dependencies = [ [[package]] name = "designcraft" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-engine", "designcraft-ui-egui", @@ -871,7 +871,7 @@ dependencies = [ [[package]] name = "designcraft-cli" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -887,7 +887,7 @@ dependencies = [ [[package]] name = "designcraft-color" -version = "0.4.0" +version = "0.5.0" dependencies = [ "kurbo", "moxcms", @@ -899,7 +899,7 @@ dependencies = [ [[package]] name = "designcraft-compose" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -915,7 +915,7 @@ dependencies = [ [[package]] name = "designcraft-doc" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-geom", @@ -927,7 +927,7 @@ dependencies = [ [[package]] name = "designcraft-engine" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -957,7 +957,7 @@ dependencies = [ [[package]] name = "designcraft-epub" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -966,7 +966,7 @@ dependencies = [ [[package]] name = "designcraft-fonts" -version = "0.4.0" +version = "0.5.0" dependencies = [ "harfrust 0.13.3", "kurbo", @@ -978,7 +978,7 @@ dependencies = [ [[package]] name = "designcraft-format" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-doc", "serde", @@ -989,7 +989,7 @@ dependencies = [ [[package]] name = "designcraft-geom" -version = "0.4.0" +version = "0.5.0" dependencies = [ "flo_curves", "kurbo", @@ -1002,7 +1002,7 @@ dependencies = [ [[package]] name = "designcraft-idml" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-doc", @@ -1014,7 +1014,7 @@ dependencies = [ [[package]] name = "designcraft-images" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-fonts", @@ -1025,7 +1025,7 @@ dependencies = [ [[package]] name = "designcraft-mcp" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-engine", "designcraft-geom", @@ -1038,7 +1038,7 @@ dependencies = [ [[package]] name = "designcraft-pdf" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1060,7 +1060,7 @@ dependencies = [ [[package]] name = "designcraft-render" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1078,7 +1078,7 @@ dependencies = [ [[package]] name = "designcraft-textimport" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-doc", "quick-xml 0.38.4", @@ -1087,7 +1087,7 @@ dependencies = [ [[package]] name = "designcraft-tools" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1099,7 +1099,7 @@ dependencies = [ [[package]] name = "designcraft-ui-egui" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-color", "designcraft-compose", @@ -1123,7 +1123,7 @@ dependencies = [ [[package]] name = "designcraft-web" -version = "0.4.0" +version = "0.5.0" dependencies = [ "designcraft-engine", "designcraft-ui-egui", @@ -5562,7 +5562,7 @@ checksum = "9440ea3e5aeabb0ac63af70daf835274065238cdd0cec83418f417eae38bacee" [[package]] name = "xtask" -version = "0.4.0" +version = "0.5.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index c59188532..af62549eb 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.4.0" +version = "0.5.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.90" diff --git a/contributors/contributors.json b/contributors/contributors.json index c21fcc6eb..cf12c54c2 100644 --- a/contributors/contributors.json +++ b/contributors/contributors.json @@ -2,49 +2,49 @@ "schema": 1, "repo": "storytold/designcraft", "branch": "main", - "head": "f17397c305ecda9d644105f7a4e9b9d65d34bb60", - "head_date": "2026-10-07T18:55:09Z", - "commits": 294, + "head": "66c7ce7e96ec286a091878cc2541ee8369aa79d6", + "head_date": "2026-10-08T13:12:32Z", + "commits": 350, "unattributed_commits": 0, "contributors": [ { "login": "echelon", "people_entry": true, "github_name": null, - "prs": 22, - "commits": 260, - "lines_added": 99427, - "lines_deleted": 6061, + "prs": 25, + "commits": 270, + "lines_added": 100858, + "lines_deleted": 6338, "binary_added": 42, "binary_deleted": 2, "first_commit": "2026-10-01T13:00:02Z", - "last_commit": "2026-10-07T18:55:09Z" + "last_commit": "2026-10-08T13:50:30Z" }, { "login": "storybored379", "people_entry": false, "github_name": null, - "prs": 4, - "commits": 4, - "lines_added": 150, - "lines_deleted": 11, + "prs": 5, + "commits": 5, + "lines_added": 181, + "lines_deleted": 14, "binary_added": 0, "binary_deleted": 0, "first_commit": "2026-10-03T16:31:40Z", - "last_commit": "2026-10-05T03:53:26Z" + "last_commit": "2026-10-06T07:03:03Z" }, { "login": "CameronGilroy", "people_entry": false, "github_name": null, - "prs": 1, - "commits": 18, - "lines_added": 5236, - "lines_deleted": 381, + "prs": 2, + "commits": 23, + "lines_added": 8982, + "lines_deleted": 609, "binary_added": 0, "binary_deleted": 0, "first_commit": "2026-10-05T06:15:59Z", - "last_commit": "2026-10-05T18:56:22Z" + "last_commit": "2026-10-07T10:22:06Z" }, { "login": "midasdf", @@ -63,14 +63,14 @@ "login": "ShaoWenbinSaleh", "people_entry": false, "github_name": null, - "prs": 1, - "commits": 2, - "lines_added": 6020, - "lines_deleted": 1278, + "prs": 3, + "commits": 10, + "lines_added": 10282, + "lines_deleted": 2843, "binary_added": 0, "binary_deleted": 0, "first_commit": "2026-10-05T19:15:57Z", - "last_commit": "2026-10-06T14:32:13Z" + "last_commit": "2026-10-07T11:47:38Z" }, { "login": "japbcoelho", @@ -84,6 +84,123 @@ "binary_deleted": 0, "first_commit": "2026-10-06T01:43:44Z", "last_commit": "2026-10-06T01:45:41Z" + }, + { + "login": "aiongg", + "people_entry": false, + "github_name": null, + "prs": 3, + "commits": 19, + "lines_added": 5933, + "lines_deleted": 735, + "binary_added": 0, + "binary_deleted": 0, + "first_commit": "2026-10-06T15:11:56Z", + "last_commit": "2026-10-07T13:18:17Z" + }, + { + "login": "epfabian", + "people_entry": false, + "github_name": null, + "prs": 1, + "commits": 1, + "lines_added": 50, + "lines_deleted": 4, + "binary_added": 0, + "binary_deleted": 0, + "first_commit": "2026-10-06T18:31:52Z", + "last_commit": "2026-10-06T18:31:52Z" + }, + { + "login": "EthanSuquet", + "people_entry": false, + "github_name": null, + "prs": 2, + "commits": 2, + "lines_added": 689, + "lines_deleted": 5, + "binary_added": 0, + "binary_deleted": 0, + "first_commit": "2026-10-06T19:15:09Z", + "last_commit": "2026-10-06T20:13:06Z" + }, + { + "login": "Luskish", + "people_entry": false, + "github_name": null, + "prs": 1, + "commits": 1, + "lines_added": 259, + "lines_deleted": 32, + "binary_added": 0, + "binary_deleted": 0, + "first_commit": "2026-10-07T02:49:05Z", + "last_commit": "2026-10-07T02:49:05Z" + }, + { + "login": "denizkoekden", + "people_entry": false, + "github_name": null, + "prs": 1, + "commits": 1, + "lines_added": 7, + "lines_deleted": 0, + "binary_added": 0, + "binary_deleted": 0, + "first_commit": "2026-10-07T19:23:57Z", + "last_commit": "2026-10-07T19:23:57Z" + }, + { + "login": "skylartaylor", + "people_entry": false, + "github_name": null, + "prs": 4, + "commits": 4, + "lines_added": 528, + "lines_deleted": 28, + "binary_added": 0, + "binary_deleted": 0, + "first_commit": "2026-10-07T20:27:50Z", + "last_commit": "2026-10-07T22:10:32Z" + }, + { + "login": "RicSchonfelder", + "people_entry": false, + "github_name": null, + "prs": 1, + "commits": 1, + "lines_added": 1059, + "lines_deleted": 4, + "binary_added": 0, + "binary_deleted": 0, + "first_commit": "2026-10-07T20:43:34Z", + "last_commit": "2026-10-07T20:43:34Z" + }, + { + "login": "h-a-n-a-s-h-i", + "people_entry": false, + "github_name": null, + "prs": 0, + "commits": 2, + "lines_added": 42, + "lines_deleted": 42, + "binary_added": 0, + "binary_deleted": 0, + "first_commit": "2026-10-08T12:13:12Z", + "last_commit": "2026-10-08T14:02:08Z" + }, + { + "login": "XusBadia", + "people_entry": false, + "github_name": null, + "prs": 1, + "commits": 1, + "lines_added": 241, + "lines_deleted": 1, + "binary_added": 2, + "binary_deleted": 0, + "first_commit": "2026-10-08T13:12:32Z", + "last_commit": "2026-10-08T13:12:32Z" } ], "models": [ @@ -92,9 +209,18 @@ "company": "Anthropic", "model": "Claude Opus", "version": "5.5", - "commits": 266, - "lines_added": 83821, - "lines_deleted": 6091 + "commits": 282, + "lines_added": 86274, + "lines_deleted": 6420 + }, + { + "id": "openai/codex", + "company": "OpenAI", + "model": "Codex", + "version": "", + "commits": 2, + "lines_added": 57, + "lines_deleted": 8 }, { "id": "anthropic/claude-opus/4.8", @@ -104,15 +230,6 @@ "commits": 1, "lines_added": 1633, "lines_deleted": 3 - }, - { - "id": "openai/codex", - "company": "OpenAI", - "model": "Codex", - "version": "", - "commits": 1, - "lines_added": 26, - "lines_deleted": 5 } ] } From aeabc82ca64f7398d8e9d2ee5b724769954c8f12 Mon Sep 17 00:00:00 2001 From: jahala Date: Sat, 10 Oct 2026 06:09:30 +0100 Subject: [PATCH 02/24] Images: PSD decode passes clippy on Rust 1.98 (#136) Rust 1.98 adds the clippy lint chunks_exact_to_as_chunks. It flags two loops in the PSD decoder, so `cargo xtask ci` stops at the clippy step on unmodified main for anyone on current stable. Both loops now use as_chunks / as_chunks_mut (stable since 1.88, below the workspace rust-version 1.90). The chunks are arrays, so the try_from that could never fail goes away too. Decoded pixels are unchanged; the existing PSD tests cover both paths. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/images/src/psd.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/images/src/psd.rs b/crates/images/src/psd.rs index 7da9e3ac4..182005274 100644 --- a/crates/images/src/psd.rs +++ b/crates/images/src/psd.rs @@ -144,8 +144,7 @@ pub(crate) fn decode(bytes: &[u8]) -> Option { let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; let byte = |v: f32| v.round().clamp(0.0, 255.0) as u8; let white = mode.white(); - for (i, px) in rgba.chunks_exact_mut(4).enumerate() { - let Ok(px) = <&mut [u8; 4]>::try_from(px) else { continue }; + for (i, px) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { let a = alpha.get(i).copied().unwrap_or(255); let mut v = px.map(f32::from); // The composite is matted against white where it's partly transparent: un-matte it. @@ -314,7 +313,7 @@ fn fill(dst: &mut [u8], slot: usize, step: usize, src: &[u8], depth: u16) { match depth { 1 => dst.zip(src.iter().flat_map(|&b| (0..8).rev().map(move |i| if (b >> i) & 1 == 1 { 0 } else { 255 }))).for_each(|(d, s)| *d = s), 16 => dst - .zip(src.chunks_exact(2).map(|c| c.iter().fold(0u32, |n, &b| n << 8 | u32::from(b)))) + .zip(src.as_chunks::<2>().0.iter().map(|c| c.iter().fold(0u32, |n, &b| n << 8 | u32::from(b)))) .for_each(|(d, s)| *d = ((s * 255 + 32_767) / 65_535) as u8), _ => dst.zip(src).for_each(|(d, &s)| *d = s), } From 07b95eb7b394f24ce96da62de6775f84bbf44d2c Mon Sep 17 00:00:00 2001 From: Haseom Shin Date: Sat, 10 Oct 2026 14:09:36 +0900 Subject: [PATCH 03/24] Compose: don't panic when a hyphenated paragraph starts with a no-break letter (#115) --- crates/compose/src/lib.rs | 5 +++++ crates/compose/src/tests.rs | 12 ++++++++++++ 2 files changed, 17 insertions(+) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5a3056d8f..3db5070d5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -2080,6 +2080,11 @@ fn hyphenation_points(text: &str, glyphs: &[Glyph], pp: &ParaProps, exceptions: while j < glyphs.len() && (glyphs[j].is_letter() || glyphs[j].len == 0 || glyphs[j].ch == shape::SOFT_HYPHEN) && !glyphs[j].no_break { j += 1; } + // A no-break letter can't start a hyphenatable word. + if j == i { + i += 1; + continue; + } // A discretionary hyphen in a word (or right before it) replaces automatic hyphenation. let discretionary = glyphs[i..j].iter().any(|g| g.ch == shape::SOFT_HYPHEN) || (i > 0 && glyphs[i - 1].ch == shape::SOFT_HYPHEN); let (a, b) = (glyphs[i].byte, glyphs[j - 1].byte + glyphs[j - 1].len); diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs index 549e7bccf..256d9a13c 100644 --- a/crates/compose/src/tests.rs +++ b/crates/compose/src/tests.rs @@ -313,6 +313,18 @@ fn discretionary_hyphen_replaces_automatic_points() { assert!(lines.iter().filter(|l| l.hyphenated).count() <= 1); } +#[test] +fn hyphenation_skips_a_no_break_word_at_the_start() { + // Used to index before the first glyph and panic. + let text = "Extraordinarily long words wrap in a narrow column"; + let (mut d, sid, _) = doc_with(text, Rect::new(0.0, 0.0, 60.0, 1000.0), ParaAttrs::default()); + d.story_mut(sid).unwrap().format_chars(0..15, |f| f.over.no_break = Some(true)); + let cs = compose_story(&d, sid, &ComposeOptions::default()); + // The no-break word stays whole on the first line. + let first = all_lines(&cs)[0]; + assert!(!first.hyphenated && first.range.end >= 15, "{:?}", &text[first.range.clone()]); +} + /// Story of `n` one-line filler paragraphs followed by `extra` paragraphs, in a 2-column frame. fn keep_doc(fillers: usize, extra: &[&str], height: f64) -> (Document, StoryId, Vec) { let mut parts: Vec = (0..fillers).map(|k| format!("Filler {k}")).collect(); From 9fbd6d24025597b09d9c872a29e90c9aa4e76ca8 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:09:41 -0400 Subject: [PATCH 04/24] Show an alert when a file can't be opened or placed (#80) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Opening an InDesign document says to export IDML (#21) .indd and .indt files (recognised by their published 16-byte signature) failed to open or place with a confusing format error. They now explain that the format is closed and how to export IDML from InDesign instead. File › Open offers .indd and .indt files (desktop and web), and dropping one on the window opens it like a .designcraft or .idml file. A file that can't be opened or placed from File › Open, Place, a drop, the command line or the control channel's app.open shows an alert with the reason, as well as the status line. * File open: an .indd file is an unreadable file like any other Remove the INDD signature check and message, and .indd/.indt from the Open filters and drop routing. The alert tests use a generic unreadable file. * Control channel: a failed app.open answers with the error and opens no alert An alert waits for a click that a control client can't give. app.open reports the error in its response, as engine.execute does; File › Open, drops and the command line still show the alert. --- apps/designcraft/src/main.rs | 2 +- crates/ui-egui/src/dialogs.rs | 25 +++++-- crates/ui-egui/src/i18n.rs | 20 ++++++ crates/ui-egui/src/i18n/ar.rs | 2 + crates/ui-egui/src/lib.rs | 130 ++++++++++++++++++++++++++++++---- crates/ui-egui/src/menus.rs | 2 +- 6 files changed, 160 insertions(+), 21 deletions(-) diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index 101a5f5f5..307bfe1a0 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -245,7 +245,7 @@ fn main() -> eframe::Result { let _ = app.run("file.newSample", serde_json::json!({})); } for f in files { - if let Err(e) = app.run("file.open", serde_json::json!({"path": f})) { + if let Err(e) = app.open_file("file.open", serde_json::json!({"path": f})) { eprintln!("designcraft: {f}: {e}"); } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 34832db14..450e64c2f 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -803,7 +803,9 @@ fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) { pub fn show(app: &mut DesignApp, ctx: &egui::Context) { let Some(mut d) = app.ui.dialog.clone() else { return }; let mut result: Option = None; + let alert_title = d.s("title"); let title = match d.id.as_str() { + "alert" => crate::i18n::tr(&app.ui.language, &alert_title), "ruby" => crate::i18n::tr(&app.ui.language, "Ruby"), "newDocument" => crate::i18n::tr(&app.ui.language, "New Document"), "frameSize" => crate::i18n::tr(&app.ui.language, "Rectangle"), @@ -837,7 +839,11 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { }; egui::Modal::new(egui::Id::new("dialog")).show(ctx, |ui| { ui.set_min_width(380.0); - ui.set_max_width(if d.id == "newDocument" && crate::i18n::is_rtl(&app.ui.language) { 380.0 } else { 640.0 }); + ui.set_max_width(match d.id.as_str() { + "alert" => 440.0, + "newDocument" if crate::i18n::is_rtl(&app.ui.language) => 380.0, + _ => 640.0, + }); if crate::i18n::is_rtl(&app.ui.language) { ui.horizontal(|ui| { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { @@ -1366,6 +1372,14 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { }); } "documentSetup" => document_setup(app, ui, &mut d), + "alert" => { + let file = d.s("file"); + if !file.is_empty() { + crate::rtl::label(ui, egui::RichText::new(crate::rtl::isolate(&file)).font(semibold(13.0))); + ui.add_space(4.0); + } + crate::rtl::label(ui, d.s("message")); + } _ => {} } ui.add_space(12.0); @@ -1381,7 +1395,9 @@ pub fn show(app: &mut DesignApp, ctx: &egui::Context) { { result = Some(true); } - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Cancel"))).clicked() || ui.input(|i| i.key_pressed(egui::Key::Escape)) { + // An alert only has OK. + let cancel = d.id != "alert" && ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Cancel"))).clicked(); + if cancel || ui.input(|i| i.key_pressed(egui::Key::Escape)) { result = Some(false); } }); @@ -1498,7 +1514,7 @@ pub fn confirm(app: &mut DesignApp) -> Result { } "pdfImport" => { let crop = d.s("crop"); - app.run("file.place", json!({"path": d.s("path"), "pdfPage": d.n("page").unwrap_or(1.0).max(1.0) as u64, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }})) + app.open_file("file.place", json!({"path": d.s("path"), "pdfPage": d.n("page").unwrap_or(1.0).max(1.0) as u64, "pdfCrop": if crop.is_empty() { "crop".to_string() } else { crop }})) } "print" => { let pages = if d.s("range") == "all" { Value::Null } else { json!(d.s("pages")) }; @@ -1601,7 +1617,7 @@ pub fn confirm(app: &mut DesignApp) -> Result { app.run("document.preferences", doc) } "newWorkspace" => app.run("window.newWorkspace", json!({"name": d.s("name")})), - "importOptions" => app.run( + "importOptions" => app.open_file( "file.place", json!({"path": d.s("path"), "removeStyles": d.b("removeStyles"), "styleConflicts": d.s("styleConflicts"), "styleMap": d.fields.get("map").cloned().unwrap_or(json!({}))}), ), @@ -1669,6 +1685,7 @@ pub fn confirm(app: &mut DesignApp) -> Result { } app.run("footnote.options", p) } + "alert" => Ok(Value::Null), "findChange" if d.b("objectMode") => Ok(Value::Null), "findChange" => app.run("find.change", json!({"find": d.s("find"), "change": d.s("change"), "grep": d.b("grep"), "caseSensitive": d.b("caseSensitive"), "wholeWord": d.b("wholeWord"), "scope": d.s("scope")})), id if id.starts_with("cmd:") => { diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 878657a5f..fbb5fd27a 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -230,6 +230,26 @@ const TABLE: &[(&str, [&str; 5])] = &[ ("Business Card", ["Business Card", "Business Card", "Business Card", "Business Card", "名片"]), ("CMYK", ["CMYK", "CMYK", "CMYK", "CMYK", "CMYK"]), ("Cancel", ["Cancel", "Cancel", "Cancel", "Cancel", "取消"]), + ( + "Can't Open the File", + [ + "Datei kann nicht geöffnet werden", + "Impossible d'ouvrir le fichier", + "No se puede abrir el archivo", + "ファイルを開けません", + "无法打开文件", + ], + ), + ( + "Can't Place the File", + [ + "Datei kann nicht platziert werden", + "Impossible d'importer le fichier", + "No se puede colocar el archivo", + "ファイルを配置できません", + "无法置入文件", + ], + ), ("Center Content", ["Center Content", "Center Content", "Center Content", "Center Content", "内容居中"]), ("Change All", ["Change All", "Change All", "Change All", "Change All", "全部更改"]), ("Change to:", ["Change to:", "Change to:", "Change to:", "Change to:", "更改为:"]), diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 783f33e5e..34a50b57e 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -167,6 +167,8 @@ pub(super) const TABLE: &[(&str, &str)] = &[ ("Dock panel", "إرساء اللوحة"), ("OK", "موافق"), ("Cancel", "إلغاء"), + ("Can't Open the File", "تعذّر فتح الملف"), + ("Can't Place the File", "تعذّر إدراج الملف"), ("Apply", "تطبيق"), ("Done", "تم"), ("Reset", "إعادة ضبط"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7b474fa21..43a08167f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -58,8 +58,8 @@ pub struct Services { /// Hand bytes to the user as a named file (browser download). When set, Save uses it /// instead of writing to a path. pub download: Option, - /// Files delivered asynchronously, drained every frame: `.designcraft` → `file.openBytes`, - /// anything else → `file.place`. + /// Files delivered asynchronously, drained every frame: documents ([`opens_as_document`]) → + /// `file.openBytes`, `.ase` → `swatch.load`, anything else → `file.place`. pub inbox: Option, } @@ -539,10 +539,10 @@ impl DesignApp { self.ui.dialog = Some(dialogs::Dialog::new("pdfImport", json!({"path": path, "page": "1", "pages": pages}))); Ok(Value::Null) } else { - self.run(cmd, json!({"path": path})) + self.open_file(cmd, json!({"path": path})) } } - Some(path) => self.run(cmd, json!({"path": path})), + Some(path) => self.open_file(cmd, json!({"path": path})), None => Ok(Value::Null), }; } @@ -561,11 +561,11 @@ impl DesignApp { let lower = name.to_ascii_lowercase(); let r = if lower.ends_with(".ase") { self.run("swatch.load", json!({"base64": b64})) - } else if lower.ends_with(".designcraft") || lower.ends_with(".idml") { + } else if opens_as_document(&name) { let title = name.rsplit_once('.').map_or(name.as_str(), |(stem, _)| stem); - self.run("file.openBytes", json!({"name": title, "base64": b64})) + self.open_file("file.openBytes", json!({"name": title, "base64": b64})) } else { - self.run("file.place", json!({"name": name, "base64": b64})) + self.open_file("file.place", json!({"name": name, "base64": b64})) }; if let Err(e) = r { self.status(format!("{name}: {e}")); @@ -636,18 +636,34 @@ impl DesignApp { } #[cfg(not(target_arch = "wasm32"))] for f in ctx.input(|i| i.raw.dropped_files.clone()) { - { - let p = f.path().to_string_lossy().to_string(); - if p.is_empty() { - continue; - } - let lp = p.to_ascii_lowercase(); - let cmd = if lp.ends_with(".designcraft") || lp.ends_with(".idml") { "file.open" } else { "file.place" }; - let _ = self.run(cmd, json!({"path": p})); + let p = f.path().to_string_lossy().to_string(); + if !p.is_empty() { + let _ = self.open_dropped(&p); } } } + /// A file dropped on the window: documents open, anything else is placed. + pub fn open_dropped(&mut self, path: &str) -> Result { + let cmd = if opens_as_document(path) { "file.open" } else { "file.place" }; + self.open_file(cmd, json!({"path": path})) + } + + /// Open (`file.open`, `file.openBytes`) or place (`file.place`) a file the user chose. A file + /// that can't be opened or placed gets an alert with the reason, as well as the status line. + pub fn open_file(&mut self, cmd: &str, params: Value) -> Result { + let file = match params.get("path").and_then(Value::as_str) { + Some(path) => std::path::Path::new(path).file_name().map_or_else(|| path.to_string(), |n| n.to_string_lossy().to_string()), + None => params.get("name").and_then(Value::as_str).unwrap_or_default().to_string(), + }; + 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" }; + self.ui.dialog = Some(dialogs::Dialog::new("alert", json!({"title": title, "file": file, "message": e}))); + } + r + } + /// Inject synthetic events (one pointer event per frame). pub fn raw_input_hook(&mut self, raw: &mut egui::RawInput) { if self.synthetic.is_empty() { @@ -856,6 +872,13 @@ impl DesignApp { } } +/// Files that open as documents (when dropped or picked) rather than being placed: DesignCraft +/// and IDML. +pub fn opens_as_document(name: &str) -> bool { + let n = name.to_ascii_lowercase(); + [".designcraft", ".idml"].iter().any(|ext| n.ends_with(ext)) +} + pub fn now_ms() -> f64 { #[cfg(not(target_arch = "wasm32"))] { @@ -883,4 +906,81 @@ mod tests { assert!(!ui.snap_view().snap_to_guides); assert_eq!(ui.snap_view().zone_px, 0.0); } + + /// A temporary file named `name` whose bytes aren't a document or a graphic. + fn unreadable_file(name: &str) -> std::path::PathBuf { + let path = std::env::temp_dir().join(format!("designcraft-ui-{}-{name}", std::process::id())); + std::fs::write(&path, b"neither a document nor a graphic").unwrap(); + path + } + + /// The open alert dialog: (title, message). + fn alert(app: &DesignApp) -> (String, String) { + let d = app.ui.dialog.as_ref().expect("an alert is open"); + assert_eq!(d.id, "alert"); + (d.fields["title"].as_str().unwrap().to_string(), d.fields["message"].as_str().unwrap().to_string()) + } + + #[test] + fn dropped_documents_open_and_the_rest_is_placed() { + for name in ["a.designcraft", "B.IDML"] { + assert!(opens_as_document(name), "{name}"); + } + for name in ["a.png", "b.pdf", "idml.txt", "c.idml.zip"] { + assert!(!opens_as_document(name), "{name}"); + } + } + + #[test] + fn dropping_an_unreadable_file_alerts() { + // A document opens, so it says it can't be opened. + let path = unreadable_file("broken.designcraft"); + let mut app = DesignApp::new(Session::new(), Services::default()); + let r = app.open_dropped(&path.to_string_lossy()); + let _ = std::fs::remove_file(&path); + let e = r.unwrap_err(); + let (title, message) = alert(&app); + assert_eq!(title, "Can't Open the File", "a document opens, it isn't placed"); + assert_eq!(message, e); + assert!(app.ui.status.contains(&e), "the status line says it too"); + assert!(app.session.documents().is_empty()); + dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "OK closes the alert"); + // Anything else is placed, so it says it can't be placed. + app.run("file.new", json!({})).unwrap(); + let path = unreadable_file("notes.xyz"); + let r = app.open_dropped(&path.to_string_lossy()); + let _ = std::fs::remove_file(&path); + let e = r.unwrap_err(); + assert_eq!(alert(&app), ("Can't Place the File".to_string(), e)); + } + + #[test] + fn file_open_failures_show_an_alert() { + let path = unreadable_file("open.designcraft"); + let picked = path.to_string_lossy().to_string(); + let services = Services { pick_open: Some(Box::new(move |_| Some(picked.clone()))), ..Default::default() }; + let mut app = DesignApp::new(Session::new(), services); + let e = app.run("app.openDialog", json!({})).unwrap_err(); + assert_eq!(alert(&app), ("Can't Open the File".to_string(), e)); + // Placing it says so too. + app.ui.dialog = None; + app.run("file.new", json!({})).unwrap(); + let e = app.run("app.placeDialog", json!({})).unwrap_err(); + let _ = std::fs::remove_file(&path); + assert_eq!(alert(&app), ("Can't Place the File".to_string(), e)); + } + + #[test] + fn other_command_errors_stay_in_the_status_line() { + let mut app = DesignApp::new(Session::new(), Services::default()); + assert!(app.run("file.open", json!({"path": "/nonexistent/x.designcraft"})).is_err()); + assert!(app.ui.dialog.is_none(), "a scripted file.open doesn't raise an alert"); + assert!(!app.ui.status.is_empty()); + // The control channel's app.open answers with the error; no alert waits for a click. + let (req, _rx) = control::ControlRequest::new("app.open", json!({"path": "/nonexistent/x.designcraft"})); + let control::Outcome::Done(r) = control::handle(&mut app, &egui::Context::default(), &req) else { panic!("app.open answers") }; + assert_eq!(r["ok"], json!(false), "{r}"); + assert!(app.ui.dialog.is_none(), "a control-channel app.open doesn't raise an alert"); + } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index abff58c62..5774ce096 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -704,7 +704,7 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option v, From 4564ec6707112f9c9bebd4ab61326b84ed405e8c Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:09:47 -0400 Subject: [PATCH 05/24] UI: text fields take Select All, Copy, Cut, Paste, Undo and Redo from the Mac menu (#30) (#111) The macOS menu bar takes Cmd+A, Cmd+C, Cmd+X, Cmd+V, Cmd+Z and Cmd+Shift+Z before the window sees them, so in a panel, dialog or search field they ran the document's commands: Select All selected every frame, Paste pasted into the layout, Undo undid the last document change. While a text field has keyboard focus, these Edit items now act on the field, whether chosen by shortcut or from the menu: Select All, Undo and Redo reach it as their keys, Copy and Cut as clipboard events, and Paste asks the window for the system clipboard. The items stay enabled for the field even when the document has nothing to copy or undo. With no field focused, and for every other item, the menu works as before. --- apps/designcraft/src/main.rs | 2 +- apps/designcraft/src/native_menu.rs | 6 +- crates/ui-egui/src/menus.rs | 161 ++++++++++++++++++++++++++++ 3 files changed, 165 insertions(+), 4 deletions(-) diff --git a/apps/designcraft/src/main.rs b/apps/designcraft/src/main.rs index 307bfe1a0..a5cb13fb8 100644 --- a/apps/designcraft/src/main.rs +++ b/apps/designcraft/src/main.rs @@ -25,7 +25,7 @@ impl eframe::App for App { self.1 = Some(native_menu::NativeMenu::install(&mut self.0)); } if let Some(m) = &mut self.1 { - m.poll(&mut self.0); + m.poll(&mut self.0, ctx); } } self.0.logic(ctx); diff --git a/apps/designcraft/src/native_menu.rs b/apps/designcraft/src/native_menu.rs index 4c039efd3..8bf75b159 100644 --- a/apps/designcraft/src/native_menu.rs +++ b/apps/designcraft/src/native_menu.rs @@ -72,10 +72,10 @@ impl NativeMenu { Self { _menu: menu, items, last_refresh: 0.0 } } - pub fn poll(&mut self, app: &mut DesignApp) { + pub fn poll(&mut self, app: &mut DesignApp, ctx: &egui::Context) { while let Ok(ev) = MenuEvent::receiver().try_recv() { if let Some((cmd, params, _)) = self.items.get(ev.id.as_ref()) { - designcraft_ui_egui::menus::activate(app, &cmd.clone(), ¶ms.clone()); + menus::activate_native(app, ctx, &cmd.clone(), ¶ms.clone()); } } let now = designcraft_ui_egui::now_ms(); @@ -84,7 +84,7 @@ impl NativeMenu { } self.last_refresh = now; for (cmd, params, h) in self.items.values() { - let en = menus::menu_enabled(app, cmd); + let en = menus::native_menu_enabled(app, ctx, cmd); match h { Handle::Plain(i) => i.set_enabled(en), Handle::Check(c) => { diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 5774ce096..be0b0303a 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1743,6 +1743,44 @@ pub fn activate(app: &mut DesignApp, id: &str, params: &Value) { let _ = app.run(id, p); } +/// A native menu bar item was chosen (macOS): like [`activate`], except that the menu bar takes +/// ⌘A, ⌘C, ⌘X, ⌘V, ⌘Z and ⇧⌘Z before the window sees them, so while a text field has keyboard +/// focus, Select All, Copy, Cut, Paste, Undo and Redo act on that field, as in any Mac app. +pub fn activate_native(app: &mut DesignApp, ctx: &egui::Context, id: &str, params: &Value) { + if !(ctx.text_edit_focused() && params.is_null() && forward_to_text_field(app, ctx, id)) { + activate(app, id, params); + } +} + +/// Whether a native menu bar item can be chosen: as in the in-window menus, but the editing +/// commands a focused text field takes are always available to it. +pub fn native_menu_enabled(app: &DesignApp, ctx: &egui::Context, id: &str) -> bool { + (ctx.text_edit_focused() && TEXT_FIELD_COMMANDS.contains(&id)) || menu_enabled(app, id) +} + +/// The editing commands a focused text field takes from the native menu bar. +const TEXT_FIELD_COMMANDS: [&str; 6] = ["edit.selectAll", "edit.copy", "edit.cut", "edit.paste", "edit.undo", "edit.redo"]; + +/// Hand a standard editing command to the focused text field as next frame's input; false when +/// `id` isn't one of them. +fn forward_to_text_field(app: &mut DesignApp, ctx: &egui::Context, id: &str) -> bool { + let key = |key: egui::Key, modifiers: egui::Modifiers| { + [true, false].map(|pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers }) + }; + match id { + "edit.selectAll" => app.synthetic.extend(key(egui::Key::A, egui::Modifiers::COMMAND)), + "edit.undo" => app.synthetic.extend(key(egui::Key::Z, egui::Modifiers::COMMAND)), + "edit.redo" => app.synthetic.extend(key(egui::Key::Z, egui::Modifiers::COMMAND | egui::Modifiers::SHIFT)), + "edit.copy" => app.synthetic.push(egui::Event::Copy), + "edit.cut" => app.synthetic.push(egui::Event::Cut), + // Only the integration reads the system clipboard: it answers with an `Event::Paste`. + "edit.paste" => ctx.send_viewport_cmd(egui::ViewportCommand::RequestPaste), + _ => return false, + } + ctx.request_repaint(); + true +} + /// The menu bar contents (inside the app bar; macOS uses the native menu instead). pub fn menu_bar(app: &mut DesignApp, ui: &mut egui::Ui) { let lang = app.ui.language.clone(); @@ -2433,6 +2471,129 @@ mod tests { assert!(run_ui(&mut app, "window.floatPanel", &json!({"panel": "nope"})).unwrap().is_err()); } + /// One frame as the desktop app runs it: queued synthetic input, then the native menu item + /// chosen during the frame (`menu`), then the app's logic and ui. + fn native_frame(app: &mut crate::DesignApp, ctx: &egui::Context, events: Vec, menu: Option<&str>) -> egui::FullOutput { + let mut input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + app.raw_input_hook(&mut input); + let mut menu = menu; + let mut out = ctx.run_ui(input, |ui| { + let ctx = ui.ctx().clone(); + if let Some(id) = menu.take() { + activate_native(app, &ctx, id, &Value::Null); + } + app.logic(&ctx); + app.ui(ui); + }); + out.textures_delta.clear(); + out + } + + /// A document with two frames, nothing selected, and Quick Apply's search field focused + /// holding `text`. + fn app_with_focused_field(ctx: &egui::Context, text: &str) -> crate::DesignApp { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.session.execute("frame.create", &json!({"rect": [36, 36, 200, 200]})).unwrap(); + app.session.execute("frame.create", &json!({"rect": [236, 36, 400, 200]})).unwrap(); + app.session.execute("edit.deselectAll", &json!({})).unwrap(); + app.ui.palette = Some(text.into()); + for _ in 0..3 { + native_frame(&mut app, ctx, vec![], None); + } + assert!(ctx.text_edit_focused()); + app + } + + fn field_selection(ctx: &egui::Context) -> Option<(usize, usize)> { + let id = ctx.memory(|m| m.focused())?; + let r = egui::TextEdit::load_state(ctx, id)?.cursor.char_range()?; + Some((r.primary.index.min(r.secondary.index).into(), r.primary.index.max(r.secondary.index).into())) + } + + fn document_items(app: &crate::DesignApp) -> (usize, usize) { + let d = app.session.active().unwrap(); + (d.doc.spreads.iter().flat_map(|sp| &sp.items).count(), d.selection.items.len()) + } + + #[test] + fn native_select_all_selects_the_focused_fields_text() { + // The Mac menu bar takes ⌘A before the window sees it (#30). + let ctx = egui::Context::default(); + let mut app = app_with_focused_field(&ctx, "frame"); + native_frame(&mut app, &ctx, vec![], Some("edit.selectAll")); + native_frame(&mut app, &ctx, vec![], None); + assert_eq!(field_selection(&ctx), Some((0, 5)), "the field's whole text is selected"); + assert_eq!(document_items(&app), (2, 0), "the document selection is unchanged"); + } + + #[test] + fn native_paste_and_copy_act_on_the_focused_field() { + let ctx = egui::Context::default(); + let mut app = app_with_focused_field(&ctx, "frame"); + native_frame(&mut app, &ctx, vec![], Some("edit.selectAll")); + native_frame(&mut app, &ctx, vec![], None); + // Copy puts the field's selected text on the clipboard. + native_frame(&mut app, &ctx, vec![], Some("edit.copy")); + let out = native_frame(&mut app, &ctx, vec![], None); + assert!(out.platform_output.commands.contains(&egui::OutputCommand::CopyText("frame".into())), "{:?}", out.platform_output.commands); + // Paste asks the integration for the clipboard, which it hands to the field as a paste. + let out = native_frame(&mut app, &ctx, vec![], Some("edit.paste")); + let commands = &out.viewport_output[&egui::ViewportId::ROOT].commands; + assert!(commands.contains(&egui::ViewportCommand::RequestPaste), "{commands:?}"); + native_frame(&mut app, &ctx, vec![egui::Event::Paste("text".into())], None); + assert_eq!(app.ui.palette.as_deref(), Some("text")); + assert_eq!(document_items(&app), (2, 0), "nothing was pasted into the document"); + } + + #[test] + fn native_undo_and_redo_act_on_the_focused_field() { + let ctx = egui::Context::default(); + let mut app = app_with_focused_field(&ctx, ""); + native_frame(&mut app, &ctx, vec![egui::Event::Text("abc".into())], None); + assert_eq!(app.ui.palette.as_deref(), Some("abc")); + native_frame(&mut app, &ctx, vec![], Some("edit.undo")); + native_frame(&mut app, &ctx, vec![], None); + assert_eq!(app.ui.palette.as_deref(), Some(""), "the field's typing is undone"); + assert_eq!(document_items(&app), (2, 0), "the document's last frame is still there"); + native_frame(&mut app, &ctx, vec![], Some("edit.redo")); + native_frame(&mut app, &ctx, vec![], None); + assert_eq!(app.ui.palette.as_deref(), Some("abc")); + assert_eq!(document_items(&app), (2, 0)); + } + + #[test] + fn native_editing_items_are_enabled_for_a_focused_field() { + let ctx = egui::Context::default(); + let mut app = app_with_focused_field(&ctx, "frame"); + // Nothing is selected in the document, so its Copy and Cut are off; the field's are on. + assert!(!menu_enabled(&app, "edit.copy") && !menu_enabled(&app, "edit.cut")); + for id in ["edit.selectAll", "edit.copy", "edit.cut", "edit.paste", "edit.undo", "edit.redo"] { + assert!(native_menu_enabled(&app, &ctx, id), "{id}"); + } + assert!(!native_menu_enabled(&app, &ctx, "edit.duplicate"), "other items follow the document"); + app.ui.palette = None; + native_frame(&mut app, &ctx, vec![], None); + native_frame(&mut app, &ctx, vec![], None); + assert!(!native_menu_enabled(&app, &ctx, "edit.copy"), "without a focused field, as the document says"); + } + + #[test] + fn native_select_all_without_a_focused_field_selects_the_documents_items() { + let ctx = egui::Context::default(); + let mut app = app_with_focused_field(&ctx, "frame"); + app.ui.palette = None; + native_frame(&mut app, &ctx, vec![], None); + native_frame(&mut app, &ctx, vec![], None); + assert!(!ctx.text_edit_focused()); + native_frame(&mut app, &ctx, vec![], Some("edit.selectAll")); + assert_eq!(document_items(&app), (2, 2)); + } + #[test] fn quick_apply_lists_styles_then_commands() { let mut s = designcraft_engine::Session::new(); From d730d8fa271e19a5e3dddeae15a5e6edb862e784 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:09:52 -0400 Subject: [PATCH 06/24] UI: toolbars that don't fit the window switch to two columns or scroll (#57) (#112) * UI: toolbars that don't fit the window switch to two columns or scroll (#57) In a short window the Tools panel lays its tools out in two columns, without changing the single/double-column preference, which comes back when the window grows again. While the window forces two columns the column toggle is disabled. Whatever two columns can't fit scrolls vertically. The Control panel and the application bar scroll sideways when their controls are wider than the window. The Control panel keeps its height. In the application bar the workspace controls follow the menus instead of overlapping them. A plain mouse wheel scrolls these one-direction bars, and a thin floating scroll bar shows only when something overflows, so nothing changes while everything fits. Tool buttons, icon buttons and the Fill proxy carry accessibility labels, which the new window-size tests use to find them. * UI: captions in a sideways-scrolled bar stay on one line The last group of a scrolled Control bar row got only the width left over, so a caption like Columns wrapped one letter per line. --- crates/ui-egui/src/chrome.rs | 268 ++++++++++++++++++++++++---------- crates/ui-egui/src/icons.rs | 2 + crates/ui-egui/src/lib.rs | 51 +++++++ crates/ui-egui/src/toolbar.rs | 126 +++++++++++++--- crates/ui-egui/src/widgets.rs | 15 ++ 5 files changed, 364 insertions(+), 98 deletions(-) diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index dfb5e699b..23876f3a7 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -21,86 +21,105 @@ pub fn app_bar(app: &mut DesignApp, ui: &mut egui::Ui) { let full = ui.max_rect(); let mut menus_end = full.min.x; let mut tools_start = full.max.x; - ui.horizontal_centered(|ui| { - if icons::button(ui, "home", 24.0, app.session.active().is_none(), crate::i18n::tr(&app.ui.language, "Home")).clicked() { - app.session_home(); - } - ui.add_space(6.0); - if !app.native_menu { - ui.style_mut().visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT; - ui.style_mut().visuals.widgets.inactive.bg_stroke = Stroke::NONE; - ui.style_mut().visuals.widgets.hovered.bg_stroke = Stroke::NONE; - ui.style_mut().spacing.button_padding = vec2(7.0, 3.0); - crate::menus::menu_bar(app, ui); - } - menus_end = ui.min_rect().max.x; - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.add_space(4.0); - // Search field. - let (r, _) = ui.allocate_exact_size(vec2(125.0, 18.0), Sense::click()); - ui.painter().rect(r, 1.0, t.input, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); - icons::paint(ui.painter(), egui::Rect::from_min_size(r.min + vec2(3.0, 2.0), vec2(14.0, 14.0)), "search", t.icon); - crate::rtl::paint( - ui.painter(), - r.min + vec2(20.0, 9.0), - egui::Align2::LEFT_CENTER, - crate::i18n::tr(&app.ui.language, "Search"), - egui::FontId::proportional(11.0), - t.text_dim, - ); - ui.add_space(8.0); - let current = app.ui.workspace.clone(); - let shown = crate::i18n::workspace_name(&app.ui.language, ¤t); - ui.menu_button(crate::rtl::widget(ui, egui::RichText::new(format!("{shown} ▾")).font(semibold(11.5)).color(t.text)), |ui| { - let customs: Vec = app.ui.custom_workspaces.iter().map(|w| w.name.clone()).collect(); - for w in - ["Essentials", "Advanced", "Book", "Digital Publishing", "Interactive for PDF", "Printing and Proofing", "Typography"] - .into_iter() - .map(str::to_string) - .chain(customs.iter().cloned()) - { - if ui.selectable_label(w == current, crate::rtl::widget(ui, crate::i18n::workspace_name(&app.ui.language, &w))).clicked() + // The right-hand controls' width, measured last frame: in a window too narrow for them + // and the menus they follow the menus, and the bar scrolls sideways. + let tools_w_id = ui.id().with("tools_width"); + let tools_w: f32 = ui.data(|d| d.get_temp(tools_w_id)).unwrap_or(0.0); + crate::widgets::overflow_scrolling(ui); + egui::ScrollArea::horizontal().id_salt("app_bar_scroll").auto_shrink([false, false]).show(ui, |ui| { + ui.horizontal_centered(|ui| { + if icons::button(ui, "home", 24.0, app.session.active().is_none(), crate::i18n::tr(&app.ui.language, "Home")).clicked() { + app.session_home(); + } + ui.add_space(6.0); + if !app.native_menu { + ui.style_mut().visuals.widgets.inactive.weak_bg_fill = Color32::TRANSPARENT; + ui.style_mut().visuals.widgets.inactive.bg_stroke = Stroke::NONE; + ui.style_mut().visuals.widgets.hovered.bg_stroke = Stroke::NONE; + ui.style_mut().spacing.button_padding = vec2(7.0, 3.0); + crate::menus::menu_bar(app, ui); + } + menus_end = ui.min_rect().max.x; + let size = vec2(ui.available_width().max(tools_w), ui.available_height()); + let tools = ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| { + ui.add_space(4.0); + // Search field. + let (r, _) = ui.allocate_exact_size(vec2(125.0, 18.0), Sense::click()); + ui.painter().rect(r, 1.0, t.input, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside); + icons::paint(ui.painter(), egui::Rect::from_min_size(r.min + vec2(3.0, 2.0), vec2(14.0, 14.0)), "search", t.icon); + crate::rtl::paint( + ui.painter(), + r.min + vec2(20.0, 9.0), + egui::Align2::LEFT_CENTER, + crate::i18n::tr(&app.ui.language, "Search"), + egui::FontId::proportional(11.0), + t.text_dim, + ); + ui.add_space(8.0); + let current = app.ui.workspace.clone(); + let shown = crate::i18n::workspace_name(&app.ui.language, ¤t); + ui.menu_button(crate::rtl::widget(ui, egui::RichText::new(format!("{shown} ▾")).font(semibold(11.5)).color(t.text)), |ui| { + let customs: Vec = app.ui.custom_workspaces.iter().map(|w| w.name.clone()).collect(); + for w in + ["Essentials", "Advanced", "Book", "Digital Publishing", "Interactive for PDF", "Printing and Proofing", "Typography"] + .into_iter() + .map(str::to_string) + .chain(customs.iter().cloned()) { - let _ = app.run("window.workspace", json!({"name": w})); + if ui + .selectable_label(w == current, crate::rtl::widget(ui, crate::i18n::workspace_name(&app.ui.language, &w))) + .clicked() + { + let _ = app.run("window.workspace", json!({"name": w})); + ui.close(); + } + } + ui.separator(); + if ui + .button(crate::rtl::widget( + ui, + format!( + "{} {}", + crate::i18n::tr(&app.ui.language, "Reset"), + crate::i18n::workspace_name(&app.ui.language, ¤t) + ), + )) + .clicked() + { + let _ = app.run("window.resetWorkspace", json!({})); ui.close(); } - } - ui.separator(); - if ui - .button(crate::rtl::widget( - ui, - format!("{} {}", crate::i18n::tr(&app.ui.language, "Reset"), crate::i18n::workspace_name(&app.ui.language, ¤t)), - )) - .clicked() - { - let _ = app.run("window.resetWorkspace", json!({})); - ui.close(); - } - if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "New Workspace…"))).clicked() { - let _ = app.run("window.newWorkspace", json!({})); - ui.close(); - } - if !customs.is_empty() { - ui.menu_button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Delete Workspace")), |ui| { - for w in &customs { - if ui.button(w).clicked() { - let _ = app.run("window.deleteWorkspace", json!({"name": w})); - ui.close(); + if ui.button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "New Workspace…"))).clicked() { + let _ = app.run("window.newWorkspace", json!({})); + ui.close(); + } + if !customs.is_empty() { + ui.menu_button(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Delete Workspace")), |ui| { + for w in &customs { + if ui.button(w).clicked() { + let _ = app.run("window.deleteWorkspace", json!({"name": w})); + ui.close(); + } } - } - }); + }); + } + }); + ui.add_space(6.0); + if icons::button(ui, "share", 22.0, false, crate::i18n::tr(&app.ui.language, "Share")).clicked() { + app.status("Export a PDF, IDML or package to share — no cloud account needed."); } + ui.add_space(8.0); + // Always one click away: the ArtCraft community Discord. + if crate::about::discord_button(ui, "Discord", vec2(78.0, 22.0)) { + let _ = app.run("help.discord", json!({})); + } + tools_start = ui.min_rect().min.x; + ui.min_rect().width() }); - ui.add_space(6.0); - if icons::button(ui, "share", 22.0, false, crate::i18n::tr(&app.ui.language, "Share")).clicked() { - app.status("Export a PDF, IDML or package to share — no cloud account needed."); + if (tools.inner - tools_w).abs() > 0.5 { + ui.data_mut(|d| d.insert_temp(tools_w_id, tools.inner)); + ui.ctx().request_discard("app bar: the right-hand controls changed width"); } - ui.add_space(8.0); - // Always one click away: the ArtCraft community Discord. - if crate::about::discord_button(ui, "Discord", vec2(78.0, 22.0)) { - let _ = app.run("help.discord", json!({})); - } - tools_start = ui.min_rect().min.x; }); }); // Centred title. @@ -142,14 +161,18 @@ pub fn control_bar(app: &mut DesignApp, ui: &mut egui::Ui) { egui::Frame::NONE.fill(t.panel).inner_margin(egui::Margin { left: 8, right: 8, top: 5, bottom: 3 }).stroke(Stroke::new(1.0, t.divider)), ) .show(ui, |ui| { - ui.horizontal(|ui| { - let text_mode = - matches!(app.session.tool_id(), "type" | "verticalType") || app.session.active().is_some_and(|d| d.selection.text.is_some()); - if text_mode { - control_text(app, ui); - } else { - control_object(app, ui); - } + // Wider than the window: the bar scrolls sideways. + crate::widgets::overflow_scrolling(ui); + egui::ScrollArea::horizontal().id_salt("control_bar_scroll").auto_shrink([false, true]).show(ui, |ui| { + ui.horizontal(|ui| { + let text_mode = + matches!(app.session.tool_id(), "type" | "verticalType") || app.session.active().is_some_and(|d| d.selection.text.is_some()); + if text_mode { + control_text(app, ui); + } else { + control_object(app, ui); + } + }); }); }); } @@ -716,3 +739,86 @@ fn community_card(app: &mut DesignApp, ui: &mut egui::Ui) { }); }); } + +#[cfg(test)] +mod tests { + use egui::{pos2, vec2}; + use egui_kittest::kittest::Queryable; + + use crate::test_window::{self, wheel}; + + /// The Control panel's last control with nothing selected. + const LAST_CONTROL: &str = "Jump to Next Column"; + const FIRST_CONTROL: &str = "Rotate 90° Counterclockwise"; + + fn app() -> crate::DesignApp { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.control_bar = true; + app + } + + fn rect(h: &egui_kittest::Harness<'static, test_window::Window>, label: &str) -> egui::Rect { + h.get_by_label(label).rect() + } + + #[test] + fn a_narrow_window_scrolls_the_control_bar() { + let w = 700.0; + let mut h = test_window::open(app(), vec2(w, 600.0)); + let bar = test_window::panel_rect(&h, "control_bar"); + assert!(rect(&h, LAST_CONTROL).max.x > w, "the controls are wider than the window"); + // A plain mouse wheel scrolls the bar sideways. + let first = rect(&h, FIRST_CONTROL).center(); + wheel(&mut h, first, vec2(0.0, -3000.0)); + let last = rect(&h, LAST_CONTROL); + let window = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(w, 600.0)); + assert!(window.contains_rect(last) && bar.contains_rect(last), "{last:?} outside the bar {bar:?}"); + assert_eq!(test_window::panel_rect(&h, "control_bar").height(), bar.height(), "the bar keeps its height"); + // A popup opened from a scrolled control opens at that control. + let fill = h.get_by_label("Fill").rect(); + let chip = pos2(fill.max.x + 15.0, fill.center().y); + h.hover_at(chip); + h.drag_at(chip); + h.drop_at(chip); + h.run_steps(4); + let item = rect(&h, "[Black]"); + assert!(item.min.y > fill.max.y && (item.min.x - chip.x).abs() < 120.0, "popup item at {item:?}, control at {chip:?}"); + } + + #[test] + fn a_narrow_window_scrolls_the_app_bar() { + let w = 640.0; + let mut h = test_window::open(app(), vec2(w, 600.0)); + let (help, share) = (rect(&h, "Help"), rect(&h, "Share")); + assert!(help.max.x <= share.min.x, "the menus ({help:?}) and the workspace controls ({share:?}) overlap"); + wheel(&mut h, help.center(), vec2(0.0, -3000.0)); + let share = rect(&h, "Share"); + let window = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(w, 600.0)); + assert!(window.contains_rect(share), "{share:?} outside the window"); + } + + #[test] + fn a_wide_window_does_not_scroll_the_bars() { + let mut h = test_window::open(app(), vec2(1400.0, 900.0)); + let before = [rect(&h, FIRST_CONTROL), rect(&h, LAST_CONTROL), rect(&h, "Help"), rect(&h, "Share")]; + assert!(before.iter().all(|r| r.max.x <= 1400.0), "{before:?}"); + wheel(&mut h, before[0].center(), vec2(0.0, -3000.0)); + wheel(&mut h, before[2].center(), vec2(0.0, -3000.0)); + let after = [rect(&h, FIRST_CONTROL), rect(&h, LAST_CONTROL), rect(&h, "Help"), rect(&h, "Share")]; + assert_eq!(after, before); + } + + #[test] + fn a_scrolled_bar_keeps_its_captions_on_one_line() { + let mut app = app(); + app.run("file.new", serde_json::json!({})).unwrap(); + let f = app.run("frame.create", serde_json::json!({"rect": [72, 72, 300, 200], "content": "text", "text": "Hello"})).unwrap(); + app.run("selection.set", serde_json::json!({"ids": [f["id"]]})).unwrap(); + let mut h = test_window::open(app, vec2(700.0, 600.0)); + let bar = test_window::panel_rect(&h, "control_bar").center(); + wheel(&mut h, bar, vec2(0.0, -3000.0)); + // The text frame's last group: its caption gets only what is left of the row. + let columns = h.get_by_label("Columns").rect(); + assert!(columns.height() < 20.0 && columns.width() > columns.height(), "Columns wraps: {columns:?}"); + } +} diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 7e2146036..69415e9b3 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -805,6 +805,8 @@ pub fn button(ui: &mut egui::Ui, name: &str, size: f32, selected: bool, tip: &st } let pad = size * 0.16; paint(ui.painter(), r.shrink(pad), name, if selected { t.text_strong } else { t.icon }); + let enabled = ui.is_enabled(); + resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::Button, enabled, selected, tip)); if tip.is_empty() { resp } else { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 43a08167f..275018cb6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -984,3 +984,54 @@ mod tests { assert!(app.ui.dialog.is_none(), "a control-channel app.open doesn't raise an alert"); } } + +/// The whole window in a headless test harness, at a chosen window size. +#[cfg(test)] +pub(crate) mod test_window { + use egui_kittest::Harness; + + pub struct Window { + pub app: crate::DesignApp, + ready: bool, + } + + /// The window at `size` with a new document open. + pub fn open(mut app: crate::DesignApp, size: egui::Vec2) -> Harness<'static, Window> { + if app.session.active().is_none() { + app.run("file.new", serde_json::json!({})).unwrap(); + } + let mut h = Harness::builder().with_size(size).with_max_steps(1000).build_ui_state( + |ui, w: &mut Window| { + // The builder runs a frame before the texture size can be raised: skip it. + if !w.ready { + return; + } + let ctx = ui.ctx().clone(); + w.app.logic(&ctx); + w.app.ui(ui); + }, + Window { app, ready: false }, + ); + h.input_mut().max_texture_side = Some(8192); + h.state_mut().ready = true; + h.run_steps(6); + h + } + + /// The mouse wheel turned over `pos`: positive `delta` moves the content right and down. + pub fn wheel(h: &mut Harness<'static, Window>, pos: egui::Pos2, delta: egui::Vec2) { + h.hover_at(pos); + h.event(egui::Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta, + phase: egui::TouchPhase::Move, + modifiers: egui::Modifiers::NONE, + }); + h.run_steps(10); + } + + /// The outer rect of a side or top panel, from egui's memory. + pub fn panel_rect(h: &Harness<'static, Window>, id: &str) -> egui::Rect { + egui::containers::panel::PanelState::load(&h.ctx, egui::Id::new(id)).map(|s| s.outer_rect).unwrap() + } +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index a3d495479..5a5e1f08a 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -12,27 +12,33 @@ const BTN: f32 = 24.0; pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { let t = Tokens::get(ui.ctx()); - let cols = if app.ui.tools_double_column { 2 } else { 1 }; + let frame = egui::Frame::NONE.fill(t.panel).stroke(Stroke::new(1.0, t.divider)); + // A single column that doesn't fit the window's height becomes two, without changing the + // preference; whatever two columns still can't fit scrolls. + let single_h_id = egui::Id::new("tools_single_column_height"); + let single_h: Option = ui.data(|d| d.get_temp(single_h_id)); + let viewport_h = ui.available_height() - frame.total_margin().sum().y; + let crowded = !app.ui.tools_double_column && single_h.is_some_and(|h| h > viewport_h); + let cols = if app.ui.tools_double_column || crowded { 2 } else { 1 }; let width = 8.0 + BTN * cols as f32 + 4.0 * (cols as f32 - 1.0) + 8.0; - let r = egui::Panel::left("tools") - .exact_size(width) - .resizable(false) - .frame(egui::Frame::NONE.fill(t.panel).stroke(Stroke::new(1.0, t.divider))) - .show(ui, |ui| { + let r = egui::Panel::left("tools").exact_size(width).resizable(false).frame(frame).show(ui, |ui| { + crate::widgets::overflow_scrolling(ui); + let scroll = egui::ScrollArea::vertical().id_salt("tools_scroll").auto_shrink([false, false]).show(ui, |ui| { ui.spacing_mut().item_spacing.y = 1.0; ui.add_space(3.0); - // Collapse chevrons. + // Collapse chevrons (nothing to toggle while the window forces two columns). ui.horizontal(|ui| { ui.add_space(width / 2.0 - 8.0); - if icons::button( - ui, - if cols == 1 { "double-chevron-right" } else { "double-chevron-left" }, - 16.0, - false, - crate::i18n::tr(&app.ui.language, "Toggle double column"), - ) - .clicked() - { + let toggle = ui.add_enabled_ui(!crowded, |ui| { + icons::button( + ui, + if cols == 1 { "double-chevron-right" } else { "double-chevron-left" }, + 16.0, + false, + crate::i18n::tr(&app.ui.language, "Toggle double column"), + ) + }); + if toggle.inner.clicked() { app.ui.tools_double_column = !app.ui.tools_double_column; } }); @@ -169,6 +175,15 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { ui.add_space(8.0); fill_stroke_proxy(app, ui, width); }); + if cols == 1 { + let h = scroll.content_size.y; + ui.data_mut(|d| d.insert_temp(single_h_id, h)); + // Laid out in one column that turned out too tall: lay out again in two. + if h > viewport_h { + ui.ctx().request_discard("tools panel: one column does not fit"); + } + } + }); if std::env::var_os("DESIGNCRAFT_DEBUG_LAYOUT").is_some() { eprintln!("tools panel rect {:?} (wanted width {width}); remaining {:?}", r.response.rect, ui.available_rect_before_wrap()); } @@ -252,9 +267,11 @@ fn fill_stroke_proxy(app: &mut DesignApp, ui: &mut egui::Ui, width: f32) { paint_stroke(p); paint_fill(p); } + let fill_tip = crate::i18n::tr(&app.ui.language, "Fill (X)"); let fresp = ui.interact(fill_r, ui.id().with("proxy_fill"), Sense::click()).on_hover_ui(|ui| { - crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Fill (X)")); + crate::rtl::label(ui, fill_tip); }); + fresp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, fill_tip)); let sresp = ui.interact(stroke_r.translate(vec2(0.0, 0.0)), ui.id().with("proxy_stroke"), Sense::click()).on_hover_ui(|ui| { crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Stroke (X)")); }); @@ -387,7 +404,82 @@ fn tool_button(ui: &mut egui::Ui, icon: &str, active: bool, tip: &str) -> egui:: ui.painter().rect_filled(egui::Rect::from_center_size(r.center(), egui::vec2(28.0, 20.0)), 2.0, t.hover); } icons::paint(ui.painter(), egui::Rect::from_center_size(r.center(), egui::vec2(17.0, 17.0)), icon, if active { t.text_strong } else { t.icon }); + let enabled = ui.is_enabled(); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, tip)); resp.on_hover_ui(|ui| { crate::rtl::label(ui, tip); }) } + +#[cfg(test)] +mod tests { + use egui::{pos2, vec2}; + use egui_kittest::kittest::Queryable; + + use crate::test_window::{self, wheel}; + + /// The last tool group's button and the Fill proxy, near the bottom of the panel. + const LAST_TOOL: &str = "Zoom Tool (Z)"; + const FILL: &str = "Fill (X)"; + /// Status bar height: the Tools panel ends above it. + const STATUS_H: f32 = 17.0; + + fn app(double: bool) -> crate::DesignApp { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.tools_double_column = double; + app + } + + fn column_width(cols: f32) -> f32 { + 8.0 + super::BTN * cols + 4.0 * (cols - 1.0) + 8.0 + } + + fn rect(h: &egui_kittest::Harness<'static, test_window::Window>, label: &str) -> egui::Rect { + h.get_by_label(label).rect() + } + + #[test] + fn a_short_window_reaches_every_tool() { + for double in [false, true] { + let (w, ht) = (1000.0, 500.0); + let mut h = test_window::open(app(double), vec2(w, ht)); + let panel = test_window::panel_rect(&h, "tools"); + wheel(&mut h, panel.center(), vec2(0.0, -2000.0)); + let visible = egui::Rect::from_min_max(pos2(0.0, panel.min.y), pos2(w, ht - STATUS_H)); + for label in [LAST_TOOL, FILL] { + let r = rect(&h, label); + assert!(visible.contains_rect(r), "double column {double}: {label} at {r:?} is outside {visible:?}"); + } + assert_eq!(h.state().app.ui.tools_double_column, double, "the preference is the user's"); + } + } + + #[test] + fn tools_take_two_columns_while_one_does_not_fit() { + let (w, ht) = (1086.0, 612.0); + let mut h = test_window::open(app(false), vec2(w, ht)); + assert_eq!(test_window::panel_rect(&h, "tools").width(), column_width(2.0)); + let visible = egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(w, ht - STATUS_H)); + for label in [LAST_TOOL, FILL] { + let r = rect(&h, label); + assert!(visible.contains_rect(r), "{label} at {r:?} is outside {visible:?} without scrolling"); + } + assert!(!h.state().app.ui.tools_double_column); + // A taller window brings the single column back. + h.set_size(vec2(1400.0, 900.0)); + h.run_steps(4); + assert_eq!(test_window::panel_rect(&h, "tools").width(), column_width(1.0)); + assert!(!h.state().app.ui.tools_double_column); + } + + #[test] + fn a_tall_window_keeps_one_column_and_does_not_scroll() { + let mut h = test_window::open(app(false), vec2(1400.0, 900.0)); + let panel = test_window::panel_rect(&h, "tools"); + assert_eq!(panel.width(), column_width(1.0)); + let before = (rect(&h, LAST_TOOL), rect(&h, FILL)); + assert!(panel.contains_rect(before.0) && panel.contains_rect(before.1), "{before:?} outside {panel:?}"); + wheel(&mut h, panel.center(), vec2(0.0, -2000.0)); + assert_eq!((rect(&h, LAST_TOOL), rect(&h, FILL)), before); + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 8e6b72167..dd7f3d8b7 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -572,6 +572,21 @@ pub fn segmented(ui: &mut Ui, labels: &[&str], active: usize, width: f32) -> Opt out } +/// Scrolling for a bar that a small window cuts off (Tools panel, Control panel, application +/// bar): the mouse wheel scrolls the bar's only direction, and a thin scroll bar floats over the +/// contents, so nothing moves and nothing shows while everything fits. +pub fn overflow_scrolling(ui: &mut Ui) { + let style = ui.style_mut(); + style.always_scroll_the_only_direction = true; + // A caption at the end of a scrolled row gets only what is left of it: extend, don't wrap. + style.wrap_mode = Some(egui::TextWrapMode::Extend); + let s = &mut style.spacing.scroll; + *s = egui::style::ScrollStyle::floating(); + s.bar_width = 6.0; + // A faint handle while the pointer is elsewhere: the bar shows there is more. + s.dormant_handle_opacity = 0.5; +} + #[cfg(test)] mod tests { use super::*; From 788e0eac669bf280d9a44f5515596d2ca773f131 Mon Sep 17 00:00:00 2001 From: Haseom Shin Date: Sat, 10 Oct 2026 14:13:17 +0900 Subject: [PATCH 07/24] Images: set SVG text in the shared fonts when the bundled ones lack it (#116) --- crates/fonts/src/testing.rs | 9 ++-- crates/images/Cargo.toml | 3 ++ crates/images/src/lib.rs | 100 ++++++++++++++++++++++++++++++++++-- 3 files changed, 105 insertions(+), 7 deletions(-) diff --git a/crates/fonts/src/testing.rs b/crates/fonts/src/testing.rs index e03ad1b6f..830f3d358 100644 --- a/crates/fonts/src/testing.rs +++ b/crates/fonts/src/testing.rs @@ -29,14 +29,15 @@ pub fn font_mapping(family: &str, glyphs: &[(char, char)]) -> Option> { let mut tables = tables_of(base)?; tables.retain(|(tag, _)| tag != b"name" && tag != b"cmap"); - // `name`: format 0, family (1) and subfamily (2), Windows Unicode English. - let strings: Vec> = [family, "Regular"].iter().map(|s| s.encode_utf16().flat_map(u16::to_be_bytes).collect()).collect(); + // `name`: format 0, family (1), subfamily (2) and PostScript name (6), Windows Unicode English. + let ps: String = family.chars().filter(char::is_ascii_alphanumeric).chain("-Regular".chars()).collect(); + let strings: Vec> = [family, "Regular", &ps].iter().map(|s| s.encode_utf16().flat_map(u16::to_be_bytes).collect()).collect(); let mut name = Vec::new(); - for v in [0u16, 2, 6 + 2 * 12] { + for v in [0u16, 3, 6 + 3 * 12] { name.extend_from_slice(&v.to_be_bytes()); } let mut at = 0usize; - for (id, s) in [1u16, 2].iter().zip(&strings) { + for (id, s) in [1u16, 2, 6].iter().zip(&strings) { for v in [3u16, 1, 0x409, *id, u16::try_from(s.len()).ok()?, u16::try_from(at).ok()?] { name.extend_from_slice(&v.to_be_bytes()); } diff --git a/crates/images/Cargo.toml b/crates/images/Cargo.toml index de878d596..0db9d190c 100644 --- a/crates/images/Cargo.toml +++ b/crates/images/Cargo.toml @@ -14,3 +14,6 @@ designcraft-fonts = { workspace = true } image = { workspace = true } tiff = { workspace = true } resvg = { workspace = true } + +[dev-dependencies] +designcraft-fonts = { workspace = true, features = ["testing"] } diff --git a/crates/images/src/lib.rs b/crates/images/src/lib.rs index b770140fd..1e81115c4 100644 --- a/crates/images/src/lib.rs +++ b/crates/images/src/lib.rs @@ -1,7 +1,7 @@ //! Placed graphics: format sniffing, sizes and decoding for the renderer and PDF export. //! Rasters go through `image` (PNG, JPEG, GIF, WebP, TIFF, BMP) or [`psd`] (Photoshop's merged -//! composite); SVG is parsed with usvg (text set in the bundled fonts) and rasterised with resvg -//! for the screen — PDF export draws the same tree as vectors. +//! composite); SVG is parsed with usvg (text set in the bundled fonts, then the shared ones) and +//! rasterised with resvg for the screen — PDF export draws the same tree as vectors. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use std::sync::{Arc, OnceLock}; @@ -67,10 +67,67 @@ fn svg_options() -> &'static usvg::Options<'static> { db.set_serif_family("Source Serif 4"); db.set_sans_serif_family("Source Sans 3"); db.set_monospace_family("JetBrains Mono"); - usvg::Options { fontdb: Arc::new(db), font_family: "Source Sans 3".into(), ..Default::default() } + let font_resolver = usvg::FontResolver { select_font: select_font(), select_fallback: select_fallback() }; + usvg::Options { fontdb: Arc::new(db), font_family: "Source Sans 3".into(), font_resolver, ..Default::default() } }) } +/// A family the SVG names that isn't bundled comes from the shared fonts (installed ones too), +/// as it would in a text frame. +fn select_font() -> usvg::FontSelectionFn<'static> { + let bundled = usvg::FontResolver::default_font_selector(); + Box::new(move |font, db| { + let fonts = designcraft_fonts::FontDb::global(); + for family in font.families() { + if let usvg::FontFamily::Named(name) = family + && !db.faces().any(|f| f.families.iter().any(|(n, _)| n.eq_ignore_ascii_case(name))) + && fonts.has_family(name) + { + for style in fonts.styles(name) { + add_face(db, fonts.face(name, &style)); + } + } + } + bundled(font, db) + }) +} + +/// Characters the chosen fonts lack (Korean, Arabic…) fall back to a shared face that has them. +fn select_fallback() -> usvg::FallbackSelectionFn<'static> { + let loaded = usvg::FontResolver::default_fallback_selector(); + Box::new(move |c, exclude, db| { + loaded(c, exclude, db).or_else(|| { + let id = add_face(db, designcraft_fonts::FontDb::global().fallback_for(c, 0, None)?)?; + // usvg asks again until we run out: a face it already tried ends the search. + (!exclude.contains(&id)).then_some(id) + }) + }) +} + +/// A shared face's bytes, handed to usvg without a copy. +struct FaceBytes(Arc); + +impl AsRef<[u8]> for FaceBytes { + fn as_ref(&self) -> &[u8] { + self.0.data() + } +} + +/// Add `face` to the SVG's font database (once) and return its id there. +fn add_face(db: &mut Arc, face: Arc) -> Option { + let same = |f: &usvg::fontdb::FaceInfo| { + f.index == face.index() + && matches!(&f.source, usvg::fontdb::Source::Binary(b) if std::ptr::eq(b.as_ref().as_ref().as_ptr(), face.data().as_ptr())) + }; + if let Some(f) = db.faces().find(|f| same(f)) { + return Some(f.id); + } + let index = face.index(); + let ids = Arc::make_mut(db).load_font_source(usvg::fontdb::Source::Binary(Arc::new(FaceBytes(face)))); + // A collection loads all its faces (skipping any it can't read): pick ours by its index. + ids.into_iter().find(|id| db.face(*id).is_some_and(|f| f.index == index)) +} + /// The parsed SVG. pub fn svg_tree(bytes: &[u8]) -> Option { usvg::Tree::from_data(bytes, svg_options()).ok() @@ -211,6 +268,43 @@ mod tests { assert!(!is_svg(b"\x89PNG")); } + /// The family of the font that sets each text glyph of `svg`, and the glyph's id. + fn glyph_families(svg: &str) -> Vec<(String, u16)> { + fn walk(g: &usvg::Group, tree: &usvg::Tree, out: &mut Vec<(String, u16)>) { + for n in g.children() { + match n { + usvg::Node::Group(g) => walk(g, tree, out), + usvg::Node::Text(t) => { + for g in t.layouted().iter().flat_map(|s| &s.positioned_glyphs) { + out.extend(tree.fontdb().face(g.font).map(|f| (f.families[0].0.clone(), g.id.0))); + } + } + _ => {} + } + } + } + let tree = svg_tree(svg.as_bytes()).unwrap(); + let mut out = Vec::new(); + walk(tree.root(), &tree, &mut out); + out + } + + #[test] + fn svg_text_uses_the_shared_fonts() { + let font = designcraft_fonts::testing::font_with("DC Test SVG Hangul", &['한', '글']).unwrap(); + designcraft_fonts::FontDb::global().add_font(font); + let text = |attrs: &str, body: &str| { + format!(r#"{body}"#) + }; + let named = r#" font-family="DC Test SVG Hangul""#; + // A family named in the SVG. + let set = glyph_families(&text(named, "한글")); + assert!(set.len() == 2 && set.iter().all(|(f, gid)| f == "DC Test SVG Hangul" && *gid != 0), "{set:?}"); + // Characters the bundled default lacks: a shared face that has them, not the default. + let set = glyph_families(&text("", "한글")); + assert!(set.len() == 2 && set.iter().all(|(f, gid)| f != "Source Sans 3" && *gid != 0), "{set:?}"); + } + /// A minimal Photoshop file: 2×1 RGB, no layers, raw merged image. fn tiny_psd() -> Vec { let mut b = Vec::new(); From 4c6aa4cd4b1b1c516cf88226a89ee760d2780140 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Fri, 9 Oct 2026 23:13:23 -0600 Subject: [PATCH 08/24] browser-correctness: fix print, startup flags, and document MIME (#117) --- Cargo.lock | 73 ++++++++++++++++++++++ apps/designcraft-web/Cargo.toml | 2 + apps/designcraft-web/src/browser_policy.rs | 67 ++++++++++++++++++++ apps/designcraft-web/src/main.rs | 6 +- apps/designcraft-web/src/web.rs | 16 +---- crates/engine/Cargo.toml | 3 + crates/engine/src/cmd/print.rs | 49 ++++++++------- crates/engine/tests/browser_print.rs | 31 +++++++++ 8 files changed, 211 insertions(+), 36 deletions(-) create mode 100644 apps/designcraft-web/src/browser_policy.rs create mode 100644 crates/engine/tests/browser_print.rs diff --git a/Cargo.lock b/Cargo.lock index cfc7d3517..6473b84f8 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -635,6 +635,12 @@ dependencies = [ "wayland-client", ] +[[package]] +name = "cast" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5" + [[package]] name = "cc" version = "1.5.1" @@ -952,6 +958,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "wasm-bindgen-test", "zip", ] @@ -1126,9 +1133,11 @@ name = "designcraft-web" version = "0.5.0" dependencies = [ "designcraft-engine", + "designcraft-format", "designcraft-ui-egui", "eframe", "egui", + "form_urlencoded", "js-sys", "log", "rfd", @@ -2550,6 +2559,16 @@ dependencies = [ "autocfg", ] +[[package]] +name = "minicov" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4869b6a491569605d66d3952bcdf03df789e5b536e5f0cf7758a7f08a55ae24d" +dependencies = [ + "cc", + "walkdir", +] + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -2673,6 +2692,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -3022,6 +3050,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "oorandom" +version = "11.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" + [[package]] name = "open" version = "5.4.4" @@ -4746,6 +4780,45 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-bindgen-test" +version = "0.3.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae7499dfd45780a0a91d7ee6bb9ac51970a4479a41a89da443fdda5a39547d42" +dependencies = [ + "async-trait", + "cast", + "js-sys", + "libm", + "minicov", + "nu-ansi-term", + "num-traits", + "oorandom", + "serde", + "serde_json", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-bindgen-test-macro", + "wasm-bindgen-test-shared", +] + +[[package]] +name = "wasm-bindgen-test-macro" +version = "0.3.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "wasm-bindgen-test-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f692aa943ccd88363733b77063f32cfed5bc6cbea8e6e8b251b302f881606fe" + [[package]] name = "wayland-backend" version = "0.3.17" diff --git a/apps/designcraft-web/Cargo.toml b/apps/designcraft-web/Cargo.toml index d27b3c416..75775c31e 100644 --- a/apps/designcraft-web/Cargo.toml +++ b/apps/designcraft-web/Cargo.toml @@ -15,6 +15,8 @@ path = "src/main.rs" [dependencies] designcraft-engine = { workspace = true } +designcraft-format = { workspace = true } +form_urlencoded = "1.2" designcraft-ui-egui = { workspace = true } egui = { workspace = true } log = { workspace = true } diff --git a/apps/designcraft-web/src/browser_policy.rs b/apps/designcraft-web/src/browser_policy.rs new file mode 100644 index 000000000..524df6cc5 --- /dev/null +++ b/apps/designcraft-web/src/browser_policy.rs @@ -0,0 +1,67 @@ +//! Pure browser startup and download metadata 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. +pub(crate) fn has_query_flag(query: &str, flag: &str) -> bool { + let query = query.strip_prefix('?').unwrap_or(query); + form_urlencoded::parse(query.as_bytes()).any(|(key, _)| key == flag) +} + +pub(crate) fn mime_for(name: &str) -> &'static str { + match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() { + Some("png") => "image/png", + Some("jpg" | "jpeg") => "image/jpeg", + Some("pdf") => "application/pdf", + Some("designcraft") => designcraft_format::MIME, + Some("idml") => "application/vnd.adobe.indesign-idml-package", + _ => "application/octet-stream", + } +} + +#[cfg(test)] +mod tests { + use super::{has_query_flag, mime_for}; + + #[test] + fn startup_flags_match_complete_decoded_keys() { + for flag in ["sample", "webgl"] { + for query in [format!("?{flag}"), format!("?{flag}=false"), format!("?{flag}=1&{flag}=0"), format!("?other=value&{flag}")] { + assert!(has_query_flag(&query, flag), "{query}"); + } + for query in [ + String::new(), + format!("?note={flag}"), + format!("?{flag}d=1"), + format!("?note=not_a_{flag}"), + "?note=%73ample%77ebgl".to_string(), + format!("?{flag}+extra=1"), + format!("?{flag}%26extra=1"), + format!("?{flag}%3Dextra=1"), + ] { + assert!(!has_query_flag(&query, flag), "{query}"); + } + } + assert!(has_query_flag("?webgl&sample", "sample")); + assert!(has_query_flag("?webgl&sample", "webgl")); + assert!(has_query_flag("?%73ample", "sample")); + assert!(has_query_flag("?%77ebgl", "webgl")); + assert!(!has_query_flag("?Sample&WEBGL", "sample")); + assert!(!has_query_flag("?Sample&WEBGL", "webgl")); + } + + #[test] + fn download_mime_matches_native_package_and_existing_exports() { + for (name, expected) in [ + ("Quarterly.designcraft", designcraft_format::MIME), + ("日本語.multi.DEsignCraft", designcraft_format::MIME), + ("page.pdf", "application/pdf"), + ("page.png", "image/png"), + ("page.jpg", "image/jpeg"), + ("page.JPEG", "image/jpeg"), + ("document.idml", "application/vnd.adobe.indesign-idml-package"), + ("unknown.bin", "application/octet-stream"), + ] { + assert_eq!(mime_for(name), expected, "{name}"); + } + } +} diff --git a/apps/designcraft-web/src/main.rs b/apps/designcraft-web/src/main.rs index ed05d5950..527baff47 100644 --- a/apps/designcraft-web/src/main.rs +++ b/apps/designcraft-web/src/main.rs @@ -12,9 +12,13 @@ //! - dropped files are read asynchronously by `web::WebShell` and delivered through the inbox. //! //! URL query flags: `?webgl` forces the WebGL2 backend instead of WebGPU; `?sample` opens the -//! sample magazine on start. +//! sample magazine on start. Flags match case-sensitive, percent-decoded query keys; values +//! are ignored and repeated keys have the same presence semantics (`?sample=false` enables it). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#[cfg(any(target_arch = "wasm32", test))] +mod browser_policy; + #[cfg(target_arch = "wasm32")] mod web; diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index c0466b691..3879f0839 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -1,5 +1,6 @@ //! The browser shell: web `Services`, drag-and-drop, and the eframe web runner. +use super::browser_policy::{has_query_flag, mime_for}; use designcraft_engine::Session; use designcraft_ui_egui::{DesignApp, Inbox, Services}; use wasm_bindgen::JsCast as _; @@ -41,7 +42,7 @@ pub fn start() { return; }; let mut options = eframe::WebOptions::default(); - if query().contains("webgl") + if has_query_flag(&query(), "webgl") && let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.instance_descriptor.backends = eframe::wgpu::Backends::GL; @@ -56,7 +57,7 @@ pub fn start() { } let inbox: Inbox = Inbox::default(); let mut app = DesignApp::new(Session::new(), services(inbox.clone(), cc.egui_ctx.clone())); - if query().contains("sample") { + if has_query_flag(&query(), "sample") { let _ = app.run("file.newSample", serde_json::json!({})); } Ok(Box::new(WebShell { app, inbox })) @@ -173,14 +174,3 @@ fn download(path: &str, bytes: &[u8]) -> Result<(), String> { window.set_timeout_with_callback_and_timeout_and_arguments_0(revoke.unchecked_ref(), 10_000).map_err(js)?; Ok(()) } - -fn mime_for(name: &str) -> &'static str { - match name.rsplit('.').next().map(str::to_ascii_lowercase).as_deref() { - Some("png") => "image/png", - Some("jpg" | "jpeg") => "image/jpeg", - Some("pdf") => "application/pdf", - Some("designcraft") => "application/json", - Some("idml") => "application/vnd.adobe.indesign-idml-package", - _ => "application/octet-stream", - } -} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index ff02d62b8..241fd281a 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -36,3 +36,6 @@ hayro-syntax = "0.7.2" hayro-interpret = { version = "0.7.0", default-features = false, features = ["embed-fonts"] } hayro-cmap = "0.1" kurbo = { workspace = true } + +[target.'cfg(target_arch = "wasm32")'.dev-dependencies] +wasm-bindgen-test = "0.3" diff --git a/crates/engine/src/cmd/print.rs b/crates/engine/src/cmd/print.rs index bbae1b38a..b944b6235 100644 --- a/crates/engine/src/cmd/print.rs +++ b/crates/engine/src/cmd/print.rs @@ -2,8 +2,12 @@ use serde_json::{Value, json}; -use super::{CommandSpec, bad, cmd, has_doc, str_param}; -use crate::{EngineError, Result, Session}; +#[cfg(not(target_arch = "wasm32"))] +use super::str_param; +use super::{CommandSpec, bad, cmd, has_doc}; +#[cfg(not(target_arch = "wasm32"))] +use crate::EngineError; +use crate::{Result, Session}; pub fn specs() -> Vec { vec![ @@ -39,31 +43,32 @@ fn printers() -> Value { fn print(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let opts = super::export::options(p, d.page_count())?; - let copies = p.get("copies").and_then(Value::as_u64).unwrap_or(1).clamp(1, 999); - let printer = str_param(p, "printer").map(str::to_string); - let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false); - let pdf = designcraft_pdf::export_pdf(d, &s.cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?; - let file = std::env::temp_dir().join(format!("designcraft-print-{}-{}.pdf", std::process::id(), d.title.replace(['/', '\\'], "_"))); - let mut cmd: Vec = vec!["lpr".into()]; - if let Some(pr) = &printer { - cmd.extend(["-P".into(), pr.clone()]); - } - if copies > 1 { - cmd.extend(["-#".into(), copies.to_string()]); - } - cmd.extend(["-T".into(), d.title.clone(), file.to_string_lossy().to_string()]); - let pages = opts.pages.as_ref().map_or(d.page_count(), |v| v.len()); - let out = json!({"printer": printer, "copies": copies, "pages": pages, "command": cmd, "bytes": pdf.len()}); - if dry { - return Ok(out); - } #[cfg(target_arch = "wasm32")] { - let _ = pdf; + // Even a dry run cannot construct a native spool command in the browser. + let _ = opts; Err(bad("file.print", "printing isn't available on the web: export a PDF and print it")) } #[cfg(not(target_arch = "wasm32"))] { + let copies = p.get("copies").and_then(Value::as_u64).unwrap_or(1).clamp(1, 999); + let printer = str_param(p, "printer").map(str::to_string); + let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false); + let pdf = designcraft_pdf::export_pdf(d, &s.cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?; + let file = std::env::temp_dir().join(format!("designcraft-print-{}-{}.pdf", std::process::id(), d.title.replace(['/', '\\'], "_"))); + let mut cmd: Vec = vec!["lpr".into()]; + if let Some(pr) = &printer { + cmd.extend(["-P".into(), pr.clone()]); + } + if copies > 1 { + cmd.extend(["-#".into(), copies.to_string()]); + } + cmd.extend(["-T".into(), d.title.clone(), file.to_string_lossy().to_string()]); + let pages = opts.pages.as_ref().map_or(d.page_count(), |v| v.len()); + let out = json!({"printer": printer, "copies": copies, "pages": pages, "command": cmd, "bytes": pdf.len()}); + if dry { + return Ok(out); + } std::fs::write(&file, &pdf).map_err(|e| EngineError::Other(format!("{}: {e}", file.display())))?; let st = std::process::Command::new(&cmd[0]).args(&cmd[1..]).output().map_err(|e| bad("file.print", format!("lpr: {e}")))?; if !st.status.success() { @@ -73,7 +78,7 @@ fn print(s: &mut Session, p: &Value) -> Result { } } -#[cfg(test)] +#[cfg(all(test, not(target_arch = "wasm32")))] mod tests { use serde_json::json; diff --git a/crates/engine/tests/browser_print.rs b/crates/engine/tests/browser_print.rs new file mode 100644 index 000000000..fda224b90 --- /dev/null +++ b/crates/engine/tests/browser_print.rs @@ -0,0 +1,31 @@ +//! Browser Print must reject native spooler operations without trapping the editor. +#![cfg(target_arch = "wasm32")] + +use designcraft_engine::Session; +use serde_json::json; +use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure}; + +wasm_bindgen_test_configure!(run_in_browser); + +fn print_is_safe(dry_run: bool) { + let mut session = Session::new(); + session.execute("file.new", &json!({"pages": 1})).unwrap(); + let error = session.execute("file.print", &json!({"dryRun": dry_run})).unwrap_err().to_string(); + assert!(error.contains("printing isn't available on the web"), "{error}"); + assert!(error.contains("export a PDF"), "{error}"); + session.execute("frame.create", &json!({"rect": [36, 36, 100, 100], "content": "text"})).unwrap(); + let exported = session.execute("file.exportPdf", &json!({})).unwrap(); + assert!(exported["bytes"].as_u64().unwrap() > 500); + assert_eq!(exported["pages"], 1); + assert!(session.execute("file.print", &json!({"pages": "9", "dryRun": dry_run})).is_err()); +} + +#[wasm_bindgen_test] +fn print_confirmation_preserves_editing_and_pdf_export() { + print_is_safe(false); +} + +#[wasm_bindgen_test] +fn print_dry_run_is_also_unsupported_without_native_operations() { + print_is_safe(true); +} From fc2739a8cdeeaa0f0fd5153a6108da5ab2db3605 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Fri, 9 Oct 2026 23:13:29 -0600 Subject: [PATCH 09/24] #61: honor MCP typing, story and page contracts (#118) --- crates/engine/src/cmd/text.rs | 18 ++++- crates/mcp/src/headless.rs | 18 ++++- crates/mcp/src/tests.rs | 84 +++++++++++++++++++++++ crates/mcp/src/tools.rs | 19 ++++-- crates/ui-egui/src/control.rs | 125 ++++++++++++++++++++++++++++++++-- crates/ui-egui/src/menus.rs | 2 +- 6 files changed, 250 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/text.rs b/crates/engine/src/cmd/text.rs index a75d6d473..552ce519a 100644 --- a/crates/engine/src/cmd/text.rs +++ b/crates/engine/src/cmd/text.rs @@ -114,8 +114,8 @@ pub fn specs() -> Vec { cmd!(query "story.get", "Get Story", [], None, "{story? | frame?} → text, frames, paragraphs, vertical, overset", has_doc, |s, p| { let st = s.doc()?; let sid = story_of(s, p).ok_or_else(|| bad("story.get", "no story"))?; + let mut v = st.doc.story_summary(sid).ok_or(designcraft_doc::DocError::NoStory(sid))?; let cs = s.cache.get(&st.doc, sid, None); - let mut v = st.doc.story_summary(sid).unwrap_or_default(); v["overset"] = json!(cs.overset_at); v["lines"] = json!(cs.line_count()); Ok(v) @@ -1638,3 +1638,19 @@ mod vertical_caret_tests { assert_eq!(mv(&mut s, "up", false, false), 3 * c); } } + +#[cfg(test)] +mod story_query_contract_tests { + use serde_json::json; + #[test] + fn missing_story_errors_but_valid_empty_and_selected_stories_succeed() { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({})).unwrap(); + assert!(s.execute("story.get", &json!({"story":999})).unwrap_err().to_string().contains("no such story")); + let f = s.execute("frame.create", &json!({"rect":[36,36,300,200],"content":"text"})).unwrap(); + assert_eq!(s.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], ""); + assert_eq!(s.execute("story.get", &json!({"frame":f["id"]})).unwrap()["text"], ""); + s.execute("text.select", &json!({"story":f["story"],"anchor":0})).unwrap(); + assert_eq!(s.execute("story.get", &json!({})).unwrap()["text"], ""); + } +} diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index ee9d11d19..aea3e8763 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -180,7 +180,7 @@ impl Headless { fn text(&mut self, p: &Value) -> Result { let t = s(p, "text").ok_or("missing `text`")?; - if !self.session.wants_text() { + if self.session.active().is_none_or(|st| st.selection.text.is_none_or(|t| st.doc.text_story(t.story, t.cell).is_none())) { return Err("no text insertion point: click into a text frame with the type tool first (pointer with tool \"type\"), \ or select text with execute text.select, or use set_story_text" .into()); @@ -191,7 +191,7 @@ impl Headless { fn render(&mut self, p: &Value) -> Result { let st = self.session.active().ok_or("no document open")?; - let page = p.get("page").and_then(Value::as_u64).unwrap_or(0) as usize; + let page = page_index(p, st.doc.page_count())?; let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0).clamp(0.05, 16.0); let bleed = p.get("bleed").and_then(Value::as_bool).unwrap_or(false); let img = self @@ -213,7 +213,7 @@ impl Headless { fn export(&mut self, p: &Value) -> Result { let path = s(p, "path").ok_or("missing `path`")?; let st = self.session.active().ok_or("no document open")?; - let page = p.get("page").and_then(Value::as_u64).unwrap_or(0) as usize; + let page = page_index(p, st.doc.page_count())?; let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(2.0).clamp(0.05, 16.0); let img = self .renderer @@ -263,3 +263,15 @@ impl Backend for Headless { "headless (in-process engine, no window)".into() } } + +/// A supplied page must be a representable unsigned index; only omission selects page zero. +fn page_index(p: &Value, count: usize) -> Result { + let page = match p.get("page") { + None => 0, + Some(v) => v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`page` must be a nonnegative integer representable as a page index")?, + }; + if page >= count { + return Err(format!("no page {page} (the document has {count} pages, indices are 0-based)")); + } + Ok(page) +} diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 2804d13fb..3051a5ad4 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -416,3 +416,87 @@ fn batch_steps_use_earlier_results() { ); assert_eq!(v["completed"], 2); } + +#[test] +fn explicit_typing_honors_caret_range_and_undo_without_changing_shortcuts() { + let mut s = server(); + assert_eq!(call(&mut s, "type_text", json!({"text":"X"}))["isError"], true); + let f = ok(&mut s, "execute", json!({"command":"frame.create","params":{"rect":[36,36,300,200],"content":"text","text":"Hello"}})); + let story = f["story"].as_u64().unwrap(); + for (anchor, focus, expected) in [(5, 5, "HelloX"), (0, 5, "X")] { + ok(&mut s, "set_story_text", json!({"story":story,"text":"Hello"})); + ok(&mut s, "execute", json!({"command":"text.select","params":{"story":story,"anchor":anchor,"focus":focus}})); + ok(&mut s, "type_text", json!({"text":"X"})); + assert_eq!(ok(&mut s, "get_story", json!({"story":story}))["text"], expected); + ok(&mut s, "execute", json!({"command":"edit.undo"})); + assert_eq!(ok(&mut s, "get_story", json!({"story":story}))["text"], "Hello"); + } + ok(&mut s, "execute", json!({"command":"text.placeCaret","params":{"frame":f["id"],"point":[100,50]}})); + ok(&mut s, "type_text", json!({"text":"X"})); + assert_eq!(ok(&mut s, "get_story", json!({"story":story}))["text"], "HelloX"); + assert_eq!(ok(&mut s, "key", json!({"key":"T"}))["handledBy"], "tool.select"); + assert_eq!(ok(&mut s, "get_story", json!({"story":story}))["text"], "HelloX"); +} + +#[test] +fn story_queries_distinguish_missing_from_empty() { + let mut s = server(); + assert_eq!(call(&mut s, "get_story", json!({"story":999}))["isError"], true); + let f = ok(&mut s, "execute", json!({"command":"frame.create","params":{"rect":[36,36,300,200],"content":"text"}})); + assert_eq!(ok(&mut s, "get_story", json!({"story":f["story"]}))["text"], ""); + assert_eq!(ok(&mut s, "get_story", json!({"frame":f["id"]}))["text"], ""); + ok(&mut s, "execute", json!({"command":"text.select","params":{"story":f["story"],"anchor":0}})); + assert_eq!(ok(&mut s, "get_story", json!({}))["text"], ""); +} + +#[test] +fn page_contract_rejects_supplied_invalid_values_without_writes() { + let mut s = server(); + ok(&mut s, "new_document", json!({"sample":true})); + let path = tmp("page-contract.png"); + for tool in ["export_png", "render_page"] { + for page in + [json!(-1), json!(-2), json!(1.5), Value::Null, json!("0"), json!(true), json!(u64::MAX), json!(18446744073709551616_f64), json!(99)] + { + std::fs::write(&path, b"KEEP").unwrap(); + let args = json!({"page":page,"path":path,"scale":0.1}); + assert_eq!(call(&mut s, tool, args)["isError"], true, "{tool}: {page}"); + assert_eq!(std::fs::read(&path).unwrap(), b"KEEP"); + } + } + let first = image_of(&call(&mut s, "render_page", json!({"page":0,"scale":0.1}))); + let next = image_of(&call(&mut s, "render_page", json!({"page":1,"scale":0.1}))); + assert_ne!(first, next); + assert_eq!(first, image_of(&call(&mut s, "render_page", json!({"scale":0.1})))); + ok(&mut s, "export_png", json!({"page":1,"path":path,"scale":0.1})); + assert_eq!(std::fs::read(&path).unwrap(), next); + ok(&mut s, "export_png", json!({"path":path,"scale":0.1})); + assert_eq!(std::fs::read(&path).unwrap(), first); + for tool in ["render_page", "export_png"] { + let definition = tool_definitions().into_iter().find(|v| v["name"] == tool).unwrap(); + assert_eq!(definition["inputSchema"]["properties"]["page"]["minimum"], 0); + } + let mut b = Headless::with_document(); + for method in ["ui.render", "app.export"] { + for page in [json!(-1), Value::Null, json!("0"), json!(99)] { + std::fs::write(&path, b"KEEP").unwrap(); + assert!(b.call(method, json!({"page":page,"path":path,"scale":0.1})).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), b"KEEP"); + } + std::fs::remove_file(&path).unwrap(); + assert!(b.call(method, json!({"page":-1,"path":path,"scale":0.1})).is_err()); + assert!(!path.exists()); + } +} + +#[test] +fn explicit_typing_rejects_stale_selection_and_closed_document() { + let mut b = Headless::with_document(); + let f = b.session.execute("frame.create", &json!({"rect":[36,36,300,200],"content":"text","text":"Hello"})).unwrap(); + b.session.execute("text.select", &json!({"story":f["story"],"anchor":5})).unwrap(); + b.session.active_mut().unwrap().selection.text.as_mut().unwrap().story.0 = 999; + assert!(b.call("ui.text", json!({"text":"X"})).is_err()); + assert_eq!(b.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "Hello"); + b.session.execute("file.close", &json!({})).unwrap(); + assert!(b.call("ui.text", json!({"text":"X"})).is_err()); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index dc2604c5b..0ad996223 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -223,7 +223,7 @@ pub fn tool_definitions() -> Vec { also write it to `path`.", obj( json!({ - "page": int("Page index, 0-based (default 0; in the desktop app default = the current page)"), + "page": {"type": "integer", "minimum": 0, "description": "Page index, 0-based (default 0; in the desktop app default = the current page)"}, "scale": num("Pixels per point (default 1 = 72 ppi)"), "bleed": boolean("Include the bleed area"), "path": string("Also write the PNG here"), @@ -237,7 +237,7 @@ pub fn tool_definitions() -> Vec { "Export PNG", "Export one page as a PNG (or JPEG if the path ends in .jpg) file. Returns the path and pixel size.", obj( - json!({"path": string("Destination file"), "page": int("Page index, 0-based (default 0)"), "scale": num("Pixels per point (default 2)")}), + json!({"path": string("Destination file"), "page": {"type": "integer", "minimum": 0, "description": "Page index, 0-based (default 0; in the desktop app default = the current page)"}, "scale": num("Pixels per point (default 2)")}), &["path"], ), false, @@ -303,7 +303,7 @@ pub fn tool_definitions() -> Vec { tool( "type_text", "Type text", - "Type text at the text insertion point (as the keyboard would with the type tool), or into the focused dialog field in \ + "Type text at the text insertion point, independently of the active tool, or into the focused dialog field in \ the desktop app. Put a caret first with pointer (tool \"type\") or execute text.placeCaret / text.select.", obj(json!({"text": string("Text to type (\\n = new paragraph)")}), &["text"]), false, @@ -409,6 +409,15 @@ fn pick(a: &Args, keys: &[&str]) -> Value { Value::Object(keys.iter().filter_map(|k| a.get(*k).filter(|v| !v.is_null()).map(|v| (k.to_string(), v.clone()))).collect()) } +/// Page omission selects a default, but an explicitly supplied null must reach validation. +fn page_params(a: &Args, keys: &[&str]) -> Value { + let mut p = pick(a, keys); + if let Some(page) = a.get("page") { + p["page"] = page.clone(); + } + p +} + fn command_params(v: Option<&Value>) -> Result { match v { None | Some(Value::Null) => Ok(json!({})), @@ -463,7 +472,7 @@ fn story_id(b: &mut dyn Backend, a: &Args) -> Result { } fn render_page(b: &mut dyn Backend, a: &Args) -> Result { - let r = b.call("ui.render", pick(a, &["page", "scale", "bleed"]))?; + let r = b.call("ui.render", page_params(a, &["page", "scale", "bleed"]))?; let b64 = r.get("pngBase64").and_then(Value::as_str).ok_or("renderer returned no image")?.to_string(); let path = a.get("path").and_then(Value::as_str); if let Some(path) = path { @@ -550,7 +559,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result render_page(b, a), "export_png" => { req_str(a, "path")?; - j(b.call("app.export", pick(a, &["path", "page", "scale"]))?) + j(b.call("app.export", page_params(a, &["path", "page", "scale"]))?) } "screenshot" => screenshot(b, a), "select_tool" => j(b.call("ui.tool.select", json!({"tool": req_str(a, "tool")?}))?), diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 32450259c..e81e4c190 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -8,7 +8,8 @@ //! - `ui.tool.select {tool}`, `ui.tool.list` //! - `ui.pointer {events:[{kind: down|drag|up|move|doubleclick, x, y, space?: "doc"|"screen"}], mods?}`: //! drive the active tool through the same path as the mouse -//! - `ui.key {key, shift?, alt?, cmd?}` / `ui.text {text}`: synthetic keyboard input +//! - `ui.key {key, shift?, alt?, cmd?}`: synthetic keyboard input +//! - `ui.text {text}`: insert at the explicit caret, or type into a focused UI field //! - `ui.move {x, y}` / `ui.click {x, y, button?, count?, shift?…}` / `ui.drag {x, y, toX, toY, steps?}`: //! real egui pointer input in screen points (reaches every widget: panels, flyouts, dialogs) //! - `ui.set {brightness?, panel?, dockTab?, rulers?, outline?, …}` @@ -216,9 +217,19 @@ pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) -> ok(Value::Null) } "ui.text" => { - app.synthetic.push(egui::Event::Text(s("text").unwrap_or("").to_string())); - ctx.request_repaint(); - ok(Value::Null) + let Some(text) = s("text") else { return err("missing `text`") }; + // Focused widgets retain the synthetic keyboard route. Document automation uses + // the explicit caret independently of the active tool, unlike ordinary typing. + if ctx.text_edit_focused() || app.ui.dialog.is_some() || app.ui.palette.is_some() { + app.synthetic.push(egui::Event::Text(text.to_string())); + ctx.request_repaint(); + ok(Value::Null) + } else { + if app.session.active().is_none_or(|st| st.selection.text.is_none_or(|t| st.doc.text_story(t.story, t.cell).is_none())) { + return err("no valid text insertion point: use text.select or text.placeCaret first"); + } + wrap(app.run("text.insert", json!({"text": text}))) + } } "ui.set" => { let mut r = Ok(Value::Null); @@ -313,7 +324,10 @@ pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) -> } "ui.render" => { let Some(st) = app.session.active() else { return err("no document") }; - let page = p.get("page").and_then(Value::as_u64).map(|v| v as usize).or_else(|| crate::canvas::current_page(app)).unwrap_or(0); + let page = match page_index(p, crate::canvas::current_page(app).unwrap_or(0), st.doc.page_count()) { + Ok(page) => page, + Err(e) => return err(e), + }; let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(1.0); let Some(img) = app.canvas.renderer.render_page( &st.doc, @@ -336,7 +350,7 @@ pub fn handle(app: &mut DesignApp, ctx: &egui::Context, req: &ControlRequest) -> } "app.open" => wrap(app.run("file.open", json!({"path": s("path")}))), "app.save" => wrap(app.run("file.save", json!({"path": s("path")}))), - "app.export" => wrap(app.run("app.exportPng", json!({"path": s("path"), "page": p.get("page"), "scale": p.get("scale")}))), + "app.export" => wrap(app.run("app.exportPng", p.clone())), "app.quit" => { ctx.send_viewport_cmd(egui::ViewportCommand::Close); ok(Value::Null) @@ -361,3 +375,102 @@ pub fn save_screenshot(app: &mut DesignApp, image: &egui::ColorImage, path: Opti None => json!({"ok": false, "error": "no writer configured"}), } } + +/// Parse explicit page indices without treating invalid values as omission. +pub(crate) fn page_index(p: &Value, default: usize, count: usize) -> Result { + let page = match p.get("page") { + None => default, + Some(v) => v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`page` must be a nonnegative integer representable as a page index")?, + }; + if page >= count { + return Err(format!("no page {page} (the document has {count} pages, indices are 0-based)")); + } + Ok(page) +} + +#[cfg(test)] +mod automation_contract_tests { + use super::*; + fn app() -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({"pages":2})).unwrap(); + app + } + fn call(app: &mut DesignApp, ctx: &egui::Context, method: &str, params: Value) -> Value { + let (req, _) = ControlRequest::new(method, params); + match handle(app, ctx, &req) { + Outcome::Done(v) => v, + Outcome::Screenshot { .. } => panic!("unexpected screenshot"), + } + } + fn frame(app: &mut DesignApp, ctx: &egui::Context, events: Vec) { + let mut output = ctx.run_ui( + egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }, + |ui| { + app.logic(ui.ctx()); + app.ui(ui); + }, + ); + output.textures_delta.clear(); + } + #[test] + fn control_typing_uses_explicit_caret_but_retains_widget_events() { + let mut app = app(); + let ctx = egui::Context::default(); + assert_eq!(call(&mut app, &ctx, "ui.text", json!({"text":"X"}))["ok"], false); + let f = app.session.execute("frame.create", &json!({"rect":[36,36,300,200],"content":"text","text":"Hello"})).unwrap(); + app.session.execute("text.select", &json!({"story":f["story"],"anchor":5})).unwrap(); + assert_eq!(app.session.tool_id(), "selection"); + assert_eq!(call(&mut app, &ctx, "ui.text", json!({"text":"X"}))["ok"], true); + assert_eq!(app.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "HelloX"); + app.session.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(app.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "Hello"); + app.select_tool("type"); + assert!(app.session.wants_text(), "the document would receive ordinary typing without widget focus"); + app.ui.palette = Some(String::new()); + for _ in 0..3 { + frame(&mut app, &ctx, vec![]); + } + assert!(ctx.text_edit_focused()); + assert_eq!(call(&mut app, &ctx, "ui.text", json!({"text":"field"}))["ok"], true); + let events = std::mem::take(&mut app.synthetic); + frame(&mut app, &ctx, events); + assert_eq!(app.ui.palette.as_deref(), Some("field")); + assert_eq!(app.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "Hello"); + } + #[test] + fn control_pages_validate_before_writer_and_preserve_omission() { + let mut app = app(); + let ctx = egui::Context::default(); + let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let sink = writes.clone(); + app.services.write = Some(Box::new(move |_, bytes| { + sink.lock().unwrap().push(bytes.to_vec()); + Ok(()) + })); + app.session.execute("frame.create", &json!({"rect":[36,36,300,200]})).unwrap(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))); + crate::canvas::go_to_page(&mut app, 1); + assert_eq!(crate::canvas::current_page(&app), Some(1)); + for method in ["ui.render", "app.export"] { + for page in + [json!(-1), json!(-2), json!(1.5), Value::Null, json!("0"), json!(true), json!(u64::MAX), json!(18446744073709551616_f64), json!(99)] + { + assert_eq!(call(&mut app, &ctx, method, json!({"page":page,"path":"unchanged.png","scale":0.1}))["ok"], false, "{method}: {page}"); + assert!(writes.lock().unwrap().is_empty()); + } + assert_eq!(call(&mut app, &ctx, method, json!({"path":"omitted.png","scale":0.1}))["ok"], true); + assert_eq!(call(&mut app, &ctx, method, json!({"page":1,"path":"explicit.png","scale":0.1}))["ok"], true); + let mut bytes = writes.lock().unwrap(); + assert_eq!(bytes.len(), 2); + assert_eq!(bytes[0], bytes[1]); + bytes.clear(); + } + assert!(app.run("app.exportPng", json!({"page":Value::Null,"path":"unchanged.png"})).is_err()); + assert!(writes.lock().unwrap().is_empty()); + } +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index be0b0303a..2a04e7cdd 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1393,7 +1393,7 @@ fn download_document(app: &mut DesignApp) -> Result { fn export_png(app: &mut DesignApp, p: &Value) -> Result { let st = app.session.active().ok_or("no document")?; - let page = p.get("page").and_then(Value::as_u64).map(|v| v as usize).or_else(|| crate::canvas::current_page(app)).unwrap_or(0); + let page = crate::control::page_index(p, crate::canvas::current_page(app).unwrap_or(0), st.doc.page_count())?; let scale = p.get("scale").and_then(Value::as_f64).unwrap_or(2.0); let mut r = designcraft_render::Renderer::new(); let img = r From 691d0de18353b5fd19a2683476e67e6812c40099 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Fri, 9 Oct 2026 23:13:35 -0600 Subject: [PATCH 10/24] #72: preserve typed generic dialog values (#120) --- crates/ui-egui/src/dialogs.rs | 75 +++++++++++++++++++++++++++++++++-- 1 file changed, 72 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 450e64c2f..f44503f7c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -1700,10 +1700,12 @@ pub fn confirm(app: &mut DesignApp) -> Result { let parsed = serde_json::from_str::(v).ok().filter(|x| !x.is_string()); p.insert(f.key, parsed.unwrap_or_else(|| json!(v))); } - Some(Value::Bool(b)) => { - p.insert(f.key, json!(b)); + Some(Value::String(_)) | None => {} + Some(value) => { + // Control/MCP callers can supply JSON directly. Preserve its type, + // including explicit null, for the command to interpret. + p.insert(f.key, value.clone()); } - _ => {} } } let r = app.run(cid, Value::Object(p)); @@ -2671,6 +2673,73 @@ fn find_font(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { mod tests { use super::*; + fn command_app(id: &str, fields: Value) -> DesignApp { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.dialog = Some(Dialog::new(&format!("cmd:{id}"), fields)); + app + } + + #[test] + fn generic_new_document_preserves_typed_values_and_text_entry() { + for pages in [json!(2), json!(" 2 ")] { + let mut app = command_app( + "file.new", + json!({ + "preset": "A4", "pages": pages, "facingPages": false, "gutter": 0, + "margins": {"top": 10, "bottom": 20, "inside": 30, "outside": 40}, + "title": " ", "status": "internal", "primaryTextFrame": true + }), + ); + confirm(&mut app).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.page_count(), 2); + assert!(!doc.settings.facing_pages); + assert!(doc.title.starts_with("Untitled-")); + for page in doc.spreads.iter().flat_map(|s| &s.pages) { + assert!((page.width - 595.2755905511812).abs() < 0.01); + assert!((page.height - 841.8897637795277).abs() < 0.01); + assert_eq!(page.columns.gutter, 0.0); + assert_eq!(page.margins.top, 10.0); + assert_eq!(page.margins.outside, 40.0); + } + assert!(doc.spreads.iter().all(|s| s.items.is_empty()), "undocumented fields stay excluded"); + assert!(app.ui.dialog.is_none()); + } + } + + #[test] + fn generic_command_preserves_array_geometry() { + let mut app = command_app("file.new", json!({})); + confirm(&mut app).unwrap(); + app.ui.dialog = Some(Dialog::new("cmd:frame.create", json!({"rect": [10, 20, 110, 220]}))); + confirm(&mut app).unwrap(); + let doc = &app.session.active().unwrap().doc; + let item = doc.spreads.iter().flat_map(|s| &s.items).next().unwrap(); + assert_eq!(item.bounds(), designcraft_geom::Rect::new(10.0, 20.0, 110.0, 220.0)); + } + + #[test] + fn generic_explicit_null_uses_the_commands_existing_semantics() { + // file.new accepts null width by using the selected preset's width. + for width in [Value::Null, json!("null")] { + let mut app = command_app("file.new", json!({"preset": "A4", "width": width, "title": " Sample layout "})); + confirm(&mut app).unwrap(); + let doc = &app.session.active().unwrap().doc; + assert_eq!(doc.title, "Sample layout"); + assert!((doc.settings.page_width - 595.2755905511812).abs() < 0.01); + } + } + + #[test] + fn generic_invalid_number_retains_dialog_without_creating_document() { + let mut app = command_app("file.new", json!({"width": 0})); + assert!(confirm(&mut app).is_err()); + assert!(app.session.active().is_none()); + let dialog = app.ui.dialog.as_ref().unwrap(); + assert_eq!(dialog.fields["width"], 0); + assert!(dialog.fields["status"].as_str().unwrap().contains("page size out of range")); + } + #[test] fn parses_command_params() { let f = command_fields("{name, type: custom|lastPageNumber|chapterNumber, text?, rule?: {on, weight}, flag?: bool} — creates"); From 3033c8cc64d23c88c7171758c9e6cd0969a95a05 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:13:42 -0400 Subject: [PATCH 11/24] CLI: export options after the last export are an error; MCP and README docs match the code (#127) * CLI: run rejects an export option with no export after it (#67) --page, --scale and --pdf-options apply to the exports that follow them; one given after the last --export or --all-pages did nothing and said nothing. The usage text and docs/agents.md say so. * MCP: document that text offsets and story lengths are UTF-8 bytes (#68) * MCP: docs name the UI-only commands precisely; app.links works headless (#62) * README: PDF and EPUB export ship (#60) --- README.md | 3 ++- apps/designcraft-cli/src/main.rs | 34 +++++++++++++++++++++++++++++-- apps/designcraft-cli/tests/cli.rs | 22 ++++++++++++++++++++ crates/mcp/src/tools.rs | 12 ++++++----- docs/agents.md | 4 ++++ docs/mcp.md | 10 ++++++++- 6 files changed, 76 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 41af2b453..c6c08faf6 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,8 @@ by its own renderer. Try it yourself with `File → New → Sample Document`, or Line breaks are identical on screen and in PDF. - **Fast.** Multithreaded SIMD rendering (vello_cpu), copy-on-write documents with O(1) undo snapshots, and cached composition. -- **Open.** A documented native format, IDML import and export, PNG export, and PDF on the roadmap. +- **Open.** A documented native format, IDML import and export, and PNG, PDF (PDF/X-4, PDF/A-2b) + and EPUB export. No subscription, no licence server, no telemetry. - **Agent-native.** Every menu item, tool gesture, panel control and dialog can be driven over a JSON control channel and an **MCP server**, so Claude and other agents can lay out and edit diff --git a/apps/designcraft-cli/src/main.rs b/apps/designcraft-cli/src/main.rs index 9e9eba25d..a564befc2 100644 --- a/apps/designcraft-cli/src/main.rs +++ b/apps/designcraft-cli/src/main.rs @@ -1,7 +1,8 @@ //! Headless DesignCraft. //! //! ```text -//! designcraft-cli run [--in FILE.designcraft|FILE.idml | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--export OUT.png|.jpg|.pdf|.designcraft|.idml|.epub] [--pdf-options JSON] [--all-pages DIR] +//! designcraft-cli run [--in FILE.designcraft|FILE.idml | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT.png|.jpg|.pdf|.designcraft|.idml|.epub] [--all-pages DIR] +//! # --page, --scale and --pdf-options apply to the exports that follow them //! designcraft-cli commands [FILTER] # list commands (JSON), optionally only ids/labels/menus containing FILTER //! designcraft-cli describe ID # one command: label, menu, shortcut, parameters //! designcraft-cli script [FILE|-] [--in FILE | --sample] [--connect PORT] [--save OUT] [--export OUT] [--keep-going] @@ -77,7 +78,7 @@ fn main() -> ExitCode { } _ => { eprintln!( - "usage: designcraft-cli run [--in FILE | --sample] [--cmd ID[=JSON]]... [--page N] [--scale S] [--pdf-options JSON] [--export OUT] [--all-pages DIR]\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]\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli links\n designcraft-cli --version" + "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]\n designcraft-cli perf [--pages N] [--runs N] [--strict]\n designcraft-cli bench FILE [--runs N]\n designcraft-cli links\n designcraft-cli --version" ); eprintln!( "\nCommunity: {} · {} · {}", @@ -136,7 +137,36 @@ fn mcp(args: &[String]) -> Result<(), String> { Server::new(backend).serve(stdin.lock(), stdout.lock()).map_err(|e| e.to_string()) } +/// The first `--page`, `--scale` or `--pdf-options` with no `--export` or `--all-pages` after it. +/// They apply to the exports that follow them, so one after the last export would do nothing. +fn option_after_last_export(args: &[String]) -> Option<&str> { + let mut unused = None; + let mut it = args.iter(); + while let Some(a) = it.next() { + match a.as_str() { + "--page" | "--scale" | "--pdf-options" => { + unused = unused.or(Some(a.as_str())); + it.next(); + } + "--export" | "--all-pages" => { + unused = None; + it.next(); + } + "--in" | "--cmd" => { + it.next(); + } + _ => {} + } + } + unused +} + fn run(args: &[String]) -> Result<(), String> { + 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" + )); + } let mut s = Session::new(); let mut page = 0usize; let mut scale = 1.0f64; diff --git a/apps/designcraft-cli/tests/cli.rs b/apps/designcraft-cli/tests/cli.rs index 75f6d90b9..8c2b0f14b 100644 --- a/apps/designcraft-cli/tests/cli.rs +++ b/apps/designcraft-cli/tests/cli.rs @@ -80,3 +80,25 @@ fn closed_stdout_ends_quietly() { let err = String::from_utf8_lossy(&out.stderr); assert!(out.status.success() && !err.contains("panicked"), "{:?}: {err}", out.status); } + +/// `--scale`, `--page` and `--pdf-options` apply to the exports after them; one with no export +/// after it was silently ignored. +#[test] +fn run_export_options_come_before_their_export() { + let dir = std::env::temp_dir().join(format!("dc-cli-order-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (a, b) = (dir.join("a.png"), dir.join("b.png")); + let (a, b) = (a.to_str().unwrap(), b.to_str().unwrap()); + for (opt, val) in [("--scale", "0.5"), ("--page", "1"), ("--pdf-options", r#"{"pages":"1"}"#)] { + let out = cli().args(["run", "--sample", "--export", a, opt, val]).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{opt} after the last --export: {err}"); + assert!(err.contains(opt) && err.contains("before"), "{err}"); + } + assert!(!std::path::Path::new(a).exists(), "nothing is exported when the arguments are wrong"); + let out = cli().args(["run", "--sample", "--scale", "0.5", "--export", a, "--scale", "0.25", "--export", b]).output().unwrap(); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains("wrote") && std::path::Path::new(a).exists() && std::path::Path::new(b).exists(), "{err}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 0ad996223..802f615dc 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -106,7 +106,8 @@ pub fn tool_definitions() -> Vec { "Run any DesignCraft command by id with JSON params (ids and params from list_commands). Examples: \ {\"command\":\"frame.create\",\"params\":{\"rect\":[36,36,576,300],\"content\":\"text\",\"text\":\"Hello\"}} → {id, story}; \ {\"command\":\"type.char\",\"params\":{\"size\":24}}; {\"command\":\"edit.undo\"}. Coordinates are points in spread space. \ - In the desktop app UI-only commands (view.*, window.*, app.*) work too.", + In the desktop app the UI-only commands (view.*, window.*, help.*, edit.dynamicSpelling, and app.* except app.links, \ + which works everywhere) work too.", obj(json!({"command": string("Command id, e.g. frame.create"), "params": params_schema()}), &["command"]), false, ), @@ -137,16 +138,17 @@ pub fn tool_definitions() -> Vec { "inspect_document", "Inspect document", "Summary of the active document: settings, pages (index, name, bounds, margins, columns), spreads with items (id, kind, \ - bounds, fill, stroke, story), stories (id, frames, length, overset, preview), layers, paragraph/character styles, \ - swatches, selection, active tool.", + bounds, fill, stroke, story), stories (id, frames, length in UTF-8 bytes, overset, preview), layers, \ + paragraph/character styles, swatches, selection, active tool.", empty(), true, ), tool( "get_story", "Get story", - "Full text of a story plus its frames, paragraph count, line count and overset position. Identify it by `story` id or \ - by a text `frame` id (default: the selection).", + "Full text of a story plus its length, frames, paragraph count, line count and overset position (length and positions \ + are UTF-8 byte offsets, the unit text.select takes). Identify it by `story` id or by a text `frame` id (default: the \ + selection).", obj(json!({"story": int("Story id"), "frame": int("Text frame id")}), &[]), true, ), diff --git a/docs/agents.md b/docs/agents.md index 4571b2797..0dd23f062 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -41,6 +41,10 @@ The result is JSON: `{"completed": n, "results": [...]}`, plus `failedIndex` / ` fails (the exit status is non-zero; `--keep-going` records errors and continues). `run --cmd ID=JSON` accepts the same references, and MCP's `batch` tool takes `commands` or `script` text with them. +`run` works through its arguments in order. `--page`, `--scale` and `--pdf-options` apply to the `--export` / +`--all-pages` that follow them, so one run can write several sizes +(`run --sample --scale 0.5 --export small.png --scale 2 --export large.png`); one with no export after it is an error. + ## Data merge `data.source.select {path, sheet?}` links a CSV/TSV/`.xlsx` file to the document (`data.source.update` re-reads it, diff --git a/docs/mcp.md b/docs/mcp.md index 2181fef92..f53c56767 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -31,7 +31,7 @@ Other MCP clients use the same command line, e.g. in a JSON config: | Engine | In-process `designcraft_engine::Session`, starts with an empty Letter document (`--sample` opens the sample magazine) | The app's session, through its loopback control channel ([control-protocol.md](control-protocol.md)) | | Rendering | `designcraft-render` (CPU) | The app's renderer | | Window tools (`screenshot`, `click`, `drag`, `menu_list`, `ui_inspect`, `ui_set`, `dialog_*`) | Return an error explaining how to connect | Work | -| UI-only commands (`view.*`, `window.*`, `app.*`) via `execute` | Error | Work | +| UI-only commands via `execute` (`view.*`, `window.*`, `help.*`, `edit.dynamicSpelling`, and `app.*` except `app.links`) | Error | Work | In connected mode every tool maps to a control-channel method (`engine.execute`, `ui.render`, `ui.pointer`, …), so what the agent does shows up live in the window. The connection is re-established once if the app restarts. @@ -43,6 +43,14 @@ spread the right page starts at x = page width. `inspect_document` lists page bo `render_page` / `export_png` are 0-based. `pointer` events in connected mode may use `"space": "screen"` (egui points, see `ui_inspect` → `canvasRect`). +## Text offsets + +Positions in a story's text are **UTF-8 byte offsets**, not character counts: `anchor` / `focus` of `text.select`, +`start` / `end` of `story.replaceRange` and of `find.find` matches, the `pos` that `text.placeCaret`, `text.insert` +and `text.move` return, a story's `length` in `get_story` and `inspect_document`, and its `overset` position in +`get_story`. A character outside ASCII takes 2 to 4 bytes (é 2, — and は 3), so the story `はただ商店` has length 15 +and its second character starts at 3. An offset inside a character snaps back to the start of that character. + ## Tools | Tool | What it does | From fe16e00e3753714cef96818fdc2d6e8a373d431b Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:13:48 -0400 Subject: [PATCH 12/24] PDF/A keeps placed images; right-to-left tables and columns (#128) * PDF: PDF/A exports keep placed PNG, JPEG, GIF and WebP images by writing them without interpolation (#71) * Tables: new tables take their paragraph's direction, and the Table panel sets a table's direction (#100) * Text: stories made in a right-to-left-bound document fill their columns from the right (#100) --- crates/doc/src/edit.rs | 7 ++++ crates/engine/src/cmd/layout.rs | 29 +++++++++++++++ crates/engine/src/cmd/object.rs | 1 + crates/engine/src/cmd/path_type.rs | 1 + crates/engine/src/cmd/place_text.rs | 1 + crates/engine/src/cmd/table.rs | 55 ++++++++++++++++++++++++++++- crates/pdf/src/export.rs | 30 +++++++++------- crates/pdf/src/tests.rs | 49 +++++++++++++++++++++++++ crates/ui-egui/src/panels/table.rs | 10 ++++++ 9 files changed, 169 insertions(+), 14 deletions(-) diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs index 188f514d2..3bb827135 100644 --- a/crates/doc/src/edit.rs +++ b/crates/doc/src/edit.rs @@ -171,11 +171,18 @@ impl Document { Ok(removed) } + /// The column direction a new story starts with: right to left in a document whose binding is + /// right to left (Document Setup), else left to right. Stories already made keep theirs. + pub fn new_story_direction(&self) -> crate::TextDirection { + if self.settings.right_to_left_binding { crate::TextDirection::RightToLeft } else { crate::TextDirection::LeftToRight } + } + /// Create a text frame with a new (or given) story at `rect` on spread `r`. pub fn add_text_frame(&mut self, r: SpreadRef, rect: Rect, layer: LayerId, text: &str, para: ParaFormat) -> Result<(ItemId, StoryId)> { let id = ItemId(self.alloc()); let sid = StoryId(self.alloc()); let mut story = Story::with_text(sid, text, para); + story.direction = self.new_story_direction(); story.frames.push(id); self.stories.insert(sid, Arc::new(story)); let mut item = Item::new(id, layer, Shape::Rectangle, shapes::rectangle(rect)); diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 2a1b0751c..bd5320799 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -759,6 +759,35 @@ mod setup_tests { let d = &s.doc().unwrap().doc; assert_eq!(d.spreads[1].pages.iter().map(|p| (p.side, p.x)).collect::>(), vec![(Left, 0.0), (Right, w)]); } + + /// Multi-column frames filled the left column first in a right-to-left document (#100): + /// stories made in a right-to-left-bound document start their columns on the right. + #[test] + fn new_stories_follow_the_binding_direction() { + use designcraft_doc::TextDirection::{LeftToRight, RightToLeft}; + let text = (1..=12).map(|i| format!("الفقرة {i}")).collect::>().join("\n"); + for (binding, expected) in [("rightToLeft", RightToLeft), ("leftToRight", LeftToRight)] { + let mut s = crate::Session::new(); + s.execute("file.new", &json!({"preset": "A4", "pages": 1})).unwrap(); + s.execute("layout.documentSetup", &json!({"binding": binding})).unwrap(); + let f = s.execute("frame.create", &json!({"rect": [40, 170, 555, 260], "content": "text", "text": text})).unwrap(); + s.execute("object.textFrameOptions", &json!({"ids": [f["id"]], "columns": 2, "gutter": 20})).unwrap(); + let sid = designcraft_doc::StoryId(f["story"].as_u64().unwrap()); + let st = s.doc().unwrap(); + assert_eq!(st.doc.story(sid).unwrap().direction, expected, "{binding}"); + let cs = s.cache.get(&st.doc, sid, None); + let fr = &cs.frames[0]; + let (first, last) = (fr.lines.first().unwrap(), fr.lines.last().unwrap()); + assert!(fr.columns.len() == 2 && first.x0 != last.x0, "the text fills both columns: {:?}", fr.columns); + assert_eq!(first.x0 > last.x0, expected == RightToLeft, "{binding}: the first line is in the first column"); + // An empty frame given text content starts a story too. + let g = s.execute("frame.create", &json!({"rect": [40, 400, 555, 500]})).unwrap(); + s.execute("object.content", &json!({"ids": [g["id"]], "type": "text"})).unwrap(); + let d = &s.doc().unwrap().doc; + let tf = d.item(designcraft_doc::ItemId(g["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story; + assert_eq!(d.story(tf).unwrap().direction, expected, "{binding}: object.content"); + } + } } #[cfg(test)] diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index 40802d548..dc456a134 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1379,6 +1379,7 @@ fn content_type(s: &mut Session, p: &Value) -> Result { ("text", Some(Content::Unassigned | Content::Graphic(_))) => { let sid = StoryId(d.alloc()); let mut st = Story::new(sid); + st.direction = d.new_story_direction(); st.frames.push(*id); d.stories.insert(sid, Arc::new(st)); if let Some(it) = d.item_mut(*id) { diff --git a/crates/engine/src/cmd/path_type.rs b/crates/engine/src/cmd/path_type.rs index 883f0c20a..77bbf87ab 100644 --- a/crates/engine/src/cmd/path_type.rs +++ b/crates/engine/src/cmd/path_type.rs @@ -54,6 +54,7 @@ fn on_path(s: &mut Session, p: &Value) -> Result { } let sid = StoryId(d.alloc()); let mut st = Story::with_text(sid, &text, Default::default()); + st.direction = d.new_story_direction(); st.frames = vec![id]; d.stories.insert(sid, std::sync::Arc::new(st)); let it = d.item_mut(id).ok_or(designcraft_doc::DocError::NoItem(id))?; diff --git a/crates/engine/src/cmd/place_text.rs b/crates/engine/src/cmd/place_text.rs index 39805bfb0..766811b50 100644 --- a/crates/engine/src/cmd/place_text.rs +++ b/crates/engine/src/cmd/place_text.rs @@ -200,6 +200,7 @@ pub(super) fn place_text(s: &mut Session, p: &Value, name: &str, bytes: &[u8]) - Some(_) => { let sid = StoryId(d.alloc()); let mut ns = Story::new(sid); + ns.direction = d.new_story_direction(); ns.frames = vec![fid]; d.stories.insert(sid, std::sync::Arc::new(ns)); if let Some(it) = d.item_mut(fid) { diff --git a/crates/engine/src/cmd/table.rs b/crates/engine/src/cmd/table.rs index c2f925c09..3bb188b49 100644 --- a/crates/engine/src/cmd/table.rs +++ b/crates/engine/src/cmd/table.rs @@ -372,6 +372,14 @@ fn column_width(s: &Session, t: &TextSel) -> f64 { spec.and_then(|f| f.columns().first().map(|c| c.width())).unwrap_or(300.0) } +/// The direction of the paragraph at `offset` in `story`, as composition resolves it (its style +/// chain, then local overrides). A table created there takes it. +fn para_direction(d: &Document, story: StoryId, offset: usize) -> designcraft_doc::TextDirection { + d.story(story) + .and_then(|st| st.paras.get(st.para_at(offset))) + .map_or(designcraft_doc::TextDirection::LeftToRight, |pf| d.styles.resolve_para(pf).0.direction) +} + fn insert(s: &mut Session, p: &Value) -> Result { let t = s.doc()?.selection.text.ok_or_else(|| bad("table.insert", "no insertion point"))?; if t.cell.is_some() { @@ -385,6 +393,7 @@ fn insert(s: &mut Session, p: &Value) -> Result { s.edit(|d, sel| { let id = d.alloc(); let mut table = Table::new(id, rows, cols, header, footer, width); + table.options.direction = para_direction(d, t.story, t.range().start); let st = d.story_mut(t.story).ok_or_else(|| bad("table.insert", "no story"))?; // Cells start with the paragraph format at the caret. let pf = st.paras[st.para_at(t.range().start)].clone(); @@ -410,6 +419,7 @@ fn convert_from_text(s: &mut Session, p: &Value) -> Result { let width = p.get("width").and_then(Value::as_f64).unwrap_or_else(|| column_width(s, &t)); s.edit(|d, sel| { let id = d.alloc(); + let direction = para_direction(d, t.story, t.range().start); let st = d.story_mut(t.story).ok_or_else(|| bad("table.convertFromText", "no story"))?; let ranges = st.para_ranges(); let (pa, pb) = (st.para_at(t.range().start), st.para_at(t.range().end)); @@ -420,7 +430,8 @@ fn convert_from_text(s: &mut Session, p: &Value) -> Result { let data: Vec> = st.text[a..b].split('\n').map(|line| line.split(sep).map(|c| c.trim().to_string()).collect()).collect(); let pf = st.paras[pa].clone(); let cf = st.format_after(a).clone(); - let table = Table::from_strings(id, &data, width, &pf, &cf); + let mut table = Table::from_strings(id, &data, width, &pf, &cf); + table.options.direction = direction; st.delete(a..b); let anchor = st.insert_table(a, table); *sel = Selection::text(TextSel::caret(t.story, anchor)); @@ -1435,4 +1446,46 @@ mod arabic_tests { assert_eq!(t.ncols(), 2); assert_eq!(t.options.direction, designcraft_doc::TextDirection::RightToLeft); } + + /// A text frame whose paragraphs have a paragraph style with `direction`, with the story's + /// text selected. Returns the session and the story id. + fn styled_frame(direction: &str, text: &str) -> (Session, u64) { + let mut s = Session::new(); + s.execute("file.new", &json!({"preset": "A4", "pages": 1})).unwrap(); + s.execute("style.paragraph.create", &json!({"name": "Dir", "para": {"direction": direction}})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [40, 330, 555, 420], "content": "text", "text": text, "caret": true})).unwrap(); + s.execute("edit.selectAll", &json!({})).unwrap(); + s.execute("style.paragraph.apply", &json!({"name": "Dir"})).unwrap(); + s.execute("edit.selectAll", &json!({})).unwrap(); + (s, r["story"].as_u64().unwrap()) + } + + fn only_table(s: &Session) -> std::sync::Arc { + s.doc().unwrap().doc.stories.values().flat_map(|st| st.tables.values()).next().unwrap().clone() + } + + /// Text converted to a table in a right-to-left paragraph laid its columns out left to right + /// (#100): the first column belongs on the right. + #[test] + fn tables_take_the_direction_of_their_paragraph() { + use designcraft_doc::TextDirection::{LeftToRight, RightToLeft}; + let (mut s, sid) = styled_frame("rightToLeft", "١\t٢\t٣\nأ\tب\tج"); + s.execute("table.convertFromText", &json!({"columnSeparator": "tab"})).unwrap(); + assert_eq!(only_table(&s).options.direction, RightToLeft); + let st = s.doc().unwrap(); + let cs = s.cache.get(&st.doc, designcraft_doc::StoryId(sid), None); + let placed = &cs.frames[0].tables[0]; + let (first, last) = (placed.cell(0, 0).unwrap().rect, placed.cell(0, 2).unwrap().rect); + assert!(first.x0 > last.x0, "cell ١ is the rightmost: {first:?} {last:?}"); + + let (mut s, _) = styled_frame("leftToRight", "1\t2\t3\na\tb\tc"); + s.execute("table.convertFromText", &json!({"columnSeparator": "tab"})).unwrap(); + assert_eq!(only_table(&s).options.direction, LeftToRight); + + for (direction, expected) in [("rightToLeft", RightToLeft), ("leftToRight", LeftToRight)] { + let (mut s, _) = styled_frame(direction, "x"); + s.execute("table.insert", &json!({"rows": 1, "cols": 2})).unwrap(); + assert_eq!(only_table(&s).options.direction, expected, "table.insert in a {direction} paragraph"); + } + } } diff --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs index 0c77e69b9..095ea77cc 100644 --- a/crates/pdf/src/export.rs +++ b/crates/pdf/src/export.rs @@ -154,6 +154,7 @@ pub fn export_pdf_with_report(doc: &Document, cache: &Cache, opts: &PdfOptions) fonts: HashMap::new(), reverse_cmaps: HashMap::new(), rgb_only: archival.is_some(), + interpolate: archival.is_none(), tags: Vec::new(), story_tags: HashMap::new(), tag_story: None, @@ -327,6 +328,7 @@ pub fn export_booklet(doc: &Document, cache: &Cache, opts: &BookletOptions) -> R fonts: HashMap::new(), reverse_cmaps: HashMap::new(), rgb_only: false, + interpolate: true, tags: Vec::new(), story_tags: HashMap::new(), tag_story: None, @@ -421,6 +423,8 @@ pub(crate) struct Exporter<'a> { pub reverse_cmaps: HashMap>>, /// Convert CMYK to RGB (PDF/A: krilla needs a CMYK output profile we don't ship yet). pub rgb_only: bool, + /// Ask viewers to smooth upscaled images (`/Interpolate`). Off for PDF/A, which forbids it. + interpolate: bool, /// Tagged PDF: the structure in reading order (stories gather their frames' content). tags: Vec, story_tags: HashMap>, @@ -1168,21 +1172,21 @@ impl Exporter<'_> { let data = asset.data.clone(); let fmt = image::guess_format(&data).ok(); let img = match fmt { - Some(image::ImageFormat::Jpeg) => Image::from_jpeg(data.clone().into(), true).ok(), + Some(image::ImageFormat::Jpeg) => Image::from_jpeg(data.clone().into(), self.interpolate).ok(), // A CMYK TIFF keeps its ink values (`image` decodes it to RGB, and 100% K would print // as four-colour black). PDF/A exports are RGB only. - Some(image::ImageFormat::Tiff) if !self.rgb_only && designcraft_images::is_cmyk_tiff(&data) => match cmyk_tiff(&data) { + Some(image::ImageFormat::Tiff) if !self.rgb_only && designcraft_images::is_cmyk_tiff(&data) => match cmyk_tiff(&data, self.interpolate) { Some(img) => Some(img), None => { self.warn(format!( "{}: converted to RGB (a CMYK TIFF that is planar, has premultiplied alpha, uses other inks or is over 256 MiB)", asset.name )); - lossless(&data, fmt) + lossless(&data, fmt, self.interpolate) } }, - _ if self.opts.compress_images => recompress(&data).or_else(|| lossless(&data, fmt)), - _ => lossless(&data, fmt), + _ if self.opts.compress_images => recompress(&data, self.interpolate).or_else(|| lossless(&data, fmt, self.interpolate)), + _ => lossless(&data, fmt, self.interpolate), }; if img.is_none() { self.warn(format!("image `{}` could not be decoded and was skipped", asset.name)); @@ -1276,11 +1280,11 @@ fn relabel_pdf_header(data: &[u8], from: &[u8], to: &[u8]) -> Option> { Some(out) } -fn lossless(data: &Arc>, fmt: Option) -> Option { +fn lossless(data: &Arc>, fmt: Option, interpolate: bool) -> Option { let direct = match fmt { - Some(image::ImageFormat::Png) => Image::from_png(data.clone().into(), true).ok(), - Some(image::ImageFormat::Gif) => Image::from_gif(data.clone().into(), true).ok(), - Some(image::ImageFormat::WebP) => Image::from_webp(data.clone().into(), true).ok(), + Some(image::ImageFormat::Png) => Image::from_png(data.clone().into(), interpolate).ok(), + Some(image::ImageFormat::Gif) => Image::from_gif(data.clone().into(), interpolate).ok(), + Some(image::ImageFormat::WebP) => Image::from_webp(data.clone().into(), interpolate).ok(), _ => None, }; direct.or_else(|| { @@ -1320,18 +1324,18 @@ impl krilla::image::CustomImage for CmykImage { } /// A CMYK TIFF as a DeviceCMYK image. `None` when it can't be read as CMYK. -fn cmyk_tiff(data: &[u8]) -> Option { +fn cmyk_tiff(data: &[u8], interpolate: bool) -> Option { let r = designcraft_images::decode_cmyk_tiff(data)?; // krilla panics when the channel lengths don't match the size. let pixels = usize::try_from(r.width).ok()?.checked_mul(usize::try_from(r.height).ok()?)?; if r.cmyk.len() != pixels.checked_mul(4)? || r.alpha.as_ref().is_some_and(|a| a.len() != pixels) { return None; } - Image::from_custom(CmykImage(Arc::new(r)), true).ok() + Image::from_custom(CmykImage(Arc::new(r)), interpolate).ok() } /// Opaque raster → JPEG (quality 90). `None` when the image has transparency or can't be decoded. -fn recompress(data: &[u8]) -> Option { +fn recompress(data: &[u8], interpolate: bool) -> Option { let img = image::load_from_memory(data).ok()?; if img.color().has_alpha() && img.to_rgba8().pixels().any(|p| p[3] < 255) { return None; @@ -1340,5 +1344,5 @@ fn recompress(data: &[u8]) -> Option { let mut buf = Vec::new(); let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut buf, 90); image::ImageEncoder::write_image(enc, rgb.as_raw(), rgb.width(), rgb.height(), image::ExtendedColorType::Rgb8).ok()?; - Image::from_jpeg(buf.into(), true).ok() + Image::from_jpeg(buf.into(), interpolate).ok() } diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index 1771c4e4f..83744a3e1 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -271,6 +271,55 @@ fn cmyk_tiff_keeps_its_inks() { } } +/// An 8×8 raster encoded as `fmt`; `alpha` gives it a transparent corner. +fn raster(fmt: image::ImageFormat, alpha: bool) -> Vec { + let img = + image::RgbaImage::from_fn(8, 8, |x, y| image::Rgba([(x * 30) as u8, (y * 30) as u8, 128, if alpha && x == 0 && y == 0 { 0 } else { 255 }])); + let img = if fmt == image::ImageFormat::Jpeg { + image::DynamicImage::ImageRgb8(image::DynamicImage::ImageRgba8(img).to_rgb8()) + } else { + image::DynamicImage::ImageRgba8(img) + }; + let mut b = std::io::Cursor::new(Vec::new()); + img.write_to(&mut b, fmt).unwrap(); + b.into_inner() +} + +/// Each image XObject's /Interpolate value (`None` when absent). +fn interpolate_flags(bytes: &[u8]) -> Vec> { + use hayro_syntax::object::Name; + let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).expect("parse"); + pdf.objects() + .into_iter() + .filter_map(|o| o.into_stream()) + .filter(|s| s.dict().get::("Subtype").is_some_and(|n| n.as_str() == "Image")) + .map(|s| s.dict().get::("Interpolate")) + .collect() +} + +/// PDF/A-2b rejected placed PNG, JPEG, GIF and WebP images (#71): they were written with +/// /Interpolate true, which PDF/A forbids. Ordinary exports keep interpolation. +#[test] +fn archival_exports_keep_placed_images_without_interpolation() { + use image::ImageFormat as F; + let mut d = doc_with_text("x"); + for (fmt, alpha) in [(F::Png, true), (F::Png, false), (F::Jpeg, false), (F::Gif, true), (F::WebP, true)] { + place(&mut d, raster(fmt, alpha), (8, 8)); + } + for compress_images in [false, true] { + let opts = PdfOptions { compress_images, created: Some(1_700_000_000), ..Default::default() }; + let a = export_pdf_with_report(&d, &Cache::new(), &PdfOptions { standard: Standard::PdfA2b, ..opts.clone() }); + let a = a.unwrap_or_else(|e| panic!("PDF/A-2b with images (compress {compress_images}): {e:?}")); + let flags = interpolate_flags(&a.bytes); + assert!(flags.len() >= 5, "every placed image is in the PDF/A file: {flags:?}"); + assert!(flags.iter().all(|f| *f != Some(true)), "{flags:?}"); + let plain = export_pdf(&d, &Cache::new(), &opts).unwrap(); + let flags = interpolate_flags(&plain); + assert!(flags.len() >= 5, "{flags:?}"); + assert!(flags.contains(&Some(true)), "ordinary exports interpolate: {flags:?}"); + } +} + /// What a page draws: each glyph (its text and outline bounds) and each filled path's bounds. fn drawn(bytes: &[u8]) -> (Vec<(String, kurbo::Rect)>, Vec) { use hayro_interpret::font::Glyph; diff --git a/crates/ui-egui/src/panels/table.rs b/crates/ui-egui/src/panels/table.rs index 3f2d871ff..7a1cb3aae 100644 --- a/crates/ui-egui/src/panels/table.rs +++ b/crates/ui-egui/src/panels/table.rs @@ -191,6 +191,16 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { } }); divider(ui); + // Column order: right to left puts the first column on the right. + let rtl = info["options"]["direction"] == "rightToLeft"; + ui.horizontal(|ui| { + caption(ui, crate::i18n::tr(&app.ui.language, "Direction")); + for (on, label, dir) in [(!rtl, "Left to Right", "leftToRight"), (rtl, "Right to Left", "rightToLeft")] { + if ui.selectable_label(on, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, label))).clicked() && !on { + run(app, "table.options", json!({"direction": dir})); + } + } + }); let mut alt = !info["options"]["altRows"].is_null(); if ui.checkbox(&mut alt, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, "Alternating Row Fills"))).changed() { let v = if alt { json!({"first": 1, "firstColor": "[Black]", "firstTint": 0.1, "next": 1, "nextColor": "[None]"}) } else { Value::Null }; From ce3deb651aa1e5bcaf10e4b2632e4799f5d396a1 Mon Sep 17 00:00:00 2001 From: jahala Date: Sat, 10 Oct 2026 06:13:54 +0100 Subject: [PATCH 13/24] Commands: huge row and column counts can't exhaust memory (#137) Three commands took a count from their parameters and used it unchecked. Parameters come from MCP, the control channel and scripts, so the count is hostile input (never-crash: cap input-sized allocations, checked arithmetic). - layout.createGuides made one or two guides per row and column with no upper limit: 30 million rows took 1.2 GB, and 2^32 - 1 would exhaust memory, which aborts the process past the command guard. A count over 2^32 wrapped to a small one. Both counts are now capped at 100. - edit.stepAndRepeat multiplied rows by columns as usize. In debug builds the overflow panicked; in release builds 2^32 x 2^32 wraps to 0, passes the 1000-copy limit and starts a grid of 2^64 copies. The product is now checked, and a grid that large falls back to `count` copies like any other grid over 1000. - file.new stored any column count in the page (4 billion, or a wrapped value past 2^32). Page::column_rects builds one rect per column each time the columns are laid out. The count is now clamped to 1..=216, the range layout.marginsAndColumns already uses. Each case has a regression test that failed before the fix. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/engine/src/cmd/file.rs | 2 +- crates/engine/src/cmd/guides.rs | 22 +++++++++++++++++++--- crates/engine/src/cmd/object.rs | 2 +- crates/engine/src/tests.rs | 22 ++++++++++++++++++++++ 4 files changed, 43 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index e40000095..767c62280 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -124,7 +124,7 @@ fn file_new(s: &mut Session, p: &Value) -> Result { nd.height = f64_or(p, "height", nd.height); nd.pages = p.get("pages").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(nd.pages).clamp(1, 9999); nd.facing_pages = p.get("facingPages").and_then(Value::as_bool).unwrap_or(nd.facing_pages); - nd.columns = p.get("columns").and_then(Value::as_u64).map(|v| v as u32).unwrap_or(nd.columns); + nd.columns = p.get("columns").and_then(Value::as_u64).map(|v| v.clamp(1, 216) as u32).unwrap_or(nd.columns); nd.gutter = f64_or(p, "gutter", nd.gutter); nd.primary_text_frame = p.get("primaryTextFrame").and_then(Value::as_bool).unwrap_or(false); match p.get("margins") { diff --git a/crates/engine/src/cmd/guides.rs b/crates/engine/src/cmd/guides.rs index df578e30b..8a0fee5e3 100644 --- a/crates/engine/src/cmd/guides.rs +++ b/crates/engine/src/cmd/guides.rs @@ -51,7 +51,7 @@ pub fn specs() -> Vec { "Create Guides…", ["Layout"], None, - "{rows?: 0, columns?: 0, rowGutter?: 12, columnGutter?: 12, fitTo?: margins|page, removeExisting?: false, spread?, page? (index in the spread; default all pages)}", + "{rows?: 0, columns?: 0 (at most 100 each), rowGutter?: 12, columnGutter?: 12, fitTo?: margins|page, removeExisting?: false, spread?, page? (index in the spread; default all pages)}", has_doc, create_guides ), @@ -157,9 +157,13 @@ pub(crate) fn grid_positions(a: f64, b: f64, n: u32, gutter: f64) -> Vec { v } +/// The most rows or columns Create Guides lays out. The count comes from the caller, and every +/// guide is stored in the document. +const MAX_GUIDE_GRID: u32 = 100; + fn create_guides(s: &mut Session, p: &Value) -> Result { - let rows = p.get("rows").and_then(Value::as_u64).unwrap_or(0) as u32; - let cols = p.get("columns").and_then(Value::as_u64).unwrap_or(0) as u32; + let count = |key: &str| p.get(key).and_then(Value::as_u64).unwrap_or(0).min(u64::from(MAX_GUIDE_GRID)) as u32; + let (rows, cols) = (count("rows"), count("columns")); let rg = p.get("rowGutter").and_then(Value::as_f64).unwrap_or(12.0); let cg = p.get("columnGutter").and_then(Value::as_f64).unwrap_or(12.0); let to_page = str_param(p, "fitTo") == Some("page"); @@ -238,6 +242,18 @@ mod tests { s.execute("edit.undo", &json!({})).unwrap(); assert_eq!(s.doc().unwrap().doc.spreads[0].pages[0].guides.len(), 5); } + + /// A huge row or column count once made that many guides (2³² − 1 of them exhaust memory, which + /// no guard catches), and a count past 2³² wrapped to a small one. + #[test] + fn create_guides_caps_the_row_and_column_counts() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let args = json!({"spread": 0, "rows": 4_294_967_298_u64, "columns": 3_000_000, "rowGutter": 0.0, "columnGutter": 0.0}); + let r = s.execute("layout.createGuides", &args).unwrap(); + let per_page = 2 * (u64::from(MAX_GUIDE_GRID) - 1); + assert_eq!(r["guides"], per_page * s.doc().unwrap().doc.spreads[0].pages.len() as u64); + } } #[cfg(test)] diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index dc456a134..dba63ca70 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -1919,7 +1919,7 @@ fn step_and_repeat(s: &mut Session, p: &Value) -> Result { let cols = p.get("columns").and_then(Value::as_u64).map(|v| v as usize); let count = p.get("count").and_then(Value::as_u64).unwrap_or(1).clamp(1, 1000) as usize; let offsets: Vec = match (rows, cols) { - (Some(r), Some(c)) if r * c <= 1000 => (0..r) + (Some(r), Some(c)) if r.checked_mul(c).is_some_and(|n| n <= 1000) => (0..r) .flat_map(|i| (0..c).map(move |j| (i, j))) .filter(|&(i, j)| i + j > 0) .map(|(i, j)| Vec2::new(j as f64 * dx, i as f64 * dy)) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8f2f39b0f..1f5f7189e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -372,6 +372,28 @@ fn step_and_repeat_grid() { assert_eq!(last.y0, 36.0 + 2.0 * 40.0); } +/// rows × columns once overflowed: a panic in debug builds, and in release builds a product that +/// wrapped to 0 passed the 1000-copy limit and started a grid of 2⁶⁴ copies. +#[test] +fn step_and_repeat_with_a_huge_grid_makes_no_grid() { + let mut s = session(); + s.execute("frame.create", &json!({"rect": [36, 36, 66, 66], "content": "unassigned"})).unwrap(); + let r = s.execute("edit.stepAndRepeat", &json!({"rows": 4_294_967_296_u64, "columns": 4_294_967_296_u64})).unwrap(); + // As for any grid of more than 1000 copies: `count` (default 1) copies instead. + assert_eq!(r["created"], 1); +} + +/// The column count is the caller's and sizes a list every time the page's columns are laid out. +#[test] +fn new_document_caps_the_column_count() { + let mut s = Session::new(); + s.execute("file.new", &json!({"columns": 4_000_000_000_u64})).unwrap(); + assert_eq!(s.doc().unwrap().doc.spreads[0].pages[0].columns.count, 216); + // Past u32 the count wrapped (2³² + 3 became 3). + s.execute("file.new", &json!({"columns": 4_294_967_299_u64})).unwrap(); + assert_eq!(s.doc().unwrap().doc.spreads[0].pages[0].columns.count, 216); +} + #[test] fn snippets_roundtrip_between_documents() { let mut s = Session::new(); From d323b4e7020dc456a91c1398958ef789d32cad25 Mon Sep 17 00:00:00 2001 From: jahala Date: Sat, 10 Oct 2026 06:13:59 +0100 Subject: [PATCH 14/24] Web: AltGr and other named keys no longer type their names (#134) (#138) In the browser, pressing AltGr while editing text on the canvas inserted the word "AltGraph" into the story. eframe's web backend (0.36.2, web/input.rs text_from_keyboard_event) turns a keydown into a text event unless the key is on a fixed list of names. Browsers report many more named keys than that list holds: AltGraph, Dead, Unidentified, the media keys. Each one arrived as text. Panel text fields are not affected, because a focused egui text field takes its text from the browser's input events instead of keydown. The web shell now drops a text event that is a key name (ASCII letters and digits, starting with a capital, longer than one character) unless an egui text field has the keyboard. One key press never types such a word; a text field's input events can, so they are left alone. Co-authored-by: Claude Opus 5.5 (1M context) --- apps/designcraft-web/src/web.rs | 3 ++- crates/ui-egui/src/lib.rs | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/apps/designcraft-web/src/web.rs b/apps/designcraft-web/src/web.rs index 3879f0839..f5659863f 100644 --- a/apps/designcraft-web/src/web.rs +++ b/apps/designcraft-web/src/web.rs @@ -104,7 +104,8 @@ impl eframe::App for WebShell { self.app.logic(ctx); } - fn raw_input_hook(&mut self, _ctx: &egui::Context, raw: &mut egui::RawInput) { + fn raw_input_hook(&mut self, ctx: &egui::Context, raw: &mut egui::RawInput) { + designcraft_ui_egui::drop_key_name_text(raw, ctx.text_edit_focused()); self.app.raw_input_hook(raw); } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 275018cb6..4ec0b8b08 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -891,10 +891,42 @@ pub fn now_ms() -> f64 { } } +/// Is `text` the name of a key ("AltGraph", "Dead", "AudioVolumeUp") instead of typed text? +/// Browsers report a key press as a string: the character it types, or a name made of ASCII +/// letters and digits that starts with a capital. One key press never types such a word. +pub fn is_key_name(text: &str) -> bool { + text.len() > 1 && text.starts_with(|c: char| c.is_ascii_uppercase()) && text.chars().all(|c| c.is_ascii_alphanumeric()) +} + +/// Drop text events that are key names. eframe's web backend sends the name of every key it +/// doesn't know as text, so AltGr typed "AltGraph" into the story. `text_field_focused`: an +/// egui text field has the keyboard; its text comes from the browser's input events, which can +/// hold whole words, and is left alone. +pub fn drop_key_name_text(raw: &mut egui::RawInput, text_field_focused: bool) { + if !text_field_focused { + raw.events.retain(|e| !matches!(e, egui::Event::Text(t) if is_key_name(t))); + } +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn key_names_sent_as_text_are_dropped() { + let text = |t: &str| egui::Event::Text(t.to_string()); + let events = || { + vec![text("AltGraph"), text("é"), text("Dead"), text("A"), text("Unidentified"), text("ß"), text("AudioVolumeUp"), text("ab"), text("Æ")] + }; + let mut raw = egui::RawInput { events: events(), ..Default::default() }; + drop_key_name_text(&mut raw, false); + assert_eq!(raw.events, vec![text("é"), text("A"), text("ß"), text("ab"), text("Æ")]); + // A focused text field gets its text from input events, which can be whole words. + let mut raw = egui::RawInput { events: events(), ..Default::default() }; + drop_key_name_text(&mut raw, true); + assert_eq!(raw.events, events()); + } + #[test] fn snap_view_uses_the_saved_switches() { let mut ui = UiState::default(); From c614e0ab9e404bddf423aba09d7aae4f163a22db Mon Sep 17 00:00:00 2001 From: jahala Date: Sat, 10 Oct 2026 06:14:05 +0100 Subject: [PATCH 15/24] Docs, About: the Illustrator-class sibling is VectorCraft (#59) (#139) DrawCraft was renamed VectorCraft, and its repository is now storytold/vectorcraft. Three places still used the old name: - AGENTS.md and CLAUDE.md told contributors and agents that the sibling checkout lives at ../drawcraft. A clone made from the README link lands in ../vectorcraft, so that path does not exist. - The About window's sibling list used the app-page slug "drawcraft". getartcraft.com/apps/drawcraft still redirects to /apps/vectorcraft, so the link worked, but the README (which the list says it matches) uses /apps/vectorcraft. Co-authored-by: Claude Opus 5.5 (1M context) --- AGENTS.md | 2 +- CLAUDE.md | 2 +- crates/ui-egui/src/about.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3a2bcb59a..bedbfb6e6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # DesignCraft — instructions for agents -DesignCraft is a clean-room, open-source, Rust-native page-layout application targeting Adobe InDesign parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings with the same conventions: `../drawcraft` (Illustrator-class), `../photocraft` (Photoshop), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom). +DesignCraft is a clean-room, open-source, Rust-native page-layout application targeting Adobe InDesign parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings with the same conventions: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom). ## Start every session here 1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/indesign/*.md` (`11-observed-ui.md` holds measured observations of the running app). diff --git a/CLAUDE.md b/CLAUDE.md index 7d0673992..dfe78adb6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,6 +1,6 @@ # DesignCraft — instructions for agents -DesignCraft is a clean-room, open-source, Rust-native page-layout application targeting Adobe InDesign parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings with the same conventions: `../drawcraft` (Illustrator-class), `../photocraft` (Photoshop), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom). +DesignCraft is a clean-room, open-source, Rust-native page-layout application targeting Adobe InDesign parity — and superiority (speed, openness, agent control). It runs natively on macOS, Windows and Linux, and on the web via WASM. Siblings with the same conventions: `../vectorcraft` (Illustrator-class), `../photocraft` (Photoshop), `../pdfcraft` (Acrobat), `../filmcraft` (Premiere), `../lightcraft` (Lightroom). ## Start every session here 1. Read `plan/STATUS.md` (current milestone, next task), then the task in `plan/execution-plan.md` and the relevant `plan/architecture.md` section. Behaviour reference: `plan/indesign/*.md` (`11-observed-ui.md` holds measured observations of the running app). diff --git a/crates/ui-egui/src/about.rs b/crates/ui-egui/src/about.rs index a3875609a..4eae2e7c6 100644 --- a/crates/ui-egui/src/about.rs +++ b/crates/ui-egui/src/about.rs @@ -20,7 +20,7 @@ const MARK_PATH: &str = "M104.28,49.49L81.55,0h-31.23l-3.17,4.76L14.75,53.63,0,7 /// The other ArtCraft apps (app-page slug, name, what it is) — same list as the README. pub const SIBLINGS: &[(&str, &str, &str)] = &[ ("photocraft", "PhotoCraft", "image editing"), - ("drawcraft", "VectorCraft", "vector illustration"), + ("vectorcraft", "VectorCraft", "vector illustration"), ("filmcraft", "FilmCraft", "video editing, color and sound"), ("lightcraft", "LightCraft", "photo library and raw development"), ("pdfcraft", "PdfCraft", "reading, organizing and protecting PDFs"), From 9b8aaadae0967bcad8b28f13e20445c7d99387c2 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:14:10 -0400 Subject: [PATCH 16/24] UI: ruler units by right-click, Language in Properties (#145) * UI: right-clicking a ruler picks that ruler's units, and the vertical ruler measures in the vertical units (#133) * UI: the Properties panel's Character section sets the text's language, from the same list as the Character panel (#130) --- ROADMAP.md | 4 +- crates/ui-egui/src/canvas.rs | 116 +++++++++++++++++++++++- crates/ui-egui/src/panels/properties.rs | 70 ++++++++++++-- 3 files changed, 177 insertions(+), 13 deletions(-) diff --git a/ROADMAP.md b/ROADMAP.md index aa4c17396..588240138 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -88,7 +88,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - Edit ▸ Menus (`window.hideMenuItem`): hide menu items; menus with hidden items end in Show All Menu Items. - View ▸ Separations Preview (`view.separations`): one process plate as ink density, or areas over an ink limit in red (a GCR preview of the rendered view; spot plates and the flattener preview aren't there). - Separations Preview plates now come from each object's own colour (CMYK as authored; RGB and images through the colour settings, images via a cached 17³ table), so pure black shows only on the black plate. -- Language (Character panel ▸ Language, `type.char {language}`): text in other languages isn't hyphenated or spell-checked with the English dictionaries, typographer's quotes follow the language (German „…“, French and Russian «…», Swiss, Spanish, Dutch, Nordic, Japanese and Traditional Chinese 「…」, Simplified Chinese “…”), the font's localized forms (OpenType `locl`: Turkish i, Bulgarian Cyrillic, Japanese / Chinese / Korean glyph variants) follow it too, and so does the fallback for CJK characters the font lacks (with Draw Missing Glyphs from Fallback Fonts on): Japanese, Simplified Chinese, Traditional Chinese and Korean each try their own installed system fonts (Japanese starts with the craft-fonts Japanese faces, Mincho first, when built with them; Hangul, kana and Bopomofo pick their language's fonts whatever the language). Language names from IDML keep their spelling; locale codes as InDesign writes them for some languages (`de_DE_2006`, `nl_NL_2005`; any `ll`, `ll_CC`, `ll-CC`) are their language and region for all of the above, and Chinese is also recognised in its common spellings ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`). Hyphenation dictionaries for other languages aren't bundled yet. +- Language (Character panel ▸ Language, Properties ▸ Character, `type.char {language}`): text in other languages isn't hyphenated or spell-checked with the English dictionaries, typographer's quotes follow the language (German „…“, French and Russian «…», Swiss, Spanish, Dutch, Nordic, Japanese and Traditional Chinese 「…」, Simplified Chinese “…”), the font's localized forms (OpenType `locl`: Turkish i, Bulgarian Cyrillic, Japanese / Chinese / Korean glyph variants) follow it too, and so does the fallback for CJK characters the font lacks (with Draw Missing Glyphs from Fallback Fonts on): Japanese, Simplified Chinese, Traditional Chinese and Korean each try their own installed system fonts (Japanese starts with the craft-fonts Japanese faces, Mincho first, when built with them; Hangul, kana and Bopomofo pick their language's fonts whatever the language). Language names from IDML keep their spelling; locale codes as InDesign writes them for some languages (`de_DE_2006`, `nl_NL_2005`; any `ll`, `ll_CC`, `ll-CC`) are their language and region for all of the above, and Chinese is also recognised in its common spellings ("Simplified Chinese", "Chinese (Traditional)", `zh_CN`, `zh-Hant`). Hyphenation dictionaries for other languages aren't bundled yet. - Books (`book.new/open/add/remove/list/styleSource/paginate/syncStyles/exportPdf`, Book panel): `.dcbook` files, continuous page numbering, style sync from a style source, one merged PDF. - Track Changes (`changes.track/list/acceptAll/rejectAll`, Type ▸ Track Changes): typing is marked added (highlighted on screen), deletions are kept but hidden from layout and exports until accepted or rejected. Per-change accept/reject and authors aren't there yet. - Track Changes: per-change Accept / Reject (`changes.accept`, `changes.reject`) and a Track Changes panel listing every change. @@ -161,7 +161,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope - Gradients: the Gradient Swatch tool (G) drags a gradient's start and end across objects (Shift: 45°); the Gradient panel sets type, angle, reverse and edits stops on a ramp (drag, add, drag off to remove, location, colour). Edited gradients are unnamed swatches; `object.gradient`; the vector round-trips through IDML. - Document Setup (⌥⌘P): intent, number of pages, start page # (an even start begins with a left page), facing pages, size presets and orientation, bleed and slug per edge; `layout.documentSetup {}` reports the setup. - Stroke panel: cap, join, miter limit, alignment, type, Start/End arrowheads (12 kinds, drawn on screen and in PDF; the path is shortened under pointed heads) and gap colour under dashes and dots. -- Preferences (⌘K: General, Type, Units & Increments, Grids, Guides & Pasteboard, Display Performance) backed by `prefs.set` (application) and `document.preferences` (units, increments, grids — undoable, saved with the document); scaling applies to content and scales stroke weights (Include Stroke Weight), and X/Y/W/H measure the stroke's outer edge (Dimensions Include Stroke Weight). Quick Apply (⌘Return) finds paragraph, character and object styles as well as commands. +- Preferences (⌘K: General, Type, Units & Increments, Grids, Guides & Pasteboard, Display Performance) backed by `prefs.set` (application) and `document.preferences` (units, increments, grids — undoable, saved with the document; right-click a ruler to pick its units, the horizontal and vertical rulers each have their own); scaling applies to content and scales stroke weights (Include Stroke Weight), and X/Y/W/H measure the stroke's outer edge (Dimensions Include Stroke Weight). Quick Apply (⌘Return) finds paragraph, character and object styles as well as commands. - Parent item overrides: Cmd+Shift-click a parent item on a page (or Override All Parent Page Items, ⌥⇧⌘L) makes an editable local copy that hides the parent's; Remove All Local Overrides and Detach All Objects from Parent in the Pages panel menu. - Place PDF: placed PDF pages are sized by their crop box, drawn on screen through hayro (with mip levels) and embedded in exported PDFs as vector form XObjects (krilla), `` in IDML. - Menus expose the engine's features (TOC, numbering & sections, text variables, hyperlinks, cross-references, footnotes, step and repeat, spelling, fitting/content, effects, Data Merge, Preflight, EPUB); any menu command with parameters gets a dialog generated from its parameter documentation. diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8288dd35c..b4b17d3ab 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -318,6 +318,7 @@ pub fn show(app: &mut DesignApp, ui: &mut egui::Ui) { draw_tool_overlays(app, &painter, &xf); if rulers { draw_rulers(app, ui, full, rect, &xf, &doc, &layout, &t); + ruler_units_menus(app, &resp, full, rect, &doc); } if let Some(r) = sel_rect && !preview @@ -1247,8 +1248,7 @@ fn draw_tool_overlays(app: &mut DesignApp, painter: &egui::Painter, xf: &Xf) { #[allow(clippy::too_many_arguments)] fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf, doc: &Document, layout: &CanvasLayout, t: &Tokens) { let painter = ui.painter_at(full); - let top = Rect::from_min_max(pos2(rect.min.x, full.min.y), pos2(full.max.x, rect.min.y)); - let left = Rect::from_min_max(pos2(full.min.x, rect.min.y), pos2(rect.min.x, full.max.y)); + let (top, left) = ruler_rects(full, rect); painter.rect_filled(top, 0.0, t.ruler); painter.rect_filled(left, 0.0, t.ruler); painter.rect_filled(Rect::from_min_max(full.min, rect.min), 0.0, t.ruler); @@ -1262,11 +1262,11 @@ fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf, let Some(i) = current_slot(app, layout) else { return }; let slot = &layout.slots[i]; let origin = Point::new(slot.bounds.x0, slot.bounds.y0); - let unit = doc.settings.horizontal_units; - let (major, sub) = unit.ruler_ticks(xf.zoom); let font = egui::FontId::proportional(9.0); let tick = Stroke::new(1.0, t.ruler_tick); // Horizontal. + let unit = doc.settings.horizontal_units; + let (major, sub) = unit.ruler_ticks(xf.zoom); let c0 = xf.to_canvas(top.min).x - origin.x; let c1 = xf.to_canvas(pos2(top.max.x, 0.0)).x - origin.x; let mut k = (c0 / major).floor() as i64; @@ -1291,6 +1291,8 @@ fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf, k += 1; } // Vertical. + let unit = doc.settings.vertical_units; + let (major, sub) = unit.ruler_ticks(xf.zoom); let c0 = xf.to_canvas(pos2(0.0, left.min.y)).y - origin.y; let c1 = xf.to_canvas(pos2(0.0, left.max.y)).y - origin.y; let mut k = (c0 / major).floor() as i64; @@ -1325,6 +1327,43 @@ fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf, } } +/// The horizontal (top) and vertical (left) rulers around the view `rect` in `full`. +fn ruler_rects(full: Rect, rect: Rect) -> (Rect, Rect) { + ( + Rect::from_min_max(pos2(rect.min.x, full.min.y), pos2(full.max.x, rect.min.y)), + Rect::from_min_max(pos2(full.min.x, rect.min.y), pos2(rect.min.x, full.max.y)), + ) +} + +/// Right-clicking a ruler opens a menu of units for that ruler. +fn ruler_units_menus(app: &mut DesignApp, resp: &egui::Response, full: Rect, rect: Rect, doc: &Document) { + let (top, left) = ruler_rects(full, rect); + let at = resp.interact_pointer_pos(); + for (ruler, key, cur) in [(top, "horizontalUnits", doc.settings.horizontal_units), (left, "verticalUnits", doc.settings.vertical_units)] { + let open = if resp.secondary_clicked() { + Some(egui::SetOpenCommand::Bool(at.is_some_and(|p| ruler.contains(p)))) + } else if resp.clicked() { + Some(egui::SetOpenCommand::Bool(false)) + } else { + None + }; + egui::Popup::context_menu(resp).id(resp.id.with(("ruler_units", key))).open_memory(open).show(|ui| ruler_units_menu(app, ui, key, cur)); + } +} + +/// Every unit, the current one checked; picking one sets `key` (`horizontalUnits` or +/// `verticalUnits`) through `document.preferences`. +fn ruler_units_menu(app: &mut DesignApp, ui: &mut egui::Ui, key: &str, cur: designcraft_geom::Unit) { + for u in designcraft_geom::Unit::ALL { + let label = crate::i18n::tr(&app.ui.language, u.label()); + let text = if u == cur { format!("✓ {label}") } else { format!(" {label}") }; + if ui.button(crate::rtl::widget(ui, text)).clicked() { + let _ = app.run("document.preferences", json!({ key: u })); + ui.close(); + } + } +} + fn fmt_tick(v: f64) -> String { let r = v.round(); if (v - r).abs() < 1e-6 { format!("{}", r as i64) } else { format!("{v:.1}") } @@ -1726,3 +1765,72 @@ fn guide_drag(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, rec } true } + +#[cfg(test)] +mod tests { + use designcraft_geom::Unit; + use egui_kittest::{Harness, kittest::Queryable}; + + use super::*; + + fn harness(app: DesignApp) -> Harness<'static, DesignApp> { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state( + |ui, app: &mut DesignApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h + } + + fn right_click(h: &mut Harness<'_, DesignApp>, p: Pos2) { + h.hover_at(p); + h.step(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() }); + } + h.run_steps(3); + } + + fn units(h: &Harness<'_, DesignApp>) -> (Unit, Unit) { + let s = &h.state().session.doc().unwrap().doc.settings; + (s.horizontal_units, s.vertical_units) + } + + #[test] + fn right_clicking_a_ruler_sets_that_rulers_units() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + let mut h = harness(app); + let rect = h.state().canvas_rect.unwrap(); + assert_eq!(units(&h), (Unit::Picas, Unit::Picas)); + // Vertical ruler: the current unit is checked; picking one sets only the vertical units. + right_click(&mut h, pos2(rect.min.x - RULER / 2.0, rect.center().y)); + h.get_by_label("✓ Picas"); + h.get_by_label(" Millimeters").click(); + h.run_steps(3); + assert_eq!(units(&h), (Unit::Picas, Unit::Millimeters)); + // Horizontal ruler. + right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0)); + h.get_by_label("✓ Picas"); + h.get_by_label(" Inches").click(); + h.run_steps(3); + assert_eq!(units(&h), (Unit::Inches, Unit::Millimeters)); + // The page and the ruler corner open no units menu. + for p in [rect.center(), rect.min - vec2(RULER / 2.0, RULER / 2.0)] { + right_click(&mut h, p); + assert!(h.query_by_label(" Points").is_none()); + } + } + + #[test] + fn rulers_open_no_units_menu_without_a_document() { + let mut h = harness(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default())); + let Some(rect) = h.state().canvas_rect else { return }; + right_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0)); + assert!(h.query_by_label(" Points").is_none()); + } +} diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 8644fe796..0d1bc69a3 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1070,6 +1070,18 @@ fn character_section(app: &mut DesignApp, ui: &mut Ui) { }) { let _ = app.run("type.char", json!({"attrs": {"tracking": v}})); } + // Language: hyphenation, spelling and typographer's quotes follow it. + ui.add_space(1.0); + let lang = c["language"].as_str().unwrap_or("English: USA").to_string(); + let label = crate::i18n::tr(&app.ui.language, "Language"); + let resp = widgets::dropdown(ui, crate::i18n::tr(&app.ui.language, &lang), fw).on_hover_ui(|ui| { + crate::rtl::label(ui, label); + }); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ComboBox, true, label)); + egui::Popup::menu(&resp).show(|ui| { + ui.set_min_width(fw); + egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| language_menu(app, ui, &lang)); + }); if more_options(ui, &app.ui.language).clicked() { app.ui.open_panel = Some("character".into()); } @@ -1212,6 +1224,17 @@ const LANGUAGES: &[&str] = &[ "Hebrew", ]; +/// The Language list (Character panel, Properties ▸ Character): picking one sets the language of +/// the selected text. +fn language_menu(app: &mut DesignApp, ui: &mut Ui, cur: &str) { + for l in LANGUAGES { + if ui.selectable_label(*l == cur, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, l))).clicked() { + let _ = app.run("type.char", json!({"attrs": {"language": l}})); + ui.close(); + } + } +} + pub fn character_panel(app: &mut DesignApp, ui: &mut egui::Ui) { let Some(a) = text_attrs(app) else { crate::rtl::label(ui, crate::i18n::tr(&app.ui.language, "Select text or a text frame.")); @@ -1231,13 +1254,7 @@ pub fn character_panel(app: &mut DesignApp, ui: &mut egui::Ui) { egui::ComboBox::from_id_salt("char_language") .selected_text(crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, &lang))) .width(170.0) - .show_ui(ui, |ui| { - for l in LANGUAGES { - if ui.selectable_label(*l == lang, crate::rtl::widget(ui, crate::i18n::tr(&app.ui.language, l))).clicked() { - let _ = app.run("type.char", json!({"attrs": {"language": l}})); - } - } - }); + .show_ui(ui, |ui| language_menu(app, ui, &lang)); }); // Digits (World-Ready): shown for right-to-left paragraphs or once set. let digits = c["digits"].as_str().unwrap_or("default").to_string(); @@ -2120,3 +2137,42 @@ fn variable_font_axes(app: &mut DesignApp, ui: &mut egui::Ui, family: &str, styl let _ = app.run("type.char", json!({"attrs": {"fontStyle": format!("{base} {{{spec}}}")}})); } } + +#[cfg(test)] +mod tests { + use egui_kittest::{Harness, kittest::Queryable}; + + use super::*; + + fn language(app: &mut DesignApp) -> Value { + text_attrs(app).unwrap()["chars"]["language"].clone() + } + + #[test] + fn properties_character_section_sets_the_language() { + let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({})).unwrap(); + app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "bunun", "caret": true})).unwrap(); + app.run("edit.selectAll", json!({})).unwrap(); + assert_ne!(language(&mut app), "French"); + let mut h = Harness::builder().with_size(vec2(320.0, 1400.0)).build_ui_state( + |ui, app: &mut DesignApp| { + // The panel's fonts are installed before its first frame. + let id = egui::Id::new("test_fonts"); + if ui.data(|d| d.get_temp::(id)).is_none() { + crate::theme::install_fonts(ui.ctx(), ""); + ui.data_mut(|d| d.insert_temp(id, true)); + return; + } + show(app, ui); + }, + app, + ); + h.run_steps(3); + h.get_by_label("Language").click(); + h.run_steps(2); + h.get_by_label("French").click(); + h.run_steps(2); + assert_eq!(language(h.state_mut()), "French"); + } +} From 4349919a4a3a6dcb88825cd2c1616138d38de8f5 Mon Sep 17 00:00:00 2001 From: jahala Date: Sat, 10 Oct 2026 06:14:17 +0100 Subject: [PATCH 17/24] Import: RTF and Tagged Text keep characters past U+FFFF (#149) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Placing an RTF or Tagged Text file dropped every character outside the Basic Multilingual Plane: emoji, mathematical letters and the rarer CJK ideographs such as 𠮷 (U+20BB7, used in Japanese names). The text around them came in, so the loss was silent. It also broke our own round trip: Export Text writes these characters correctly and Place lost them. Both formats carry such a character as a UTF-16 surrogate pair, two units in a row: \u-10179?\u-8704? in RTF, <0xD83D><0xDE00> in Tagged Text. Both readers passed each unit to char::from_u32 on its own. Half a pair is not a character, so each half was dropped. A small shared Utf16Units joins the units: a first half waits for the second, and the pair becomes one character. Half a pair with no partner is still left out, as before. Co-authored-by: Claude Opus 5.5 (1M context) --- crates/textimport/src/lib.rs | 27 +++++++++++++++++++++++++++ crates/textimport/src/rtf.rs | 22 ++++++++++++++++++++-- crates/textimport/src/tagged.rs | 19 ++++++++++++++++++- 3 files changed, 65 insertions(+), 3 deletions(-) diff --git a/crates/textimport/src/lib.rs b/crates/textimport/src/lib.rs index 8dc50ea7e..22f79c513 100644 --- a/crates/textimport/src/lib.rs +++ b/crates/textimport/src/lib.rs @@ -28,6 +28,33 @@ pub fn xlsx_records(bytes: &[u8], sheet: Option<&str>) -> Result use designcraft_doc::{CharAttrs, ParaAttrs, Story}; +/// Joins UTF-16 code units that arrive one at a time (RTF `\uN`, Tagged Text `<0xNNNN>`) into +/// characters. A character past U+FFFF comes as two units, a surrogate pair: the first half +/// waits for the second. +#[derive(Default)] +pub(crate) struct Utf16Units { + high: Option, +} + +impl Utf16Units { + /// The character that `unit` is or completes. Half a pair without its partner is no character. + pub(crate) fn push(&mut self, unit: u32) -> Option { + match (self.high.take(), unit) { + (Some(high), 0xDC00..=0xDFFF) => char::from_u32(0x10000 + ((high - 0xD800) << 10) + (unit - 0xDC00)), + (_, 0xD800..=0xDBFF) => { + self.high = Some(unit); + None + } + _ => char::from_u32(unit), + } + } + + /// Other text came in between: a waiting first half has no partner. + pub(crate) fn reset(&mut self) { + self.high = None; + } +} + /// A paragraph or character style found in the source. #[derive(Clone, Debug, Default, PartialEq)] pub struct ImportedStyle { diff --git a/crates/textimport/src/rtf.rs b/crates/textimport/src/rtf.rs index c02e5e551..9189b52d2 100644 --- a/crates/textimport/src/rtf.rs +++ b/crates/textimport/src/rtf.rs @@ -70,6 +70,7 @@ pub fn import(bytes: &[u8]) -> Result { let mut st = Story::new(StoryId(0)); let mut stack: Vec = vec![State { uc: 1, ..Default::default() }]; let mut pending = 0usize; // characters still to skip after \uN + let mut units = crate::Utf16Units::default(); let mut buf = String::new(); let mut fmt = stack[0].format(); let mut warnings = Vec::new(); @@ -124,6 +125,7 @@ pub fn import(bytes: &[u8]) -> Result { if let Ok(b) = u8::from_str_radix(&hex, 16) && !stack.last().is_some_and(|s| s.skip) { + units.reset(); buf.push(cp1252(b)); } continue; @@ -225,8 +227,8 @@ pub fn import(bytes: &[u8]) -> Result { } "u" => { if let Some(n) = param { - let cp = if n < 0 { (n + 65536) as u32 } else { n as u32 }; - if let Some(ch) = char::from_u32(cp) { + let unit = if n < 0 { (n + 65536) as u32 } else { n as u32 }; + if let Some(ch) = units.push(unit) { buf.push(ch); } pending = stack.last().map_or(1, |s| s.uc); @@ -243,6 +245,7 @@ pub fn import(bytes: &[u8]) -> Result { continue; } if !stack.last().is_some_and(|s| s.skip) { + units.reset(); buf.push(c); } } @@ -287,4 +290,19 @@ Caf\'e9 \u8364? price\tab tab\line next\par assert_eq!(st.format_after(0).over.size, Some(12.0)); assert!(!st.text.contains("Times"), "font table skipped"); } + + /// Characters past U+FFFF are written as two `\uN` words, a UTF-16 surrogate pair (the form + /// our own exporter and Word write). Each half was converted alone and dropped. + #[test] + fn surrogate_pairs_become_one_character() { + let i = import(br"{\rtf1\ansi\uc1 A\u-10179?\u-8704?B \u-10174?\u-8265?\u30000?}").unwrap(); + assert_eq!(i.story.text, "A\u{1F600}B \u{20BB7}\u{7530}"); + // What the exporter writes comes back. + let mut st = Story::new(StoryId(1)); + st.insert(0, "x \u{1F600} \u{20BB7}\u{7530} y"); + let doc = designcraft_doc::Document::new(&designcraft_doc::build::NewDocument::default()); + assert_eq!(import(crate::export::rtf(&doc, &st).as_bytes()).unwrap().story.text, st.text); + // Half a pair is not a character: it is still left out. + assert_eq!(import(br"{\rtf1 A\u-10179?B\u-8704?C}").unwrap().story.text, "ABC"); + } } diff --git a/crates/textimport/src/tagged.rs b/crates/textimport/src/tagged.rs index ca78bc4b1..cfd08eea7 100644 --- a/crates/textimport/src/tagged.rs +++ b/crates/textimport/src/tagged.rs @@ -110,12 +110,14 @@ pub fn import(bytes: &[u8]) -> Result { _ => runs.push((c.to_string(), fmt.clone())), } }; + let mut units = crate::Utf16Units::default(); let mut i = 0; let mut skipped = 0; while i < chars.len() { let c = chars[i]; match c { '\\' if i + 1 < chars.len() => { + units.reset(); push(&mut paras, chars[i + 1], &fmt); i += 2; } @@ -143,7 +145,7 @@ pub fn import(bytes: &[u8]) -> Result { match name { n if n.starts_with("0x") => { if let Ok(u) = u32::from_str_radix(&n[2..], 16) - && let Some(ch) = char::from_u32(u) + && let Some(ch) = units.push(u) { push(&mut paras, ch, &fmt); } @@ -193,6 +195,7 @@ pub fn import(bytes: &[u8]) -> Result { i += 1; } c => { + units.reset(); push(&mut paras, c, &fmt); i += 1; } @@ -226,6 +229,20 @@ pub fn import(bytes: &[u8]) -> Result { mod tests { use super::*; + /// Characters past U+FFFF are written as two tags, a UTF-16 surrogate pair. Each half was + /// converted alone and dropped. + #[test] + fn surrogate_pairs_become_one_character() { + let i = import("\r\n\r\nA<0xD83D><0xDE00>B <0xD842><0xDFB7><0x7530>".as_bytes()).unwrap(); + assert_eq!(i.story.text, "A\u{1F600}B \u{20BB7}\u{7530}"); + // What the exporter writes comes back. + let doc = Document::new(&designcraft_doc::build::NewDocument::default()); + let back = import(tagged_text(&doc, &i.story).as_bytes()).unwrap(); + assert_eq!(back.story.text, i.story.text); + // Half a pair is not a character: it is still left out. + assert_eq!(import("\r\nA<0xD83D>B<0xDE00>C".as_bytes()).unwrap().story.text, "ABC"); + } + #[test] fn tagged_text_round_trips() { let src = "\r\n\r\nCaf<0x00E9> \\<1\\>\r\nA word and big text"; From 06322045a57823523dccced119dba3185a911487 Mon Sep 17 00:00:00 2001 From: skylar taylor-barrick Date: Fri, 9 Oct 2026 23:14:22 -0600 Subject: [PATCH 18/24] Security: escape HTML and EPUB metadata (#152) --- crates/epub/src/lib.rs | 233 +++++++++++++++++++++++++++++++++-------- 1 file changed, 191 insertions(+), 42 deletions(-) diff --git a/crates/epub/src/lib.rs b/crates/epub/src/lib.rs index 3a61b509e..643f59341 100644 --- a/crates/epub/src/lib.rs +++ b/crates/epub/src/lib.rs @@ -39,7 +39,7 @@ pub fn export_fixed_epub(doc: &Document, pages: &[FixedPage], opts: &EpubOptions let io = |e: std::io::Error| EpubError(e.to_string()); let zerr = |e: zip::result::ZipError| EpubError(e.to_string()); let title = opts.title.clone().unwrap_or_else(|| doc.title.clone()); - let lang = &opts.language; + let lang = language_tag(&opts.language); let id = opts.identifier.clone().unwrap_or_else(|| format!("urn:designcraft:{}", slug(&title))); let mut manifest = String::from("\n"); let mut spine = String::new(); @@ -50,8 +50,8 @@ pub fn export_fixed_epub(doc: &Document, pages: &[FixedPage], opts: &EpubOptions let (w, h) = (p.width.round().max(1.0) as u32, p.height.round().max(1.0) as u32); let xhtml = format!( "\n\n\n{} — {n}\n\n\"\"/
{}
\n\n", - esc(&title), - esc(&p.text).replace('\n', "
") + xml_text(&title), + story_markup(&p.text).replace('\n', "
") ); let _ = writeln!( manifest, @@ -66,13 +66,13 @@ pub fn export_fixed_epub(doc: &Document, pages: &[FixedPage], opts: &EpubOptions let (vw, vh) = pages.first().map_or((612, 792), |p| (p.width.round() as u32, p.height.round() as u32)); let nav = format!( "\n\n\n{}\n\n\n", - esc(&title) + xml_text(&title) ); - let author = opts.author.as_deref().map(|a| format!("{}", esc(a))).unwrap_or_default(); + let author = opts.author.as_deref().map(|a| format!("{}", xml_text(a))).unwrap_or_default(); let opf = format!( "\n\n\n{}\n{}\n{lang}{author}\n2026-01-01T00:00:00Z\npre-paginated\nauto\n\n\n\n\n{manifest}\n\n{spine}\n\n", - esc(&id), - esc(&title) + xml_text(&id), + xml_text(&title) ); let container = "\n\n"; let mut buf = std::io::Cursor::new(Vec::new()); @@ -114,7 +114,11 @@ impl std::fmt::Display for EpubError { } impl std::error::Error for EpubError {} -fn esc(s: &str) -> String { +fn valid_xml_char(c: char) -> bool { + matches!(c, '\u{9}' | '\u{A}' | '\u{D}' | '\u{20}'..='\u{D7FF}' | '\u{E000}'..='\u{FFFD}' | '\u{10000}'..='\u{10FFFF}') +} + +fn escape_markup(s: &str, attr: bool, story_breaks: bool) -> String { let mut o = String::with_capacity(s.len()); for c in s.chars() { match c { @@ -122,15 +126,81 @@ fn esc(s: &str) -> String { '<' => o.push_str("<"), '>' => o.push_str(">"), '"' => o.push_str("""), + '\'' if attr => o.push_str("'"), '\u{E000}'..='\u{E1FF}' => {} - '\u{2028}' => o.push_str("
"), + '\u{2028}' if story_breaks => o.push_str("
"), '\u{AD}' => o.push_str("­"), - c => o.push(c), + c if valid_xml_char(c) => o.push(c), + _ => {} } } o } +fn xml_text(s: &str) -> String { + escape_markup(s, false, false) +} + +fn xml_attr(s: &str) -> String { + escape_markup(s, true, false) +} + +/// Story content permits the document's discretionary line-separator marker to become markup. +/// Other contexts always serialize it as ordinary text. +fn story_markup(s: &str) -> String { + escape_markup(s, false, true) +} + +/// A conservative BCP 47 subset suitable for both HTML and EPUB language attributes. +fn language_tag(s: &str) -> &str { + if s.len() > 63 { + return "und"; + } + let mut parts = s.split('-'); + let Some(first) = parts.next() else { return "und" }; + if !(2..=8).contains(&first.len()) || !first.bytes().all(|b| b.is_ascii_alphabetic()) { + return "und"; + } + if parts.any(|p| p.is_empty() || p.len() > 8 || !p.bytes().all(|b| b.is_ascii_alphanumeric())) { + return "und"; + } + s +} + +/// Return a MIME type that is safe to place in an attribute and a data URL. Parameters are omitted +/// because exported assets are always represented as their original binary bytes. +fn safe_mime(mime: &str) -> &str { + fn token(s: &str) -> bool { + !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'+' | b'-')) + } + + let mime = mime.split_once(';').map_or(mime, |(essence, _)| essence).trim(); + if mime.len() <= 127 + && let Some((kind, subtype)) = mime.split_once('/') + && !subtype.contains('/') + && token(kind) + && token(subtype) + { + mime + } else { + "image/png" + } +} + +/// Quote arbitrary document metadata as one CSS string token. Escaping `<` is important because +/// HTML parses the contents of a `style` element before CSS parsing sees it. +fn css_string(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + if matches!(c, '"' | '\\' | '<' | '>' | '&') || c.is_control() { + let _ = write!(out, "\\{:x} ", c as u32); + } else { + out.push(c); + } + } + out +} + /// CSS class name for a style name. pub fn slug(name: &str) -> String { let s: String = name.chars().map(|c| if c.is_ascii_alphanumeric() { c.to_ascii_lowercase() } else { '-' }).collect(); @@ -177,7 +247,7 @@ fn hex(doc: &Document, swatch: &str, tint: f32) -> Option { } fn char_css(doc: &Document, c: &CharProps, base_size: f64, out: &mut String) { - let _ = write!(out, "font-family: \"{}\", serif; ", c.font_family); + let _ = write!(out, "font-family: \"{}\", serif; ", css_string(&c.font_family)); let st = c.font_style.to_lowercase(); if st.contains("bold") { out.push_str("font-weight: bold; "); @@ -330,7 +400,7 @@ pub fn story_html(doc: &Document, sid: StoryId) -> String { et.map(|e| e.class.clone()).filter(|c| !c.is_empty()).or_else(|| pc.get(pf.style.as_str()).cloned()).unwrap_or_else(|| slug(&pf.style)); let text_empty = st.text[r.clone()].trim().is_empty(); let rtl = doc.styles.resolve_para(pf).0.direction == designcraft_doc::TextDirection::RightToLeft; - let _ = write!(out, "<{tag} class=\"{class}\"{}>", if rtl { " dir=\"rtl\"" } else { "" }); + let _ = write!(out, "<{tag} class=\"{}\"{}>", xml_attr(&class), if rtl { " dir=\"rtl\"" } else { "" }); if text_empty { out.push_str(" "); } @@ -353,9 +423,9 @@ pub fn story_html(doc: &Document, sid: StoryId) -> String { None => c.to_string(), }) .collect(); - esc(&sub) + story_markup(&sub) } else { - esc(raw) + story_markup(raw) }; let et = (f.style != story::NO_CHAR_STYLE).then(|| doc.styles.export_tag(&f.style, true)).flatten(); let ctag = et.map(|e| e.tag.as_str()).filter(|t| is_tag(t, true)).unwrap_or("span"); @@ -365,12 +435,12 @@ pub fn story_html(doc: &Document, sid: StoryId) -> String { .filter(|c| !c.is_empty()) .or_else(|| cc.get(f.style.as_str()).cloned()) .unwrap_or_else(|| slug(&f.style)); - format!(" class=\"{class}\"") + format!(" class=\"{}\"", xml_attr(&class)) } else { String::new() }; let style = override_css(doc, &f.over); - let style_attr = if style.is_empty() { String::new() } else { format!(" style=\"{style}\"") }; + let style_attr = if style.is_empty() { String::new() } else { format!(" style=\"{}\"", xml_attr(&style)) }; if cls.is_empty() && style_attr.is_empty() { out.push_str(&t); } else { @@ -495,10 +565,11 @@ fn body_html<'a>( if a.data.is_empty() { continue; } + let mime = safe_mime(&a.mime); // Video and sound: an HTML5 player (with the poster, when there is one). - if let Some(kind) = designcraft_doc::media_kind(&a.mime) { - let name = format!("media/{}.{}", g.asset.0, ext(&a.mime)); - images.insert(name.clone(), (a.mime.as_str(), a.data.as_slice())); + if let Some(kind) = designcraft_doc::media_kind(mime) { + let name = format!("media/{}.{}", g.asset.0, ext(mime)); + images.insert(name.clone(), (mime, a.data.as_slice())); let m = doc.item(*iid).and_then(|i| i.media.clone()).unwrap_or_default(); let mut attrs = String::new(); for (on, attr) in @@ -509,17 +580,23 @@ fn body_html<'a>( } } if let Some(pa) = m.poster.and_then(|p| doc.assets.get(&p)) { - let pn = format!("images/{}.{}", pa.id.0, ext(&pa.mime)); - images.insert(pn.clone(), (pa.mime.as_str(), pa.data.as_slice())); + let poster_mime = safe_mime(&pa.mime); + let pn = format!("images/{}.{}", pa.id.0, ext(poster_mime)); + images.insert(pn.clone(), (poster_mime, pa.data.as_slice())); if kind == "video" { - attrs.push_str(&format!(" poster=\"{}\"", img_src(&pn, &pa.mime, &pa.data))); + attrs.push_str(&format!(" poster=\"{}\"", xml_attr(&img_src(&pn, poster_mime, &pa.data)))); } } - let _ = writeln!(body, "
<{kind} src=\"{}\"{attrs}>{}
", img_src(&name, &a.mime, &a.data), esc(&a.name)); + let _ = writeln!( + body, + "
<{kind} src=\"{}\"{attrs}>{}
", + xml_attr(&img_src(&name, mime, &a.data)), + xml_text(&a.name) + ); continue; } - let name = format!("images/{}.{}", g.asset.0, ext(&a.mime)); - images.insert(name.clone(), (a.mime.as_str(), a.data.as_slice())); + let name = format!("images/{}.{}", g.asset.0, ext(mime)); + images.insert(name.clone(), (mime, a.data.as_slice())); // Alt text from Object Export Options, else the file name. let alt = doc.item(*iid).map(|i| i.alt_text.as_str()).filter(|t| !t.is_empty()).unwrap_or(&a.name); // Object Export Options: alignment and a page break before. @@ -531,8 +608,9 @@ fn body_html<'a>( if eo.page_break_before { css.push_str("page-break-before:always;break-before:page;"); } - let style = if css.is_empty() { String::new() } else { format!(" style=\"{css}\"") }; - let _ = writeln!(body, "\"{}\"/", img_src(&name, &a.mime, &a.data), esc(alt)); + let style = if css.is_empty() { String::new() } else { format!(" style=\"{}\"", xml_attr(&css)) }; + let _ = + writeln!(body, "\"{}\"/", xml_attr(&img_src(&name, mime, &a.data)), xml_attr(alt)); } } } @@ -550,11 +628,12 @@ pub struct HtmlOptions { /// document's stories and graphics in reading order. pub fn export_html(doc: &Document, opts: &HtmlOptions) -> String { let title = opts.title.clone().unwrap_or_else(|| doc.title.clone()); - let lang = opts.language.clone().unwrap_or_else(|| "en".into()); + let language = opts.language.as_deref().unwrap_or("en"); + let lang = language_tag(language); let (body, _, _) = body_html(doc, &|_, mime, data| format!("data:{mime};base64,{}", base64(data))); format!( "\n\n\n\n\n\n{}\n\n\n\n{body}\n\n", - esc(&title), + xml_text(&title), stylesheet(doc) ) } @@ -578,38 +657,38 @@ pub fn export_epub(doc: &Document, opts: &EpubOptions) -> Result, EpubEr let title = opts.title.clone().unwrap_or_else(|| doc.title.clone()); let id = opts.identifier.clone().unwrap_or_else(|| format!("urn:designcraft:{}", slug(&title))); let (body, images, toc) = body_html(doc, &|name, _, _| name.to_string()); - let lang = &opts.language; + let lang = language_tag(&opts.language); let chapter = format!( "\n\n\n{}\n\n{body}\n\n", - esc(&title) + xml_text(&title) ); let mut nav_items = String::new(); for (a, label) in &toc { - let _ = write!(nav_items, "
  • {}
  • ", esc(label)); + let _ = write!(nav_items, "
  • {}
  • ", xml_text(label)); } if nav_items.is_empty() { - nav_items = format!("
  • {}
  • ", esc(&title)); + nav_items = format!("
  • {}
  • ", xml_text(&title)); } let nav = format!( "\n\n\n{}\n\n\n", - esc(&title) + xml_text(&title) ); let mut manifest = String::from( "\n\n\n", ); for (k, (name, (mime, _))) in images.iter().enumerate() { - let _ = writeln!(manifest, ""); + let _ = writeln!(manifest, "", xml_attr(name), xml_attr(mime)); } // Cover: an image page first in reading order. if opts.cover.is_some() { manifest.push_str("\n\n"); } let cover_spine = if opts.cover.is_some() { "\n" } else { "" }; - let author = opts.author.as_deref().map(|a| format!("{}", esc(a))).unwrap_or_default(); + let author = opts.author.as_deref().map(|a| format!("{}", xml_text(a))).unwrap_or_default(); let opf = format!( "\n\n\n{}\n{}\n{lang}{author}\n2026-01-01T00:00:00Z\n\n\n\n{manifest}\n\n{cover_spine}\n\n\n", - esc(&id), - esc(&title) + xml_text(&id), + xml_text(&title) ); let container = "\n\n"; let mut buf = std::io::Cursor::new(Vec::new()); @@ -638,8 +717,8 @@ pub fn export_epub(doc: &Document, opts: &EpubOptions) -> Result, EpubEr z.write_all(c).map_err(io)?; let xhtml = format!( "\n\n\n{}\n\"{}\"/\n\n", - esc(&title), - esc(&title) + xml_text(&title), + xml_attr(&title) ); z.start_file("OEBPS/cover.xhtml", deflate).map_err(zerr)?; z.write_all(xhtml.as_bytes()).map_err(io)?; @@ -653,9 +732,10 @@ pub fn export_epub(doc: &Document, opts: &EpubOptions) -> Result, EpubEr mod tests { use super::*; use designcraft_doc::build::NewDocument; - use designcraft_doc::geom::Rect; - use designcraft_doc::{ParaFormat, SpreadRef}; + use designcraft_doc::geom::{Affine, Rect, shapes}; + use designcraft_doc::{Asset, AssetId, Content, Graphic, Item, ItemId, ParaFormat, Shape, SpreadRef}; use std::io::Read; + use std::sync::Arc; #[test] fn exports_valid_package_in_reading_order() { @@ -734,4 +814,73 @@ mod tests { assert_eq!(base64(b"Ma"), "TWE="); assert_eq!(base64(b"M"), "TQ=="); } + + #[test] + fn metadata_is_serialized_for_its_output_context() { + let mut d = Document::new(&NewDocument::default()); + d.title = "Field Notes & ".into(); + let lid = d.default_layer(); + let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 300.0, 100.0), lid, "A&B \"D\"", ParaFormat::default()).unwrap(); + d.styles_mut() + .export_tags + .insert(format!("p:{}", story::BASIC_PARAGRAPH), designcraft_doc::ExportTag { tag: "h2".into(), class: "Primary \"Copy\"".into() }); + if let Some(basic) = d.styles_mut().paragraph.iter_mut().find(|s| s.name == story::BASIC_PARAGRAPH) { + basic.chars.font_family = Some("Quoted \"Serif\" ".into()); + } + + let aid = AssetId(d.alloc()); + d.assets.insert( + aid, + Arc::new(Asset { + page: 0, + id: aid, + name: "Cover & Notes".into(), + mime: "image/png; profile=screen".into(), + link: None, + data: Arc::new(vec![1]), + pixels: Some((1, 1)), + }), + ); + let mut item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(36.0, 120.0, 72.0, 156.0))); + item.alt_text = "Cover \"A\" & B".into(); + item.content = Content::Graphic(Graphic { + asset: aid, + size: (1.0, 1.0), + xf: Affine::IDENTITY, + auto_fit: Default::default(), + fit_align: 4, + crop: [0.0; 4], + }); + d.insert_item(SpreadRef::Doc(0), item, None).unwrap(); + + let story = story_html(&d, sid); + assert!(story.contains("

    A&B <C> "D"

    ")); + let html = export_html(&d, &HtmlOptions { title: None, language: Some("English (US)".into()) }); + assert!(html.contains("")); + assert!(html.contains("Field Notes & <Edition>")); + assert!(html.contains("alt=\"Cover "A" & B\"")); + assert!(html.contains("src=\"data:image/png;base64,AQ==\"")); + assert!(!html.contains("image/png; profile=screen")); + assert!(!stylesheet(&d).contains("")); + assert!(stylesheet(&d).contains("\\3c Alt\\3e ")); + + let bytes = export_epub( + &d, + &EpubOptions { + title: None, + author: Some("A & B".into()), + language: "English (US)".into(), + identifier: Some("notes&edition".into()), + cover: None, + }, + ) + .unwrap(); + let mut z = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap(); + let mut opf = String::new(); + z.by_name("OEBPS/content.opf").unwrap().read_to_string(&mut opf).unwrap(); + assert!(opf.contains("xml:lang=\"und\"")); + assert!(opf.contains("notes&edition")); + assert!(opf.contains("A & B")); + assert!(opf.contains("media-type=\"image/png\"")); + } } From 4aea57fea7f1c8e0aec6bcef55210d7443a49022 Mon Sep 17 00:00:00 2001 From: thaynej <36243577+thaynej@users.noreply.github.com> Date: Fri, 9 Oct 2026 23:14:27 -0600 Subject: [PATCH 19/24] Word import: keep tracked moved text (w:moveTo) (#257) Text inside a tracked move destination was dropped on .docx import, so moved passages vanished from both places. Treat moveTo like ins (both kept as accepted); moveFrom stays skipped like del. Regression test covers ins, del, moveFrom and moveTo together. Fixes #256. Also adds my contributor credit entry. Co-authored-by: Claude Opus 5.5 --- contributors/people.toml | 3 +++ crates/textimport/src/docx.rs | 23 ++++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/contributors/people.toml b/contributors/people.toml index 89c6db208..c480bd68a 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -21,3 +21,6 @@ real_name = "Brandon Thomas" display_name = "Brandon Thomas" sync_github_name = false + +[people.thaynej] +real_name = "Jeffrey Thayne" diff --git a/crates/textimport/src/docx.rs b/crates/textimport/src/docx.rs index 563eb7289..670f8a0fa 100644 --- a/crates/textimport/src/docx.rs +++ b/crates/textimport/src/docx.rs @@ -276,7 +276,9 @@ impl Ctx { for e in p.els() { match e.name.as_str() { "r" => self.run(e, st, allow_notes), - "hyperlink" | "smartTag" | "ins" | "fldSimple" | "customXml" => self.inline(e, st, allow_notes), + // Tracked changes import as accepted: insertions and move destinations are kept, + // deletions (`del`) and move sources (`moveFrom`) are dropped. + "hyperlink" | "smartTag" | "ins" | "moveTo" | "fldSimple" | "customXml" => self.inline(e, st, allow_notes), _ => {} } } @@ -469,4 +471,23 @@ mod tests { assert_eq!(i.para_styles[0].para.space_before, Some(12.0)); assert_eq!(i.char_styles[0].chars.font_style.as_deref(), Some("Italic")); } + + #[test] + fn tracked_changes_import_as_accepted_including_moves() { + // Regression (#256): text in a tracked move destination (`w:moveTo`) vanished on import. + let document = format!( + r#" + Kept text. + MOVED HERE. + MOVED THEN DELETED + Plain + INSERTED + DELETED + MOVED HERE.End. + "# + ); + let i = import(&docx(&document, "", "")).unwrap(); + i.story.check().unwrap(); + assert_eq!(i.story.text, "Kept text. MOVED HERE. Plain INSERTED\nEnd."); + } } From ecadfcee3e266eb84333fd9310b9e87116acaff9 Mon Sep 17 00:00:00 2001 From: thaynej <36243577+thaynej@users.noreply.github.com> Date: Fri, 9 Oct 2026 23:14:32 -0600 Subject: [PATCH 20/24] Autoflow: add only the pages breaks ask for (#266) A frame that a column, frame or page break ends early held only a few characters, and autoflow took that as the rate frames fill at: placing text that starts with a page break added a page per few characters (33 pages for 98 characters, 271 for a one-page Word section). The estimate now comes from full frames only; with none yet, one page is added and the story measured again. Regression test covers a leading break and a break between every paragraph. Fixes #262. Claude-Session: https://claude.ai/code/session_01GLcnoDFjqsh5x3MzVbfZeb Co-authored-by: Claude Opus 5.5 --- crates/engine/src/cmd/place_text.rs | 51 ++++++++++++++++++++++++----- 1 file changed, 42 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/place_text.rs b/crates/engine/src/cmd/place_text.rs index 766811b50..97917ee3b 100644 --- a/crates/engine/src/cmd/place_text.rs +++ b/crates/engine/src/cmd/place_text.rs @@ -105,27 +105,37 @@ fn strip(story: &mut Story) { story.format_chars(0..n, |f| *f = Default::default()); } -/// Is the story overset in its frames, and how much of it do its frames show? -fn fit(d: &Document, sid: StoryId) -> (Option, usize) { +/// Is the story overset in its frames, and how much text do its full frames hold (bytes, frames)? +/// A frame a column, frame or page break ends early is left out: it says nothing about how much +/// a frame holds. +fn fit(d: &Document, sid: StoryId) -> (Option, usize, usize) { let cs = designcraft_compose::compose_story(d, sid, &Default::default()); - let shown = cs.frames.iter().map(|f| f.range.end).max().unwrap_or(0); - (cs.overset_at, shown) + let text = d.story(sid).map_or("", |s| s.text.as_str()); + let is_break = |c: char| matches!(c, designcraft_doc::COLUMN_BREAK | designcraft_doc::FRAME_BREAK | designcraft_doc::PAGE_BREAK); + let (mut held, mut full) = (0, 0); + for f in &cs.frames { + let Some(shown) = text.get(f.range.clone()) else { continue }; + if !shown.is_empty() && !shown.chars().any(is_break) { + held += shown.len(); + full += 1; + } + } + (cs.overset_at, held, full) } /// Thread new frames on new pages (margin rectangles) until the story fits. Returns pages added. pub(crate) fn autoflow(d: &mut Document, sid: StoryId, max_pages: usize) -> Result { let mut added = 0; loop { - let (overset, shown) = fit(d, sid); + let (overset, held, full) = fit(d, sid); let Some(at) = overset else { return Ok(added) }; if added >= max_pages { return Err(bad("file.place", format!("autoflow stopped after {max_pages} pages"))); } let len = d.story(sid).map_or(0, |s| s.len()); - let frames = d.story(sid).map_or(1, |s| s.frames.len()).max(1); - // Frames still needed at the rate the existing ones are filled (at least one). - let per_frame = (shown.max(at) / frames).max(1); - let want = (len - at).div_ceil(per_frame).clamp(1, max_pages - added); + // Frames still needed at the rate the full ones are filled (at least one); with no full + // frame to go by yet, one more page. + let want = held.checked_div(full).map_or(1, |per_frame| len.saturating_sub(at).div_ceil(per_frame.max(1))).clamp(1, max_pages - added); let last = *d.story(sid).and_then(|s| s.frames.last()).ok_or_else(|| bad("file.place", "the story has no frame"))?; let mut page = d.page_of_item(last).unwrap_or(d.page_count().saturating_sub(1)); let parent = d.page_loc(page).and_then(|(si, pi)| d.spreads[si].pages[pi].parent); @@ -258,6 +268,29 @@ mod tests { assert_eq!(st.format_after(6).over.font_style.as_deref(), Some("Bold")); let _ = std::fs::remove_dir_all(&dir); } + + #[test] + fn autoflow_adds_only_the_pages_breaks_ask_for() { + // Regression (#262): a frame a break ends early made autoflow take it for a frame that + // holds a few characters, and add a page per few characters left (33 for this text). + let dir = std::env::temp_dir().join(format!("dc-place-breaks-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for (name, rtf, pages) in [ + ("lead.rtf", r"{\rtf1 \page\par A Short Heading\par First short paragraph.\par Second short paragraph.\par}", 2), + ("each.rtf", r"{\rtf1 One\par\page\par Two\par\page\par Three\par\page\par Four\par}", 4), + ] { + let path = dir.join(name); + std::fs::write(&path, rtf).unwrap(); + let mut s = Session::new(); + s.execute("file.new", &json!({"pages": 1})).unwrap(); + let r = s.execute("file.place", &json!({"path": path.to_string_lossy(), "autoflow": true})).unwrap(); + assert_eq!(r["overset"], false, "{name}: {r}"); + let d = &s.doc().unwrap().doc; + assert_eq!(d.page_count(), pages, "{name}: {r}"); + assert_eq!(d.story(StoryId(r["story"].as_u64().unwrap())).unwrap().frames.len(), pages, "{name}"); + } + let _ = std::fs::remove_dir_all(&dir); + } } #[cfg(test)] From a9326be31898aa350baa0396f2a2f35521885dae Mon Sep 17 00:00:00 2001 From: kubuntugamer <52578831+kubuntugamer@users.noreply.github.com> Date: Sat, 10 Oct 2026 00:14:38 -0500 Subject: [PATCH 21/24] fix(engine): object.opacity accepts its documented lowercase blend modes (#275) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `object.opacity` documents `blend?: normal|multiply|…`, but parsed the value with `serde_json::from_value`, which only accepts the enum's PascalCase variant names. Every documented lowercase form was silently dropped: the command returned `{"changed": 1}` while the stored blend stayed as it was, so a client following the parameter description could save and export the previous appearance without any error (#260). Parse with the codebase's own `BlendMode::parse`, which is already case-, space-, underscore- and hyphen-insensitive and covered by tests, so `multiply`, `MULTIPLY`, `Color Burn`, `soft_light` and the serialized `Multiply` all resolve to the same mode. An unrecognized value is now an error rather than a silent no-op, matching how sibling commands treat a bad parameter — restoring `normal` after `Multiply` really does go back to Normal. Three tests in `blend_mode_tests`: the documented forms apply, the PascalCase names the Properties panel submits still apply, and an unknown value is rejected without changing the item. Fixes #260 🤖 Generated with Codebuff Co-authored-by: Codebuff --- crates/engine/src/cmd/object.rs | 76 ++++++++++++++++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/object.rs b/crates/engine/src/cmd/object.rs index dba63ca70..7e219f29f 100644 --- a/crates/engine/src/cmd/object.rs +++ b/crates/engine/src/cmd/object.rs @@ -4,6 +4,7 @@ use std::collections::HashMap; use std::sync::Arc; +use designcraft_color::BlendMode; use designcraft_doc::{ Content, Document, Fill, Item, ItemId, ParaFormat, Selection, Shape, SpreadRef, Story, StoryId, Stroke, TextFrame, TextFrameOptions, TextSel, }; @@ -219,7 +220,16 @@ pub fn specs() -> Vec { ), cmd!("object.opacity", "Opacity", [], None, "{opacity: 0..1, blend?: normal|multiply|…, ids?}", has_selection, |s, p| { let o = f64_or(p, "opacity", 1.0).clamp(0.0, 1.0) as f32; - let blend = p.get("blend").and_then(|b| serde_json::from_value(b.clone()).ok()); + // `BlendMode::parse` takes the documented lowercase forms (`multiply`), the panel + // labels (`Color Burn`) and the serialized names (`Multiply`). An unknown value is + // an error rather than a silent no-op that still reports `changed` (#260). + let blend = match p.get("blend") { + None | Some(Value::Null) => None, + Some(v) => { + let raw = v.as_str().ok_or_else(|| bad("object.opacity", "blend must be a string"))?; + Some(BlendMode::parse(raw).ok_or_else(|| bad("object.opacity", format!("unknown blend mode `{raw}`")))?) + } + }; set_flag( s, p, @@ -2422,3 +2432,67 @@ mod named_target_tests { assert_eq!(s.execute("conveyor.collect", &json!({"id": r["id"]})).unwrap()["count"], 1); } } + +#[cfg(test)] +mod blend_mode_tests { + use designcraft_color::BlendMode; + + use super::*; + + /// `object.opacity` documents `blend?: normal|multiply|…`, but deserializing the value + /// against the enum only accepted the PascalCase variant names, so the documented + /// lowercase forms were silently dropped: the command reported `changed: 1` while the + /// stored blend stayed as it was (#260). + #[test] + fn lowercase_documented_blend_modes_apply() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "unassigned"})).unwrap(); + let id = ItemId(r["id"].as_u64().unwrap()); + let blend = |s: &Session| s.doc().unwrap().doc.item(id).map(|i| i.blend); + + for (given, want) in [ + ("multiply", BlendMode::Multiply), + ("screen", BlendMode::Screen), + ("MULTIPLY", BlendMode::Multiply), + ("Color Burn", BlendMode::ColorBurn), + ("color-burn", BlendMode::ColorBurn), + ("soft_light", BlendMode::SoftLight), + ("normal", BlendMode::Normal), + ] { + let out = s.execute("object.opacity", &json!({"opacity": 1, "blend": given})).unwrap(); + assert_eq!(out["changed"], 1, "{given}"); + assert_eq!(blend(&s), Some(want), "blend mode {given:?} must be applied"); + } + } + + /// The PascalCase names keep working, so the Properties panel's own submissions are + /// unaffected. + #[test] + fn pascal_case_blend_modes_still_apply() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "unassigned"})).unwrap(); + let id = ItemId(r["id"].as_u64().unwrap()); + s.execute("object.opacity", &json!({"opacity": 0.5, "blend": "Multiply"})).unwrap(); + let it = s.doc().unwrap().doc.item(id).cloned().unwrap(); + assert_eq!(it.blend, BlendMode::Multiply); + assert!((it.opacity - 0.5).abs() < 1e-6, "opacity must still be set"); + } + + /// A blend mode the command doesn't know is an error, not a silent success that leaves + /// the previous appearance in place. + #[test] + fn an_unknown_blend_mode_is_an_error() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let r = s.execute("frame.create", &json!({"rect": [36, 36, 300, 300], "content": "unassigned"})).unwrap(); + let id = ItemId(r["id"].as_u64().unwrap()); + s.execute("object.opacity", &json!({"opacity": 1, "blend": "Multiply"})).unwrap(); + let e = s.execute("object.opacity", &json!({"opacity": 1, "blend": "sparkle"})).unwrap_err().to_string(); + assert!(e.contains("sparkle") && e.contains("blend"), "{e}"); + let it = s.doc().unwrap().doc.item(id).cloned().unwrap(); + assert_eq!(it.blend, BlendMode::Multiply, "a rejected value changes nothing"); + assert_eq!(it.opacity, 1.0); + } +} From 54a4a8d4aed50df5674f8cc488f4807d01d6a2b1 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:14:43 -0400 Subject: [PATCH 22/24] Fonts: the Document Fonts folder is found whatever its case (#287) Packages name the folder `Document fonts`; on a case-sensitive file system, opening a document beside it loaded none of its fonts. The exact name still wins when both exist. --- crates/engine/src/cmd/file.rs | 37 ++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 767c62280..267ea5d88 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -185,7 +185,7 @@ pub(crate) fn load_document_fonts(d: &mut Document, path: &str) -> (Option (Option std::path::PathBuf { + use designcraft_fonts::DOCUMENT_FONTS_FOLDER; + let exact = dir.join(DOCUMENT_FONTS_FOLDER); + if exact.is_dir() { + return exact; + } + std::fs::read_dir(dir) + .into_iter() + .flatten() + .flatten() + .find(|e| e.file_name().to_str().is_some_and(|n| n.eq_ignore_ascii_case(DOCUMENT_FONTS_FOLDER)) && e.path().is_dir()) + .map_or(exact, |e| e.path()) +} + fn file_open_bytes(s: &mut Session, p: &Value) -> Result { let b = base64_decode(str_param(p, "base64").unwrap_or("")); // IDML packages are recognised by their stored `mimetype` first entry. @@ -795,6 +812,24 @@ mod document_fonts_tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn the_document_fonts_folder_is_found_whatever_its_case() { + const FAMILY: &str = "DocFont Case Test"; + let dir = std::env::temp_dir().join(format!("dc-open-docfonts-case-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let fonts = dir.join("Document fonts"); + std::fs::create_dir_all(&fonts).unwrap(); + std::fs::write(fonts.join("case.ttf"), font_with(FAMILY, &['H']).unwrap()).unwrap(); + let path = dir.join("Brochure.idml"); + write_document(&path, FAMILY); + + let mut s = Session::new(); + let r = open(&mut s, &path); + assert_eq!(r["documentFonts"], 1, "{r}"); + assert_eq!(font_entry(&mut s, FAMILY)["missing"], false); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn a_document_without_the_folder_opens_as_before() { let dir = std::env::temp_dir().join(format!("dc-open-docfonts-none-{}", std::process::id())); From 6a331e671235781482473ef714ab5e966365512b Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:14:48 -0400 Subject: [PATCH 23/24] UI: Quick Apply opens without running an entry; rows are left-aligned (#239) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * UI: the Quick Apply shortcut doesn't also run its first entry Cmd+Return opened Quick Apply, and in the same frame the list saw the same press as Enter and ran its first entry (New Document). A key press that fires a command shortcut is now consumed, so nothing else handles it that frame. This also stops Cmd+Return from inserting a paragraph break while typing. * UI: Quick Apply rows are left-aligned Rows without a shortcut or style kind were drawn with their label centred, because add_sized lays a button out centred and only the rows with a shortcut have an element that fills the remaining width. Each row is now laid out left to right in a fixed 460×22 area. * UI: Quick Apply runs its first entry only on a fresh Return Pressing Cmd+Return again while Quick Apply is open, or holding it until it repeats, reached the palette as Enter and ran the first entry. The palette now counts only a Return press that isn't a repeat and has no Cmd. --- crates/ui-egui/src/menus.rs | 90 ++++++++++++++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 2a04e7cdd..32cc48db1 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1934,6 +1934,9 @@ pub fn shortcuts(app: &mut DesignApp, ctx: &egui::Context) { if app.native_shortcuts.contains(&id) && !app.ui.shortcuts.contains_key(&id) { continue; // The native menu handles it. } + // The key press belongs to the shortcut: what it opens (Quick Apply's list, a dialog's + // default button) must not see the same press as Enter or Space this frame. + ctx.input_mut(|i| i.consume_key(modifiers, key)); // Like choosing the menu item: "…" commands open their dialog. activate(app, &id, &Value::Null); continue; @@ -1969,6 +1972,13 @@ pub fn palette(app: &mut DesignApp, ctx: &egui::Context) { ); r.request_focus(); let items = quick_apply_items(&app.session, &q); + // Only a fresh Return runs the first entry: ⌘Return pressed again or held down (repeats) is + // the shortcut, not a choice. + let enter = ui.input(|i| { + i.events + .iter() + .any(|e| matches!(e, egui::Event::Key { key: egui::Key::Enter, pressed: true, repeat: false, modifiers, .. } if !modifiers.command)) + }); egui::ScrollArea::vertical().max_height(340.0).show(ui, |ui| { for (i, it) in items.iter().enumerate() { let mut b = egui::Button::new(it.label.as_str()).frame(false); @@ -1977,7 +1987,13 @@ pub fn palette(app: &mut DesignApp, ctx: &egui::Context) { } else if !it.kind.is_empty() { b = b.shortcut_text(it.kind); } - if ui.add_sized([460.0, 22.0], b).clicked() || (i == 0 && ui.input(|i| i.key_pressed(egui::Key::Enter))) { + // The button aligns its label by the layout it's in: left, like the rows with a shortcut. + let size = egui::vec2(460.0, 22.0); + let row = + ui.allocate_ui_with_layout(size, egui::Layout::left_to_right(egui::Align::Center).with_main_align(egui::Align::Min), |ui| { + ui.add(b.min_size(size)) + }); + if row.inner.clicked() || (i == 0 && enter) { run = Some((it.id.clone(), it.params.clone())); } } @@ -2418,6 +2434,78 @@ mod tests { assert_eq!(app.session.tool_id(), "rectangleFrame"); } + #[test] + fn the_quick_apply_shortcut_opens_it_without_running_an_entry() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + let ctx = egui::Context::default(); + let frame = |app: &mut crate::DesignApp, events: Vec| { + let input = egui::RawInput { + screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), + events, + ..Default::default() + }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + }; + let cmd_return = + |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::COMMAND }; + frame(&mut app, vec![]); + frame(&mut app, vec![]); + frame(&mut app, vec![cmd_return(true), cmd_return(false)]); + frame(&mut app, vec![]); + assert_eq!(app.ui.palette.as_deref(), Some(""), "Quick Apply stays open"); + assert_eq!(app.session.documents().len(), 1, "the first entry (New Document) didn't run"); + // Pressing the shortcut again, or holding it until it repeats, doesn't run it either. + frame(&mut app, vec![cmd_return(true), cmd_return(false)]); + let repeat = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: true, modifiers: egui::Modifiers::COMMAND }; + frame(&mut app, vec![repeat, cmd_return(false)]); + assert_eq!(app.ui.palette.as_deref(), Some(""), "Quick Apply stays open"); + assert_eq!(app.session.documents().len(), 1, "a second ⌘Return or a repeat doesn't run the first entry"); + // A plain Return still does. + let enter = + |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE }; + frame(&mut app, vec![enter(true), enter(false)]); + assert_eq!(app.ui.palette, None, "Return runs the first entry and closes Quick Apply"); + assert_eq!(app.session.documents().len(), 2); + } + + #[test] + fn quick_apply_rows_are_left_aligned() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", &json!({})).unwrap(); + app.ui.palette = Some(String::new()); + let ctx = egui::Context::default(); + let mut shapes = Vec::new(); + for _ in 0..3 { + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }); + out.textures_delta.clear(); + shapes = out.shapes; + } + let label_x = |label: &str| { + // The palette is painted last, over anything else with the same text. + shapes.iter().rev().find_map(|s| match &s.shape { + egui::Shape::Text(t) if t.galley.text() == label => Some(t.pos.x), + _ => None, + }) + }; + // Rows that show a shortcut or a style kind, and rows that show neither, among the first visible ones. + let items = quick_apply_items(&app.session, ""); + let first = items.iter().take(10); + let plain = first.clone().find(|it| it.shortcut.is_none() && it.kind.is_empty()).expect("a row without a shortcut"); + let with_sc = first.clone().find(|it| it.shortcut.is_some()).expect("a row with a shortcut"); + let (a, b) = (label_x(&plain.label).expect("plain row drawn"), label_x(&with_sc.label).expect("shortcut row drawn")); + assert!((a - b).abs() < 0.5, "{:?} at x {a}, {:?} at x {b}", plain.label, with_sc.label); + } + #[test] fn sample_scripts_run() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); From 4fbf8938bf922b29602ef6e6e0984a229a8b994a Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:14:54 -0400 Subject: [PATCH 24/24] UI: the shortcut recorder waits for the key; Interactive for PDF and Digital Publishing open their panels (#264) * Keyboard Shortcuts: the recorder waits for the key pressed with the modifiers * Workspaces: Interactive for PDF and Digital Publishing open their own panels --- crates/ui-egui/src/dialogs.rs | 25 +++++++++++++++++++++++-- crates/ui-egui/src/menus.rs | 24 +++++++++++++++++++++++- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index f44503f7c..44edebb0c 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -144,6 +144,11 @@ fn user_dictionary(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { }); } +fn is_modifier_key(key: egui::Key) -> bool { + use egui::Key::*; + matches!(key, ShiftLeft | ShiftRight | ControlLeft | ControlRight | AltLeft | AltRight | SuperLeft | SuperRight) +} + fn keyboard_shortcuts(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { let mut q = d.s("query"); ui.add( @@ -153,11 +158,12 @@ fn keyboard_shortcuts(app: &mut DesignApp, ui: &mut egui::Ui, d: &mut Dialog) { ); d.fields.insert("query".into(), json!(q)); let recording = d.s("recording"); - // Capture the next key press for the command being recorded. + // Capture the next key press for the command being recorded. Pressing a modifier + // reports the modifier itself as a key; skip it and wait for the key it modifies. if !recording.is_empty() { let pressed = ui.input(|i| { i.events.iter().find_map(|e| match e { - egui::Event::Key { key, pressed: true, modifiers, .. } => Some((*key, *modifiers)), + egui::Event::Key { key, pressed: true, modifiers, .. } if !is_modifier_key(*key) => Some((*key, *modifiers)), _ => None, }) }); @@ -2767,4 +2773,19 @@ mod tests { let _ = command_fields(c.params); } } + + #[test] + fn shortcut_recorder_waits_for_the_key_after_its_modifiers() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + let mut d = Dialog::new("keyboardShortcuts", json!({"query": "", "recording": "app.palette"})); + let ctx = egui::Context::default(); + let key = |key, modifiers| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }; + // Holding Ctrl reports Ctrl itself as a key press, then Ctrl+K arrives. + for event in [key(egui::Key::ControlLeft, egui::Modifiers::COMMAND), key(egui::Key::K, egui::Modifiers::COMMAND)] { + let input = egui::RawInput { events: vec![event], ..Default::default() }; + ctx.run_ui(input, |ui| keyboard_shortcuts(&mut app, ui, &mut d)).textures_delta.clear(); + } + assert_eq!(crate::menus::shortcut_of(&app, "app.palette").as_deref(), Some("Cmd+K")); + assert_eq!(d.s("recording"), "", "recording ends with the recorded shortcut"); + } } diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 32cc48db1..43795f61a 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -1360,10 +1360,20 @@ pub fn run_ui(app: &mut DesignApp, id: &str, p: &Value) -> Option Some("properties"), + "Interactive for PDF" | "Digital Publishing" => Some("pages"), + _ => None, + }; + if let Some(tab) = dock_tab { + app.ui.dock_tab = tab.into(); + app.ui.dock_expanded = true; + } app.ui.open_panel = match name { "Typography" => Some("paragraphStyles".into()), "Printing and Proofing" => Some("swatches".into()), + "Interactive for PDF" => Some("buttons".into()), + "Digital Publishing" => Some("liquid".into()), _ => None, }; app.ui.workspace = name.to_string(); @@ -2738,6 +2748,18 @@ mod tests { assert_eq!(app.ui.workspace, "Essentials"); } + #[test] + fn interactive_workspaces_show_their_panels() { + let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()); + app.ui.dock_expanded = false; + run_ui(&mut app, "window.workspace", &json!({"name": "Interactive for PDF"})).unwrap().unwrap(); + assert_eq!((app.ui.dock_tab.as_str(), app.ui.dock_expanded, app.ui.open_panel.as_deref()), ("pages", true, Some("buttons"))); + run_ui(&mut app, "window.workspace", &json!({"name": "Digital Publishing"})).unwrap().unwrap(); + assert_eq!((app.ui.dock_tab.as_str(), app.ui.open_panel.as_deref()), ("pages", Some("liquid"))); + run_ui(&mut app, "window.workspace", &json!({"name": "Essentials"})).unwrap().unwrap(); + assert_eq!(app.ui.open_panel, None); + } + #[test] fn hide_and_show_menu_items() { let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());